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    /// and SHOULD NOT send other `session/update` notifications caused by applying them
1323    /// before it responds.
1324    #[cfg(feature = "unstable_session_options")]
1325    #[serde_as(deserialize_as = "DefaultOnNull")]
1326    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1327    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1328    pub config_options: Vec<InitialSessionConfigOption>,
1329    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1330    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1331    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1332    ///
1333    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1334    #[serde_as(deserialize_as = "DefaultOnError")]
1335    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1336    #[serde(default)]
1337    #[serde(rename = "_meta")]
1338    pub meta: Option<Meta>,
1339}
1340
1341impl NewSessionRequest {
1342    /// Builds [`NewSessionRequest`] with the required request fields set. Optional fields start unset or empty.
1343    #[must_use]
1344    pub fn new(cwd: impl Into<AbsolutePath>) -> Self {
1345        Self {
1346            cwd: cwd.into(),
1347            additional_directories: vec![],
1348            mcp_servers: vec![],
1349            system_prompt: None,
1350            #[cfg(feature = "unstable_session_options")]
1351            config_options: vec![],
1352            meta: None,
1353        }
1354    }
1355
1356    /// Additional workspace roots for this session. Each path must be absolute.
1357    #[must_use]
1358    pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1359    where
1360        I: IntoIterator<Item = P>,
1361        P: Into<AbsolutePath>,
1362    {
1363        self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1364        self
1365    }
1366
1367    /// List of MCP (Model Context Protocol) servers the agent should connect to.
1368    #[must_use]
1369    pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1370        self.mcp_servers = mcp_servers;
1371        self
1372    }
1373
1374    /// System-level instructions for the new session.
1375    #[must_use]
1376    pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1377        self.system_prompt = system_prompt.into_option();
1378        self
1379    }
1380
1381    /// **UNSTABLE**
1382    ///
1383    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1384    ///
1385    /// Initial values for the session's config options.
1386    ///
1387    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1388    /// this when the Agent advertises `session.options`.
1389    ///
1390    /// The Agent applies the entries in list order, as if the Client had called
1391    /// `session/set_config_option` for each entry after the session was set up. Malformed
1392    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1393    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1394    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1395    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries,
1396    /// and SHOULD NOT send other `session/update` notifications caused by applying them
1397    /// before it responds.
1398    #[cfg(feature = "unstable_session_options")]
1399    #[must_use]
1400    pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1401        self.config_options = config_options;
1402        self
1403    }
1404
1405    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1406    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1407    /// do not recognize.
1408    ///
1409    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1410    #[must_use]
1411    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1412        self.meta = meta.into_option();
1413        self
1414    }
1415}
1416
1417/// Response from creating a new session.
1418///
1419/// New sessions default to `idle` until a state update reports otherwise.
1420/// Updates may arrive before or after this response. Clients MUST NOT overwrite
1421/// an already-reported state when the response arrives.
1422///
1423/// See protocol docs: [Creating a Session](https://agentclientprotocol.com/protocol/v2/session-setup#creating-a-session)
1424#[serde_as]
1425#[skip_serializing_none]
1426#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1427#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1428#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_NEW_METHOD_NAME)))]
1429#[serde(rename_all = "camelCase")]
1430#[non_exhaustive]
1431pub struct NewSessionResponse {
1432    /// Unique identifier for the created session.
1433    ///
1434    /// Used in all subsequent requests for this conversation.
1435    pub session_id: SessionId,
1436    /// Initial session configuration options.
1437    ///
1438    /// Optional. Omitted or empty means no config options are advertised.
1439    /// Senders MUST use an array, not `null`. Receivers treat `null` like omission.
1440    /// Later `config_option_update` notifications replace this list.
1441    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1442    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1443    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1444    pub config_options: Vec<SessionConfigOption>,
1445    /// Initial commands the agent can execute in this session.
1446    ///
1447    /// Optional. Omitted or empty means no initial commands are advertised.
1448    /// Senders MUST use an array, not `null`. Receivers treat `null` like omission.
1449    /// Later `available_commands_update` notifications replace this list.
1450    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1451    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1452    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1453    pub available_commands: Vec<AvailableCommand>,
1454    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1455    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1456    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1457    ///
1458    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1459    #[serde_as(deserialize_as = "DefaultOnError")]
1460    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1461    #[serde(default)]
1462    #[serde(rename = "_meta")]
1463    pub meta: Option<Meta>,
1464}
1465
1466impl NewSessionResponse {
1467    /// Builds [`NewSessionResponse`] with the required response fields set. Optional fields start unset or empty.
1468    #[must_use]
1469    pub fn new(session_id: impl Into<SessionId>) -> Self {
1470        Self {
1471            session_id: session_id.into(),
1472            config_options: Vec::new(),
1473            available_commands: Vec::new(),
1474            meta: None,
1475        }
1476    }
1477
1478    /// Initial session configuration options.
1479    ///
1480    /// Optional. Omitted or empty means no config options are advertised.
1481    /// Senders MUST use an array, not `null`. Receivers treat `null` like omission.
1482    /// Later `config_option_update` notifications replace this list.
1483    #[must_use]
1484    pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
1485        self.config_options = config_options;
1486        self
1487    }
1488
1489    /// Initial commands the agent can execute in this session.
1490    #[must_use]
1491    pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
1492        self.available_commands = available_commands;
1493        self
1494    }
1495
1496    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1497    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1498    /// do not recognize.
1499    ///
1500    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1501    #[must_use]
1502    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1503        self.meta = meta.into_option();
1504        self
1505    }
1506}
1507
1508// Fork session
1509
1510/// **UNSTABLE**
1511///
1512/// This capability is not part of the spec yet, and may be removed or changed at any point.
1513///
1514/// Request parameters for forking an existing session.
1515///
1516/// Creates a new session based on the context of an existing one, allowing
1517/// operations like generating summaries without affecting the original session's history.
1518///
1519/// Only available if the Agent supports the `session.fork` capability.
1520#[cfg(feature = "unstable_session_fork")]
1521#[serde_as]
1522#[skip_serializing_none]
1523#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1524#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1525#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_FORK_METHOD_NAME)))]
1526#[serde(rename_all = "camelCase")]
1527#[non_exhaustive]
1528pub struct ForkSessionRequest {
1529    /// The ID of the session to fork.
1530    pub session_id: SessionId,
1531    /// The working directory for this session. Must be an absolute path.
1532    pub cwd: AbsolutePath,
1533    /// Additional workspace roots to activate for this session. Each path must be absolute.
1534    ///
1535    /// When omitted or empty, no additional roots are activated. When non-empty,
1536    /// this is the complete resulting additional-root list for the forked
1537    /// session.
1538    #[serde_as(deserialize_as = "DefaultOnNull")]
1539    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1540    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1541    pub additional_directories: Vec<AbsolutePath>,
1542    /// List of MCP servers to connect to for this session.
1543    #[serde_as(deserialize_as = "DefaultOnNull")]
1544    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1545    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1546    pub mcp_servers: Vec<McpServer>,
1547    /// System-level instructions for the forked session.
1548    ///
1549    /// Optional. Omitted and `null` are equivalent. The Agent may then keep a
1550    /// system prompt it stored with the source session or use its default
1551    /// instructions. Clients MUST only send this when the Agent advertises
1552    /// `session.systemPrompt`, and SHOULD send the same value they used for the
1553    /// source session.
1554    #[serde(default)]
1555    pub system_prompt: Option<SystemPrompt>,
1556    /// **UNSTABLE**
1557    ///
1558    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1559    ///
1560    /// Initial values for the forked session's config options.
1561    ///
1562    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1563    /// this when the Agent advertises `session.options`.
1564    ///
1565    /// The Agent applies the entries in list order on top of the configuration the fork
1566    /// starts with, as if the Client had called `session/set_config_option` for each entry
1567    /// after the session was set up. Malformed entries and duplicate `configId` values fail
1568    /// the request with `-32602`. The Agent MUST ignore an entry whose `configId` is unknown,
1569    /// whose `type` does not match the option, or whose value is not allowed when it is
1570    /// applied. The `configOptions` in the response contain the values the session actually
1571    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries,
1572    /// and SHOULD NOT send other `session/update` notifications caused by applying them
1573    /// before it responds.
1574    #[cfg(feature = "unstable_session_options")]
1575    #[serde_as(deserialize_as = "DefaultOnNull")]
1576    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1577    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1578    pub config_options: Vec<InitialSessionConfigOption>,
1579    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1580    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1581    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1582    ///
1583    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1584    #[serde_as(deserialize_as = "DefaultOnError")]
1585    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1586    #[serde(default)]
1587    #[serde(rename = "_meta")]
1588    pub meta: Option<Meta>,
1589}
1590
1591#[cfg(feature = "unstable_session_fork")]
1592impl ForkSessionRequest {
1593    /// Builds [`ForkSessionRequest`] with the required request fields set. Optional fields start unset or empty.
1594    #[must_use]
1595    pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
1596        Self {
1597            session_id: session_id.into(),
1598            cwd: cwd.into(),
1599            additional_directories: vec![],
1600            mcp_servers: vec![],
1601            system_prompt: None,
1602            #[cfg(feature = "unstable_session_options")]
1603            config_options: vec![],
1604            meta: None,
1605        }
1606    }
1607
1608    /// Additional workspace roots to activate for this session. Each path must be absolute.
1609    #[must_use]
1610    pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1611    where
1612        I: IntoIterator<Item = P>,
1613        P: Into<AbsolutePath>,
1614    {
1615        self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1616        self
1617    }
1618
1619    /// List of MCP servers to connect to for this session.
1620    #[must_use]
1621    pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1622        self.mcp_servers = mcp_servers;
1623        self
1624    }
1625
1626    /// System-level instructions for the forked session.
1627    #[must_use]
1628    pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1629        self.system_prompt = system_prompt.into_option();
1630        self
1631    }
1632
1633    /// **UNSTABLE**
1634    ///
1635    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1636    ///
1637    /// Initial values for the forked session's config options.
1638    ///
1639    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1640    /// this when the Agent advertises `session.options`.
1641    ///
1642    /// The Agent applies the entries in list order on top of the configuration the fork
1643    /// starts with, as if the Client had called `session/set_config_option` for each entry
1644    /// after the session was set up. Malformed entries and duplicate `configId` values fail
1645    /// the request with `-32602`. The Agent MUST ignore an entry whose `configId` is unknown,
1646    /// whose `type` does not match the option, or whose value is not allowed when it is
1647    /// applied. The `configOptions` in the response contain the values the session actually
1648    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries,
1649    /// and SHOULD NOT send other `session/update` notifications caused by applying them
1650    /// before it responds.
1651    #[cfg(feature = "unstable_session_options")]
1652    #[must_use]
1653    pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1654        self.config_options = config_options;
1655        self
1656    }
1657
1658    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1659    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1660    /// do not recognize.
1661    ///
1662    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1663    #[must_use]
1664    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1665        self.meta = meta.into_option();
1666        self
1667    }
1668}
1669
1670/// **UNSTABLE**
1671///
1672/// This capability is not part of the spec yet, and may be removed or changed at any point.
1673///
1674/// Response from forking an existing session.
1675#[cfg(feature = "unstable_session_fork")]
1676#[serde_as]
1677#[skip_serializing_none]
1678#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1679#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1680#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_FORK_METHOD_NAME)))]
1681#[serde(rename_all = "camelCase")]
1682#[non_exhaustive]
1683pub struct ForkSessionResponse {
1684    /// Unique identifier for the newly created forked session.
1685    pub session_id: SessionId,
1686    /// Initial session configuration options.
1687    ///
1688    /// Optional. Omitted or empty means no config options are advertised.
1689    /// Senders MUST use an array, not `null`. Receivers treat `null` like omission.
1690    /// Later `config_option_update` notifications replace this list.
1691    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1692    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1693    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1694    pub config_options: Vec<SessionConfigOption>,
1695    /// Initial commands the agent can execute in this session.
1696    ///
1697    /// Optional. Omitted or empty means no initial commands are advertised.
1698    /// Senders MUST use an array, not `null`. Receivers treat `null` like omission.
1699    /// Later `available_commands_update` notifications replace this list.
1700    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1701    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1702    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1703    pub available_commands: Vec<AvailableCommand>,
1704    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1705    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1706    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1707    ///
1708    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1709    #[serde_as(deserialize_as = "DefaultOnError")]
1710    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1711    #[serde(default)]
1712    #[serde(rename = "_meta")]
1713    pub meta: Option<Meta>,
1714}
1715
1716#[cfg(feature = "unstable_session_fork")]
1717impl ForkSessionResponse {
1718    /// Builds [`ForkSessionResponse`] with the required response fields set. Optional fields start unset or empty.
1719    #[must_use]
1720    pub fn new(session_id: impl Into<SessionId>) -> Self {
1721        Self {
1722            session_id: session_id.into(),
1723            config_options: Vec::new(),
1724            available_commands: Vec::new(),
1725            meta: None,
1726        }
1727    }
1728
1729    /// Initial session configuration options.
1730    ///
1731    /// Optional. Omitted or empty means no config options are advertised.
1732    /// Senders MUST use an array, not `null`. Receivers treat `null` like omission.
1733    /// Later `config_option_update` notifications replace this list.
1734    #[must_use]
1735    pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
1736        self.config_options = config_options;
1737        self
1738    }
1739
1740    /// Initial commands the agent can execute in this session.
1741    #[must_use]
1742    pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
1743        self.available_commands = available_commands;
1744        self
1745    }
1746
1747    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1748    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1749    /// do not recognize.
1750    ///
1751    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1752    #[must_use]
1753    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1754        self.meta = meta.into_option();
1755        self
1756    }
1757}
1758
1759// Resume session
1760
1761/// Request parameters for resuming an existing session.
1762///
1763/// Resumes an existing session and optionally replays retained conversation
1764/// history according to `replayFrom`.
1765#[serde_as]
1766#[skip_serializing_none]
1767#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1768#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1769#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_RESUME_METHOD_NAME)))]
1770#[serde(rename_all = "camelCase")]
1771#[non_exhaustive]
1772pub struct ResumeSessionRequest {
1773    /// The ID of the session to resume.
1774    pub session_id: SessionId,
1775    /// The working directory for this session. Must be an absolute path.
1776    ///
1777    /// Clients MUST send the session's working directory. Agents MAY reject a different directory
1778    /// with `-32602`, and MAY normalize paths when comparing.
1779    pub cwd: AbsolutePath,
1780    /// Additional workspace roots to activate for this session. Each path must be absolute.
1781    ///
1782    /// When omitted or empty, no additional roots are activated. When non-empty,
1783    /// this is the complete resulting additional-root list for the resumed
1784    /// session. It may differ from any previously used or reported list as long as
1785    /// the request `cwd` matches the session's `cwd`.
1786    #[serde_as(deserialize_as = "DefaultOnNull")]
1787    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1788    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1789    pub additional_directories: Vec<AbsolutePath>,
1790    /// List of MCP servers to connect to for this session.
1791    ///
1792    /// The complete set of Client-provided servers. Omitted and `[]` mean none. Agents SHOULD
1793    /// NOT restore servers from earlier requests.
1794    #[serde_as(deserialize_as = "DefaultOnNull")]
1795    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1796    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1797    pub mcp_servers: Vec<McpServer>,
1798    /// Inclusive cursor describing where conversation replay should begin.
1799    ///
1800    /// Optional. Omitted and `null` are equivalent and mean the Agent should resume without
1801    /// replaying previous conversation history. Replay cursors are inclusive:
1802    /// replay includes the position identified by the cursor. Supplying
1803    /// `{ "type": "start" }` means the Agent should replay all retained
1804    /// conversation history before responding.
1805    ///
1806    /// Agents MUST reject unsupported cursor types or malformed cursor values
1807    /// with `-32602` (Invalid params), rather than substituting another cursor
1808    /// or resuming without replay.
1809    #[serde(default)]
1810    pub replay_from: Option<ReplayFrom>,
1811    /// System-level instructions for the resumed session.
1812    ///
1813    /// Optional. Omitted and `null` are equivalent. The Agent may then keep a
1814    /// system prompt it stored with the session or use its default instructions.
1815    /// Clients MUST only send this when the Agent advertises
1816    /// `session.systemPrompt`, and SHOULD send the same value they used when the
1817    /// session was created.
1818    #[serde(default)]
1819    pub system_prompt: Option<SystemPrompt>,
1820    /// **UNSTABLE**
1821    ///
1822    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1823    ///
1824    /// Initial values for the session's config options.
1825    ///
1826    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1827    /// this when the Agent advertises `session.options`.
1828    ///
1829    /// The Agent applies the entries in list order, as if the Client had called
1830    /// `session/set_config_option` for each entry after the session was set up. Malformed
1831    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1832    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1833    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1834    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries
1835    /// on the requesting connection. If the session is active on other connections, the
1836    /// Agent SHOULD send `config_option_update` on those connections.
1837    ///
1838    /// The Agent applies the entries before it replays history for `replayFrom` and before
1839    /// it responds.
1840    #[cfg(feature = "unstable_session_options")]
1841    #[serde_as(deserialize_as = "DefaultOnNull")]
1842    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1843    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1844    pub config_options: Vec<InitialSessionConfigOption>,
1845    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1846    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1847    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1848    ///
1849    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1850    #[serde_as(deserialize_as = "DefaultOnError")]
1851    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1852    #[serde(default)]
1853    #[serde(rename = "_meta")]
1854    pub meta: Option<Meta>,
1855}
1856
1857impl ResumeSessionRequest {
1858    /// Builds [`ResumeSessionRequest`] with the required request fields set. Optional fields start unset or empty.
1859    #[must_use]
1860    pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
1861        Self {
1862            session_id: session_id.into(),
1863            cwd: cwd.into(),
1864            additional_directories: vec![],
1865            mcp_servers: vec![],
1866            replay_from: None,
1867            system_prompt: None,
1868            #[cfg(feature = "unstable_session_options")]
1869            config_options: vec![],
1870            meta: None,
1871        }
1872    }
1873
1874    /// Additional workspace roots to activate for this session. Each path must be absolute.
1875    #[must_use]
1876    pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1877    where
1878        I: IntoIterator<Item = P>,
1879        P: Into<AbsolutePath>,
1880    {
1881        self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1882        self
1883    }
1884
1885    /// List of MCP servers to connect to for this session.
1886    #[must_use]
1887    pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1888        self.mcp_servers = mcp_servers;
1889        self
1890    }
1891
1892    /// Inclusive cursor describing where conversation replay should begin.
1893    ///
1894    /// Omitted and `null` are equivalent and mean the Agent should resume without replaying
1895    /// previous conversation history. Replay cursors are inclusive: replay
1896    /// includes the position identified by the cursor. Supplying
1897    /// `{ "type": "start" }` means the Agent should replay all retained
1898    /// conversation history before responding.
1899    #[must_use]
1900    pub fn replay_from(mut self, replay_from: impl IntoOption<ReplayFrom>) -> Self {
1901        self.replay_from = replay_from.into_option();
1902        self
1903    }
1904
1905    /// System-level instructions for the resumed session.
1906    #[must_use]
1907    pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1908        self.system_prompt = system_prompt.into_option();
1909        self
1910    }
1911
1912    /// **UNSTABLE**
1913    ///
1914    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1915    ///
1916    /// Initial values for the session's config options.
1917    ///
1918    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1919    /// this when the Agent advertises `session.options`.
1920    ///
1921    /// The Agent applies the entries in list order, as if the Client had called
1922    /// `session/set_config_option` for each entry after the session was set up. Malformed
1923    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1924    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1925    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1926    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries
1927    /// on the requesting connection. If the session is active on other connections, the
1928    /// Agent SHOULD send `config_option_update` on those connections.
1929    #[cfg(feature = "unstable_session_options")]
1930    #[must_use]
1931    pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1932        self.config_options = config_options;
1933        self
1934    }
1935
1936    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1937    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1938    /// do not recognize.
1939    ///
1940    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1941    #[must_use]
1942    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1943        self.meta = meta.into_option();
1944        self
1945    }
1946}
1947
1948/// Inclusive cursor describing where replayed session history should begin.
1949///
1950/// Replay includes the position identified by the cursor.
1951#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1952#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1953#[serde(tag = "type", rename_all = "snake_case")]
1954#[non_exhaustive]
1955pub enum ReplayFrom {
1956    /// Replay all retained conversation history from its first replayable entry.
1957    Start(ReplayFromStart),
1958    /// Custom or future replay cursor.
1959    ///
1960    /// Values beginning with `_` are reserved for implementation-specific
1961    /// extensions. Unknown values that do not begin with `_` are reserved for
1962    /// future ACP variants.
1963    ///
1964    /// Intermediaries SHOULD preserve the raw payload when storing, replaying,
1965    /// proxying, or forwarding requests. Agents that do not support this cursor
1966    /// MUST reject the request with `-32602` (Invalid params), rather than
1967    /// substituting another cursor or resuming without replay.
1968    #[serde(untagged)]
1969    Other(OtherReplayFrom),
1970}
1971
1972impl From<ReplayFromStart> for ReplayFrom {
1973    fn from(replay_from: ReplayFromStart) -> Self {
1974        Self::Start(replay_from)
1975    }
1976}
1977
1978/// Inclusive replay cursor requesting replay from the start of retained conversation history.
1979#[serde_as]
1980#[skip_serializing_none]
1981#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1982#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1983#[serde(rename_all = "camelCase")]
1984#[non_exhaustive]
1985pub struct ReplayFromStart {
1986    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1987    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1988    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1989    ///
1990    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1991    #[serde_as(deserialize_as = "DefaultOnError")]
1992    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1993    #[serde(default)]
1994    #[serde(rename = "_meta")]
1995    pub meta: Option<Meta>,
1996}
1997
1998impl ReplayFromStart {
1999    /// Builds [`ReplayFromStart`].
2000    #[must_use]
2001    pub fn new() -> Self {
2002        Self::default()
2003    }
2004
2005    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2006    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2007    /// do not recognize.
2008    ///
2009    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2010    #[must_use]
2011    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2012        self.meta = meta.into_option();
2013        self
2014    }
2015}
2016
2017/// Custom or future replay cursor payload.
2018#[serde_as]
2019#[skip_serializing_none]
2020#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2021#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
2022#[cfg_attr(feature = "schemars", schemars(inline))]
2023#[cfg_attr(feature = "schemars", schemars(transform = other_replay_from_schema))]
2024#[serde(rename_all = "camelCase")]
2025#[non_exhaustive]
2026pub struct OtherReplayFrom {
2027    /// Custom or future replay cursor type.
2028    ///
2029    /// Values beginning with `_` are reserved for implementation-specific
2030    /// extensions. Unknown values that do not begin with `_` are reserved for
2031    /// future ACP variants.
2032    #[serde(rename = "type")]
2033    pub type_: String,
2034    /// The remaining fields of the unknown replay cursor payload, preserved verbatim,
2035    /// including `_meta`.
2036    #[serde(flatten)]
2037    pub fields: BTreeMap<String, serde_json::Value>,
2038}
2039
2040impl OtherReplayFrom {
2041    /// Builds [`OtherReplayFrom`] from an unknown discriminator and preserves the remaining extension fields.
2042    #[must_use]
2043    pub fn new(type_: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
2044        fields.remove("type");
2045        Self {
2046            type_: type_.into(),
2047            fields,
2048        }
2049    }
2050}
2051
2052impl<'de> Deserialize<'de> for OtherReplayFrom {
2053    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2054    where
2055        D: serde::Deserializer<'de>,
2056    {
2057        let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
2058        let type_ = fields
2059            .remove("type")
2060            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
2061        let serde_json::Value::String(type_) = type_ else {
2062            return Err(serde::de::Error::custom("`type` must be a string"));
2063        };
2064
2065        if is_known_replay_from_type(&type_) {
2066            return Err(serde::de::Error::custom(format!(
2067                "known replay cursor `{type_}` did not match its schema"
2068            )));
2069        }
2070
2071        Ok(Self { type_, fields })
2072    }
2073}
2074
2075fn is_known_replay_from_type(type_: &str) -> bool {
2076    matches!(type_, "start")
2077}
2078
2079#[cfg(feature = "schemars")]
2080fn other_replay_from_schema(schema: &mut Schema) {
2081    super::schema_util::reject_known_string_discriminators(schema, "type", &["start"]);
2082}
2083
2084crate::serde_util::default_on_null! {
2085    /// Response from resuming an existing session.
2086    ///
2087    /// The agent MUST send a current `state_update` after any requested history
2088    /// replay and before this response, even without replay. The update reports
2089    /// foreground state after resuming. The response alone does not imply `idle`.
2090    ///
2091    /// See protocol docs: [Current-State Synchronization](https://agentclientprotocol.com/protocol/v2/session-setup#current-state-synchronization)
2092    #[serde_as]
2093    #[skip_serializing_none]
2094    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2095    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2096    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_RESUME_METHOD_NAME)))]
2097    #[serde(rename_all = "camelCase")]
2098    #[non_exhaustive]
2099    pub struct ResumeSessionResponse {
2100        /// Initial session configuration options.
2101        ///
2102        /// Optional. Omitted or empty means no config options are advertised.
2103        /// Senders MUST use an array, not `null`. Receivers treat `null` like omission.
2104        /// Later `config_option_update` notifications replace this list.
2105        #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2106        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2107        #[serde(default, skip_serializing_if = "Vec::is_empty")]
2108        pub config_options: Vec<SessionConfigOption>,
2109        /// Initial commands the agent can execute in this session.
2110        ///
2111        /// Optional. Omitted or empty means no initial commands are advertised.
2112        /// Senders MUST use an array, not `null`. Receivers treat `null` like omission.
2113        /// Later `available_commands_update` notifications replace this list.
2114        #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2115        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2116        #[serde(default, skip_serializing_if = "Vec::is_empty")]
2117        pub available_commands: Vec<AvailableCommand>,
2118        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2119        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2120        /// Implementations MUST NOT assign meaning to keys they do not recognize.
2121        ///
2122        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2123        #[serde_as(deserialize_as = "DefaultOnError")]
2124        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2125        #[serde(default)]
2126        #[serde(rename = "_meta")]
2127        pub meta: Option<Meta>,
2128    }
2129}
2130
2131impl ResumeSessionResponse {
2132    /// Builds [`ResumeSessionResponse`] with the required response fields set. Optional fields start unset or empty.
2133    #[must_use]
2134    pub fn new() -> Self {
2135        Self::default()
2136    }
2137
2138    /// Initial session configuration options.
2139    ///
2140    /// Optional. Omitted or empty means no config options are advertised.
2141    /// Senders MUST use an array, not `null`. Receivers treat `null` like omission.
2142    /// Later `config_option_update` notifications replace this list.
2143    #[must_use]
2144    pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
2145        self.config_options = config_options;
2146        self
2147    }
2148
2149    /// Initial commands the agent can execute in this session.
2150    #[must_use]
2151    pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
2152        self.available_commands = available_commands;
2153        self
2154    }
2155
2156    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2157    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2158    /// do not recognize.
2159    ///
2160    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2161    #[must_use]
2162    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2163        self.meta = meta.into_option();
2164        self
2165    }
2166}
2167
2168// Close session
2169
2170/// Request parameters for closing an active session.
2171///
2172/// The Agent MUST cancel any ongoing work related to the session as if `session/cancel`
2173/// was called, then free the resources associated with the session. Unlike `session/cancel`,
2174/// closing also stops the session's background work. After the close response, the Agent
2175/// sends no other messages for the session on that connection.
2176///
2177/// Closing a session that does not exist or is not active SHOULD succeed, and Clients SHOULD
2178/// treat a `-32002` response as a successful close.
2179///
2180/// When closing cancels active foreground work, the Agent MUST send the final
2181/// updates for that work and the idle `state_update` with `stopReason: "cancelled"`
2182/// before responding successfully to `session/close`. Closing an idle session
2183/// does not itself require another idle update.
2184///
2185/// Closing also cancels pending `session/prompt` requests whose messages have not
2186/// been inserted, including held prompts. If closing prevents a prompt's user message from being inserted, the
2187/// Agent MUST answer that request with `-32800` (Request Cancelled). If the message
2188/// has already been inserted, the Agent MUST respond successfully with its
2189/// `messageId`. Prompt responses need not precede the close response.
2190#[serde_as]
2191#[skip_serializing_none]
2192#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2193#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2194#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CLOSE_METHOD_NAME)))]
2195#[serde(rename_all = "camelCase")]
2196#[non_exhaustive]
2197pub struct CloseSessionRequest {
2198    /// The ID of the session to close.
2199    pub session_id: SessionId,
2200    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2201    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2202    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2203    ///
2204    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2205    #[serde_as(deserialize_as = "DefaultOnError")]
2206    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2207    #[serde(default)]
2208    #[serde(rename = "_meta")]
2209    pub meta: Option<Meta>,
2210}
2211
2212impl CloseSessionRequest {
2213    /// Builds [`CloseSessionRequest`] with the required request fields set. Optional fields start unset or empty.
2214    #[must_use]
2215    pub fn new(session_id: impl Into<SessionId>) -> Self {
2216        Self {
2217            session_id: session_id.into(),
2218            meta: None,
2219        }
2220    }
2221
2222    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2223    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2224    /// do not recognize.
2225    ///
2226    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2227    #[must_use]
2228    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2229        self.meta = meta.into_option();
2230        self
2231    }
2232}
2233
2234crate::serde_util::default_on_null! {
2235    /// Response from closing a session.
2236    #[serde_as]
2237    #[skip_serializing_none]
2238    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2239    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2240    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CLOSE_METHOD_NAME)))]
2241    #[serde(rename_all = "camelCase")]
2242    #[non_exhaustive]
2243    pub struct CloseSessionResponse {
2244        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2245        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2246        /// Implementations MUST NOT assign meaning to keys they do not recognize.
2247        ///
2248        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2249        #[serde_as(deserialize_as = "DefaultOnError")]
2250        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2251        #[serde(default)]
2252        #[serde(rename = "_meta")]
2253        pub meta: Option<Meta>,
2254    }
2255}
2256
2257impl CloseSessionResponse {
2258    /// Builds [`CloseSessionResponse`] with the required response fields set. Optional fields start unset or empty.
2259    #[must_use]
2260    pub fn new() -> Self {
2261        Self::default()
2262    }
2263
2264    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2265    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2266    /// do not recognize.
2267    ///
2268    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2269    #[must_use]
2270    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2271        self.meta = meta.into_option();
2272        self
2273    }
2274}
2275
2276// Session status
2277
2278/// **UNSTABLE**
2279///
2280/// This capability is not part of the spec yet, and may be removed or changed at any point.
2281///
2282/// Request parameters for checking the status of a session.
2283///
2284/// Only available if the Agent supports the `session.status` capability.
2285///
2286/// `session/status` MUST NOT have side effects. The Agent does not load, resume, create,
2287/// close, or change the session, and does not attach the requesting connection to it.
2288/// A session the Agent does not know gets `-32002` with the requested `sessionId` in `data`.
2289#[cfg(feature = "unstable_session_status")]
2290#[serde_as]
2291#[skip_serializing_none]
2292#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2293#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2294#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_STATUS_METHOD_NAME)))]
2295#[serde(rename_all = "camelCase")]
2296#[non_exhaustive]
2297pub struct SessionStatusRequest {
2298    /// The ID of the session to check.
2299    pub session_id: SessionId,
2300    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2301    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2302    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2303    ///
2304    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2305    #[serde_as(deserialize_as = "DefaultOnError")]
2306    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2307    #[serde(default)]
2308    #[serde(rename = "_meta")]
2309    pub meta: Option<Meta>,
2310}
2311
2312#[cfg(feature = "unstable_session_status")]
2313impl SessionStatusRequest {
2314    /// Builds [`SessionStatusRequest`] with the required request fields set. Optional fields start unset or empty.
2315    #[must_use]
2316    pub fn new(session_id: impl Into<SessionId>) -> Self {
2317        Self {
2318            session_id: session_id.into(),
2319            meta: None,
2320        }
2321    }
2322
2323    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2324    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2325    /// do not recognize.
2326    ///
2327    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2328    #[must_use]
2329    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2330        self.meta = meta.into_option();
2331        self
2332    }
2333}
2334
2335/// **UNSTABLE**
2336///
2337/// This capability is not part of the spec yet, and may be removed or changed at any point.
2338///
2339/// Response from checking the status of a session.
2340///
2341/// The result is a snapshot. A session reported `open` may be closed or evicted before
2342/// the Client's next request.
2343#[cfg(feature = "unstable_session_status")]
2344#[serde_as]
2345#[skip_serializing_none]
2346#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2347#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2348#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_STATUS_METHOD_NAME)))]
2349#[serde(rename_all = "camelCase")]
2350#[non_exhaustive]
2351pub struct SessionStatusResponse {
2352    /// Whether the Agent has the session in memory.
2353    ///
2354    /// Required. Clients MUST treat a value they do not recognize as `saved`.
2355    pub status: SessionStatus,
2356    /// The session's current foreground state, as the same snapshot the Agent sends in
2357    /// `state_update` notifications.
2358    ///
2359    /// Optional. Agents SHOULD include it when `status` is `open`. Omitted, `null`, and
2360    /// malformed values mean the Agent is not reporting foreground state, and Clients
2361    /// MUST NOT read that as `idle`. This is a snapshot, not a new transition. Clients
2362    /// MUST NOT count an `idle` snapshot as a new completion.
2363    #[serde_as(deserialize_as = "DefaultOnError")]
2364    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2365    #[serde(default)]
2366    pub state: Option<StateUpdate>,
2367    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2368    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2369    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2370    ///
2371    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2372    #[serde_as(deserialize_as = "DefaultOnError")]
2373    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2374    #[serde(default)]
2375    #[serde(rename = "_meta")]
2376    pub meta: Option<Meta>,
2377}
2378
2379#[cfg(feature = "unstable_session_status")]
2380impl SessionStatusResponse {
2381    /// Builds [`SessionStatusResponse`] with the required response fields set. Optional fields start unset or empty.
2382    #[must_use]
2383    pub fn new(status: SessionStatus) -> Self {
2384        Self {
2385            status,
2386            state: None,
2387            meta: None,
2388        }
2389    }
2390
2391    /// The session's current foreground state, as the same snapshot the Agent sends in
2392    /// `state_update` notifications.
2393    #[must_use]
2394    pub fn state(mut self, state: impl IntoOption<StateUpdate>) -> Self {
2395        self.state = state.into_option();
2396        self
2397    }
2398
2399    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2400    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2401    /// do not recognize.
2402    ///
2403    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2404    #[must_use]
2405    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2406        self.meta = meta.into_option();
2407        self
2408    }
2409}
2410
2411/// **UNSTABLE**
2412///
2413/// This capability is not part of the spec yet, and may be removed or changed at any point.
2414///
2415/// Whether the Agent has a session in memory, as reported by `session/status`.
2416#[cfg(feature = "unstable_session_status")]
2417#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2418#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2419#[serde(rename_all = "snake_case")]
2420#[non_exhaustive]
2421pub enum SessionStatus {
2422    /// The Agent has the session in memory, for any connection.
2423    ///
2424    /// This does not mean the requesting connection is attached to it. A Client that did
2425    /// not create or resume the session on its own connection MUST still call
2426    /// `session/resume` before sending `session/prompt` or expecting
2427    /// `session/update` notifications.
2428    Open,
2429    /// The Agent knows the session and can resume it, but does not have it in memory.
2430    ///
2431    /// The Client can call `session/resume` to start it.
2432    Saved,
2433    /// Custom or future session status.
2434    ///
2435    /// Values beginning with `_` are reserved for implementation-specific
2436    /// extensions. Unknown values that do not begin with `_` are reserved for
2437    /// future ACP variants. Clients MUST treat a value they do not recognize as
2438    /// `saved`.
2439    #[serde(untagged)]
2440    Other(String),
2441}
2442
2443/// **UNSTABLE**
2444///
2445/// This capability is not part of the spec yet, and may be removed or changed at any point.
2446///
2447/// Request parameters for `session/options`, which returns the config options a session
2448/// would start with, without creating or resuming a session.
2449///
2450/// Only available if the Agent supports the `session.options` capability.
2451///
2452/// `session/options` MUST NOT create or resume a session, send `session/update`
2453/// notifications, add an entry to `session/list`, or change an existing session. Agents
2454/// SHOULD NOT connect to MCP servers to answer it. Agents MAY start their runtime to resolve
2455/// the options. The rules above still hold for it.
2456#[cfg(feature = "unstable_session_options")]
2457#[serde_as]
2458#[skip_serializing_none]
2459#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2460#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2461#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_OPTIONS_METHOD_NAME)))]
2462#[serde(rename_all = "camelCase")]
2463#[non_exhaustive]
2464pub struct SessionOptionsRequest {
2465    /// The working directory to resolve options for. Must be an absolute path.
2466    pub cwd: AbsolutePath,
2467    /// Additional workspace roots to resolve options for. Each path must be absolute.
2468    ///
2469    /// Optional. Omitted and `null` are equivalent to an empty list.
2470    #[serde_as(deserialize_as = "DefaultOnNull")]
2471    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
2472    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2473    pub additional_directories: Vec<AbsolutePath>,
2474    /// The session to resolve options for.
2475    ///
2476    /// Optional. Omitted and `null` are equivalent and mean a new session. When present,
2477    /// the Agent returns what `session/resume` with the same `cwd` and
2478    /// `additionalDirectories` would return, with the same `cwd` rules. A session the
2479    /// Agent does not know gets `-32002`.
2480    #[serde(default)]
2481    pub session_id: Option<SessionId>,
2482    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2483    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2484    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2485    ///
2486    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2487    #[serde_as(deserialize_as = "DefaultOnError")]
2488    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2489    #[serde(default)]
2490    #[serde(rename = "_meta")]
2491    pub meta: Option<Meta>,
2492}
2493
2494#[cfg(feature = "unstable_session_options")]
2495impl SessionOptionsRequest {
2496    /// Builds [`SessionOptionsRequest`] with the required request fields set. Optional fields start unset or empty.
2497    #[must_use]
2498    pub fn new(cwd: impl Into<AbsolutePath>) -> Self {
2499        Self {
2500            cwd: cwd.into(),
2501            additional_directories: vec![],
2502            session_id: None,
2503            meta: None,
2504        }
2505    }
2506
2507    /// Additional workspace roots to resolve options for. Each path must be absolute.
2508    #[must_use]
2509    pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
2510    where
2511        I: IntoIterator<Item = P>,
2512        P: Into<AbsolutePath>,
2513    {
2514        self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
2515        self
2516    }
2517
2518    /// The session to resolve options for. Unset means a new session.
2519    #[must_use]
2520    pub fn session_id(mut self, session_id: impl IntoOption<SessionId>) -> Self {
2521        self.session_id = session_id.into_option();
2522        self
2523    }
2524
2525    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2526    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2527    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2528    ///
2529    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2530    #[must_use]
2531    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2532        self.meta = meta.into_option();
2533        self
2534    }
2535}
2536
2537#[cfg(feature = "unstable_session_options")]
2538crate::serde_util::default_on_null! {
2539    /// **UNSTABLE**
2540    ///
2541    /// This capability is not part of the spec yet, and may be removed or changed at any point.
2542    ///
2543    /// Response from `session/options`.
2544    ///
2545    /// The result is a snapshot. The options a session actually starts with are the ones in
2546    /// the session setup response.
2547    #[serde_as]
2548    #[skip_serializing_none]
2549    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2550    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2551    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_OPTIONS_METHOD_NAME)))]
2552    #[serde(rename_all = "camelCase")]
2553    #[non_exhaustive]
2554    pub struct SessionOptionsResponse {
2555        /// The config options the session would start with, with the same rules as on
2556        /// `NewSessionResponse`.
2557        ///
2558        /// Optional. Omitted or empty means no config options are advertised.
2559        /// Senders MUST use an array, not `null`. Receivers treat `null` like omission.
2560        #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2561        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2562        #[serde(default, skip_serializing_if = "Vec::is_empty")]
2563        pub config_options: Vec<SessionConfigOption>,
2564        /// Commands the Agent knows the session would have.
2565        ///
2566        /// Optional. Omitted or empty means no commands are advertised.
2567        /// Senders MUST use an array, not `null`. Receivers treat `null` like omission.
2568        ///
2569        /// Advisory. Agents MAY return a partial list. Clients MUST use the commands from the
2570        /// `session/new` or `session/resume` response and later `available_commands_update`
2571        /// notifications for the session itself.
2572        #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2573        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2574        #[serde(default, skip_serializing_if = "Vec::is_empty")]
2575        pub available_commands: Vec<AvailableCommand>,
2576        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2577        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2578        /// Implementations MUST NOT assign meaning to keys they do not recognize.
2579        ///
2580        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2581        #[serde_as(deserialize_as = "DefaultOnError")]
2582        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2583        #[serde(default)]
2584        #[serde(rename = "_meta")]
2585        pub meta: Option<Meta>,
2586    }
2587}
2588
2589#[cfg(feature = "unstable_session_options")]
2590impl SessionOptionsResponse {
2591    /// Builds [`SessionOptionsResponse`] with the required response fields set. Optional fields start unset or empty.
2592    #[must_use]
2593    pub fn new() -> Self {
2594        Self::default()
2595    }
2596
2597    /// The config options the session would start with.
2598    #[must_use]
2599    pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
2600        self.config_options = config_options;
2601        self
2602    }
2603
2604    /// Commands the Agent knows the session would have. Advisory.
2605    #[must_use]
2606    pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
2607        self.available_commands = available_commands;
2608        self
2609    }
2610
2611    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2612    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2613    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2614    ///
2615    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2616    #[must_use]
2617    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2618        self.meta = meta.into_option();
2619        self
2620    }
2621}
2622
2623/// **UNSTABLE**
2624///
2625/// This capability is not part of the spec yet, and may be removed or changed at any point.
2626///
2627/// An initial value for a config option, sent on session setup requests.
2628///
2629/// Same shape as `session/set_config_option` without `sessionId`. Unlike
2630/// `session/set_config_option`, an unknown `configId`, a `type` that does not match the
2631/// option, or a value that is not allowed is ignored instead of rejected.
2632#[cfg(feature = "unstable_session_options")]
2633#[serde_as]
2634#[skip_serializing_none]
2635#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2636#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2637#[serde(rename_all = "camelCase")]
2638#[non_exhaustive]
2639pub struct InitialSessionConfigOption {
2640    /// The ID of the configuration option to set.
2641    pub config_id: SessionConfigId,
2642    /// The value to set, including a `type` discriminator and the raw `value`.
2643    ///
2644    /// Payloads must send `type: "id"` for id-based options. A value `type` the Agent
2645    /// does not support fails the request with `-32602`.
2646    #[serde(flatten)]
2647    pub value: SessionConfigOptionValue,
2648    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2649    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2650    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2651    ///
2652    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2653    #[serde_as(deserialize_as = "DefaultOnError")]
2654    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2655    #[serde(default)]
2656    #[serde(rename = "_meta")]
2657    pub meta: Option<Meta>,
2658}
2659
2660#[cfg(feature = "unstable_session_options")]
2661impl InitialSessionConfigOption {
2662    /// Builds [`InitialSessionConfigOption`] with the required fields set. Optional fields start unset or empty.
2663    #[must_use]
2664    pub fn new(
2665        config_id: impl Into<SessionConfigId>,
2666        value: impl Into<SessionConfigOptionValue>,
2667    ) -> Self {
2668        Self {
2669            config_id: config_id.into(),
2670            value: value.into(),
2671            meta: None,
2672        }
2673    }
2674
2675    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2676    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2677    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2678    ///
2679    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2680    #[must_use]
2681    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2682        self.meta = meta.into_option();
2683        self
2684    }
2685}
2686
2687// Cancel tool call
2688
2689/// Request parameters for cancelling one tool call.
2690///
2691/// Clients MUST NOT send it unless the tool call currently advertises `capabilities.cancel`.
2692///
2693/// The Agent responds once it has accepted the cancellation. The response does not mean
2694/// the work has stopped. The Agent confirms it with a `tool_call_update` to a final
2695/// status: normally `cancelled`, or `completed` or `failed` if the work finished first.
2696///
2697/// The Agent responds with `-32602` if the tool call is unknown, already final, or not
2698/// cancellable. Cancelling a tool call does not change the foreground state by itself.
2699///
2700/// See protocol docs: [Cancelling Tool Calls](https://agentclientprotocol.com/protocol/v2/tool-calls#cancelling-tool-calls)
2701#[serde_as]
2702#[skip_serializing_none]
2703#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2704#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2705#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TOOL_CALL_CANCEL_METHOD_NAME)))]
2706#[serde(rename_all = "camelCase")]
2707#[non_exhaustive]
2708pub struct CancelToolCallRequest {
2709    /// The ID of the session that owns the tool call.
2710    pub session_id: SessionId,
2711    /// The ID of the tool call to cancel.
2712    pub tool_call_id: ToolCallId,
2713    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2714    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2715    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2716    ///
2717    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2718    #[serde_as(deserialize_as = "DefaultOnError")]
2719    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2720    #[serde(default)]
2721    #[serde(rename = "_meta")]
2722    pub meta: Option<Meta>,
2723}
2724
2725impl CancelToolCallRequest {
2726    /// Builds [`CancelToolCallRequest`] with the required request fields set. Optional fields start unset or empty.
2727    #[must_use]
2728    pub fn new(session_id: impl Into<SessionId>, tool_call_id: impl Into<ToolCallId>) -> Self {
2729        Self {
2730            session_id: session_id.into(),
2731            tool_call_id: tool_call_id.into(),
2732            meta: None,
2733        }
2734    }
2735
2736    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2737    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2738    /// do not recognize.
2739    ///
2740    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2741    #[must_use]
2742    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2743        self.meta = meta.into_option();
2744        self
2745    }
2746}
2747
2748crate::serde_util::default_on_null! {
2749    /// Response from cancelling a tool call.
2750    #[serde_as]
2751    #[skip_serializing_none]
2752    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2753    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2754    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TOOL_CALL_CANCEL_METHOD_NAME)))]
2755    #[serde(rename_all = "camelCase")]
2756    #[non_exhaustive]
2757    pub struct CancelToolCallResponse {
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}
2770
2771impl CancelToolCallResponse {
2772    /// Builds [`CancelToolCallResponse`] with the required response fields set. Optional fields start unset or empty.
2773    #[must_use]
2774    pub fn new() -> Self {
2775        Self::default()
2776    }
2777
2778    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2779    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2780    /// do not recognize.
2781    ///
2782    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2783    #[must_use]
2784    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2785        self.meta = meta.into_option();
2786        self
2787    }
2788}
2789
2790// Cancel terminal
2791
2792/// Request parameters for cancelling one terminal.
2793///
2794/// Clients MUST NOT send it unless the terminal currently advertises `capabilities.cancel`.
2795///
2796/// The Agent responds once it has accepted the cancellation. The response does not mean
2797/// the work has stopped. The Agent confirms it with a `terminal_update` that sets
2798/// `exitStatus`. Cancelling stops the process but does not release the terminal, and does
2799/// not change the status of a tool call that references it.
2800///
2801/// The Agent responds with `-32602` if the terminal is unknown, has already exited, or is not
2802/// cancellable. Cancelling a terminal does not change the foreground state by itself.
2803///
2804/// See protocol docs: [Cancelling Terminals](https://agentclientprotocol.com/protocol/v2/tool-calls#cancelling-terminals)
2805#[serde_as]
2806#[skip_serializing_none]
2807#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2808#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2809#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TERMINAL_CANCEL_METHOD_NAME)))]
2810#[serde(rename_all = "camelCase")]
2811#[non_exhaustive]
2812pub struct CancelTerminalRequest {
2813    /// The ID of the session that owns the terminal.
2814    pub session_id: SessionId,
2815    /// The ID of the terminal to cancel.
2816    pub terminal_id: TerminalId,
2817    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2818    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2819    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2820    ///
2821    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2822    #[serde_as(deserialize_as = "DefaultOnError")]
2823    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2824    #[serde(default)]
2825    #[serde(rename = "_meta")]
2826    pub meta: Option<Meta>,
2827}
2828
2829impl CancelTerminalRequest {
2830    /// Builds [`CancelTerminalRequest`] with the required request fields set. Optional fields start unset or empty.
2831    #[must_use]
2832    pub fn new(session_id: impl Into<SessionId>, terminal_id: impl Into<TerminalId>) -> Self {
2833        Self {
2834            session_id: session_id.into(),
2835            terminal_id: terminal_id.into(),
2836            meta: None,
2837        }
2838    }
2839
2840    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2841    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2842    /// do not recognize.
2843    ///
2844    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2845    #[must_use]
2846    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2847        self.meta = meta.into_option();
2848        self
2849    }
2850}
2851
2852crate::serde_util::default_on_null! {
2853    /// Response from cancelling a terminal.
2854    #[serde_as]
2855    #[skip_serializing_none]
2856    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2857    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2858    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TERMINAL_CANCEL_METHOD_NAME)))]
2859    #[serde(rename_all = "camelCase")]
2860    #[non_exhaustive]
2861    pub struct CancelTerminalResponse {
2862        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2863        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2864        /// Implementations MUST NOT assign meaning to keys they do not recognize.
2865        ///
2866        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2867        #[serde_as(deserialize_as = "DefaultOnError")]
2868        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2869        #[serde(default)]
2870        #[serde(rename = "_meta")]
2871        pub meta: Option<Meta>,
2872    }
2873}
2874
2875impl CancelTerminalResponse {
2876    /// Builds [`CancelTerminalResponse`] with the required response fields set. Optional fields start unset or empty.
2877    #[must_use]
2878    pub fn new() -> Self {
2879        Self::default()
2880    }
2881
2882    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2883    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2884    /// do not recognize.
2885    ///
2886    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2887    #[must_use]
2888    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2889        self.meta = meta.into_option();
2890        self
2891    }
2892}
2893
2894// List sessions
2895
2896/// An opaque cursor used to paginate `session/list` results.
2897#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2898#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
2899#[serde(transparent)]
2900#[from(Arc<str>, String, &str, &mut str, Box<str>, Cow<'_, str>)]
2901#[non_exhaustive]
2902pub struct SessionListCursor(pub Arc<str>);
2903
2904impl SessionListCursor {
2905    /// Wraps a protocol string as a typed [`SessionListCursor`].
2906    #[must_use]
2907    pub fn new(cursor: impl Into<Self>) -> Self {
2908        cursor.into()
2909    }
2910}
2911
2912impl AsRef<str> for SessionListCursor {
2913    fn as_ref(&self) -> &str {
2914        &self.0
2915    }
2916}
2917
2918impl From<&String> for SessionListCursor {
2919    fn from(cursor: &String) -> Self {
2920        Self(cursor.as_str().into())
2921    }
2922}
2923
2924macro_rules! impl_session_list_cursor_option_conversion {
2925    ($source:ty) => {
2926        impl IntoOption<SessionListCursor> for $source {
2927            fn into_option(self) -> Option<SessionListCursor> {
2928                Some(self.into())
2929            }
2930        }
2931    };
2932}
2933
2934impl_session_list_cursor_option_conversion!(Arc<str>);
2935impl_session_list_cursor_option_conversion!(String);
2936impl_session_list_cursor_option_conversion!(&str);
2937impl_session_list_cursor_option_conversion!(&mut str);
2938impl_session_list_cursor_option_conversion!(&String);
2939impl_session_list_cursor_option_conversion!(Box<str>);
2940impl_session_list_cursor_option_conversion!(Cow<'_, str>);
2941
2942crate::serde_util::default_on_null! {
2943    /// Request parameters for listing existing sessions.
2944    #[serde_as]
2945    #[skip_serializing_none]
2946    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2947    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2948    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_LIST_METHOD_NAME)))]
2949    #[serde(rename_all = "camelCase")]
2950    #[non_exhaustive]
2951    pub struct ListSessionsRequest {
2952        /// Filter sessions by working directory. Must be an absolute path.
2953        ///
2954        /// Only sessions whose `cwd` is this same directory match. Subdirectories and
2955        /// `additionalDirectories` don't. Agents MAY normalize paths when comparing.
2956        ///
2957        /// Omitted and `null` are equivalent and mean sessions are not filtered by working directory.
2958        #[serde(default)]
2959        pub cwd: Option<AbsolutePath>,
2960        /// Opaque cursor token from a previous response's nextCursor field for cursor-based pagination
2961        ///
2962        /// Omitted and `null` are equivalent and mean the first page is requested.
2963        #[serde(default)]
2964        pub cursor: Option<SessionListCursor>,
2965        /// **UNSTABLE**
2966        ///
2967        /// This capability is not part of the spec yet, and may be removed or changed at any point.
2968        ///
2969        /// Filter sessions by archive state.
2970        ///
2971        /// Optional. Omitted and `null` are equivalent and mean `exclude`. Only send this when
2972        /// the Agent advertises the `session.archive` capability. The filter combines with `cwd` and
2973        /// applies before pagination. Clients keep the same value when following `nextCursor`.
2974        #[cfg(feature = "unstable_session_archive")]
2975        #[serde(default)]
2976        pub archived: Option<SessionArchiveFilter>,
2977        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2978        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2979        /// Implementations MUST NOT assign meaning to keys they do not recognize.
2980        ///
2981        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2982        #[serde_as(deserialize_as = "DefaultOnError")]
2983        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2984        #[serde(default)]
2985        #[serde(rename = "_meta")]
2986        pub meta: Option<Meta>,
2987    }
2988}
2989
2990impl ListSessionsRequest {
2991    /// Builds [`ListSessionsRequest`] with the required request fields set. Optional fields start unset or empty.
2992    #[must_use]
2993    pub fn new() -> Self {
2994        Self::default()
2995    }
2996
2997    /// Filter sessions by working directory. Must be an absolute path.
2998    #[must_use]
2999    pub fn cwd(mut self, cwd: impl IntoOption<AbsolutePath>) -> Self {
3000        self.cwd = cwd.into_option();
3001        self
3002    }
3003
3004    /// Opaque cursor token from a previous response's nextCursor field for cursor-based pagination
3005    #[must_use]
3006    pub fn cursor(mut self, cursor: impl IntoOption<SessionListCursor>) -> Self {
3007        self.cursor = cursor.into_option();
3008        self
3009    }
3010
3011    /// **UNSTABLE**
3012    ///
3013    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3014    ///
3015    /// Filter sessions by archive state.
3016    #[cfg(feature = "unstable_session_archive")]
3017    #[must_use]
3018    pub fn archived(mut self, archived: impl IntoOption<SessionArchiveFilter>) -> Self {
3019        self.archived = archived.into_option();
3020        self
3021    }
3022
3023    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3024    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3025    /// do not recognize.
3026    ///
3027    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3028    #[must_use]
3029    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3030        self.meta = meta.into_option();
3031        self
3032    }
3033}
3034
3035/// Response from listing sessions.
3036#[serde_as]
3037#[skip_serializing_none]
3038#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3039#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3040#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_LIST_METHOD_NAME)))]
3041#[serde(rename_all = "camelCase")]
3042#[non_exhaustive]
3043pub struct ListSessionsResponse {
3044    /// Array of session information objects.
3045    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
3046    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3047    pub sessions: Vec<SessionInfo>,
3048    /// Opaque cursor token. If present, pass this in the next request's cursor parameter
3049    /// to fetch the next page. Omitted and `null` are equivalent and mean there are no more
3050    /// results. An empty string is a valid cursor, not the end of results.
3051    #[serde(default)]
3052    pub next_cursor: Option<SessionListCursor>,
3053    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3054    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3055    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3056    ///
3057    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3058    #[serde_as(deserialize_as = "DefaultOnError")]
3059    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3060    #[serde(default)]
3061    #[serde(rename = "_meta")]
3062    pub meta: Option<Meta>,
3063}
3064
3065impl ListSessionsResponse {
3066    /// Builds [`ListSessionsResponse`] with the required response fields set. Optional fields start unset or empty.
3067    #[must_use]
3068    pub fn new(sessions: Vec<SessionInfo>) -> Self {
3069        Self {
3070            sessions,
3071            next_cursor: None,
3072            meta: None,
3073        }
3074    }
3075
3076    /// Sets or clears the optional `nextCursor` field.
3077    #[must_use]
3078    pub fn next_cursor(mut self, next_cursor: impl IntoOption<SessionListCursor>) -> Self {
3079        self.next_cursor = next_cursor.into_option();
3080        self
3081    }
3082
3083    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3084    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3085    /// do not recognize.
3086    ///
3087    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3088    #[must_use]
3089    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3090        self.meta = meta.into_option();
3091        self
3092    }
3093}
3094
3095// Delete session
3096
3097/// Request parameters for deleting an existing session from `session/list`.
3098///
3099/// Only available if the Agent supports the `session.delete` capability.
3100#[serde_as]
3101#[skip_serializing_none]
3102#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3103#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3104#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_DELETE_METHOD_NAME)))]
3105#[serde(rename_all = "camelCase")]
3106#[non_exhaustive]
3107pub struct DeleteSessionRequest {
3108    /// The ID of the session to delete.
3109    pub session_id: SessionId,
3110    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3111    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3112    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3113    ///
3114    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3115    #[serde_as(deserialize_as = "DefaultOnError")]
3116    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3117    #[serde(default)]
3118    #[serde(rename = "_meta")]
3119    pub meta: Option<Meta>,
3120}
3121
3122impl DeleteSessionRequest {
3123    /// Builds [`DeleteSessionRequest`] with the required request fields set. Optional fields start unset or empty.
3124    #[must_use]
3125    pub fn new(session_id: impl Into<SessionId>) -> Self {
3126        Self {
3127            session_id: session_id.into(),
3128            meta: None,
3129        }
3130    }
3131
3132    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3133    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3134    /// do not recognize.
3135    ///
3136    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3137    #[must_use]
3138    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3139        self.meta = meta.into_option();
3140        self
3141    }
3142}
3143
3144crate::serde_util::default_on_null! {
3145    /// Response from deleting a session.
3146    #[serde_as]
3147    #[skip_serializing_none]
3148    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3149    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3150    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_DELETE_METHOD_NAME)))]
3151    #[serde(rename_all = "camelCase")]
3152    #[non_exhaustive]
3153    pub struct DeleteSessionResponse {
3154        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3155        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3156        /// Implementations MUST NOT assign meaning to keys they do not recognize.
3157        ///
3158        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3159        #[serde_as(deserialize_as = "DefaultOnError")]
3160        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3161        #[serde(default)]
3162        #[serde(rename = "_meta")]
3163        pub meta: Option<Meta>,
3164    }
3165}
3166
3167impl DeleteSessionResponse {
3168    /// Builds [`DeleteSessionResponse`] with the required response fields set. Optional fields start unset or empty.
3169    #[must_use]
3170    pub fn new() -> Self {
3171        Self::default()
3172    }
3173
3174    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3175    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3176    /// do not recognize.
3177    ///
3178    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3179    #[must_use]
3180    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3181        self.meta = meta.into_option();
3182        self
3183    }
3184}
3185
3186// Archive session
3187
3188/// **UNSTABLE**
3189///
3190/// This capability is not part of the spec yet, and may be removed or changed at any point.
3191///
3192/// Request parameters for archiving a session.
3193///
3194/// Only available if the Agent supports the `session.archive` capability.
3195///
3196/// Archiving hides the session from default `session/list` results. It keeps the session ID
3197/// and saved history. If the session is active, the Agent MUST cancel any ongoing work and
3198/// free the session's resources as if `session/close` had been called, then archive it.
3199/// Archiving an archived session succeeds. A session that does not exist gets `-32002`.
3200///
3201#[cfg(feature = "unstable_session_archive")]
3202#[serde_as]
3203#[skip_serializing_none]
3204#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3205#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3206#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_ARCHIVE_METHOD_NAME)))]
3207#[serde(rename_all = "camelCase")]
3208#[non_exhaustive]
3209pub struct ArchiveSessionRequest {
3210    /// The ID of the session to archive.
3211    pub session_id: SessionId,
3212    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3213    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3214    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3215    ///
3216    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3217    #[serde_as(deserialize_as = "DefaultOnError")]
3218    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3219    #[serde(default)]
3220    #[serde(rename = "_meta")]
3221    pub meta: Option<Meta>,
3222}
3223
3224#[cfg(feature = "unstable_session_archive")]
3225impl ArchiveSessionRequest {
3226    /// Builds [`ArchiveSessionRequest`] with the required request fields set. Optional fields start unset or empty.
3227    #[must_use]
3228    pub fn new(session_id: impl Into<SessionId>) -> Self {
3229        Self {
3230            session_id: session_id.into(),
3231            meta: None,
3232        }
3233    }
3234
3235    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3236    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3237    /// do not recognize.
3238    ///
3239    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3240    #[must_use]
3241    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3242        self.meta = meta.into_option();
3243        self
3244    }
3245}
3246
3247#[cfg(feature = "unstable_session_archive")]
3248crate::serde_util::default_on_null! {
3249    /// **UNSTABLE**
3250    ///
3251    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3252    ///
3253    /// Response from archiving a session.
3254    #[serde_as]
3255    #[skip_serializing_none]
3256    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3257    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3258    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_ARCHIVE_METHOD_NAME)))]
3259    #[serde(rename_all = "camelCase")]
3260    #[non_exhaustive]
3261    pub struct ArchiveSessionResponse {
3262        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3263        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3264        /// Implementations MUST NOT assign meaning to keys they do not recognize.
3265        ///
3266        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3267        #[serde_as(deserialize_as = "DefaultOnError")]
3268        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3269        #[serde(default)]
3270        #[serde(rename = "_meta")]
3271        pub meta: Option<Meta>,
3272    }
3273}
3274
3275#[cfg(feature = "unstable_session_archive")]
3276impl ArchiveSessionResponse {
3277    /// Builds [`ArchiveSessionResponse`] with the required response fields set. Optional fields start unset or empty.
3278    #[must_use]
3279    pub fn new() -> Self {
3280        Self::default()
3281    }
3282
3283    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3284    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3285    /// do not recognize.
3286    ///
3287    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3288    #[must_use]
3289    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3290        self.meta = meta.into_option();
3291        self
3292    }
3293}
3294
3295/// **UNSTABLE**
3296///
3297/// This capability is not part of the spec yet, and may be removed or changed at any point.
3298///
3299/// Request parameters for unarchiving a session.
3300///
3301/// Only available if the Agent supports the `session.archive` capability.
3302///
3303/// Unarchiving returns the session to default `session/list` results with the same ID and
3304/// saved history. It never loads or resumes the session. Clients that want to continue an
3305/// archived session SHOULD unarchive it before calling `session/resume`.
3306/// Unarchiving a session that is not archived succeeds. A session that does not exist
3307/// gets `-32002`.
3308///
3309#[cfg(feature = "unstable_session_archive")]
3310#[serde_as]
3311#[skip_serializing_none]
3312#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3313#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3314#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_UNARCHIVE_METHOD_NAME)))]
3315#[serde(rename_all = "camelCase")]
3316#[non_exhaustive]
3317pub struct UnarchiveSessionRequest {
3318    /// The ID of the session to unarchive.
3319    pub session_id: SessionId,
3320    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3321    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3322    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3323    ///
3324    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3325    #[serde_as(deserialize_as = "DefaultOnError")]
3326    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3327    #[serde(default)]
3328    #[serde(rename = "_meta")]
3329    pub meta: Option<Meta>,
3330}
3331
3332#[cfg(feature = "unstable_session_archive")]
3333impl UnarchiveSessionRequest {
3334    /// Builds [`UnarchiveSessionRequest`] with the required request fields set. Optional fields start unset or empty.
3335    #[must_use]
3336    pub fn new(session_id: impl Into<SessionId>) -> Self {
3337        Self {
3338            session_id: session_id.into(),
3339            meta: None,
3340        }
3341    }
3342
3343    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3344    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3345    /// do not recognize.
3346    ///
3347    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3348    #[must_use]
3349    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3350        self.meta = meta.into_option();
3351        self
3352    }
3353}
3354
3355#[cfg(feature = "unstable_session_archive")]
3356crate::serde_util::default_on_null! {
3357    /// **UNSTABLE**
3358    ///
3359    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3360    ///
3361    /// Response from unarchiving a session.
3362    #[serde_as]
3363    #[skip_serializing_none]
3364    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3365    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3366    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_UNARCHIVE_METHOD_NAME)))]
3367    #[serde(rename_all = "camelCase")]
3368    #[non_exhaustive]
3369    pub struct UnarchiveSessionResponse {
3370        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3371        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3372        /// Implementations MUST NOT assign meaning to keys they do not recognize.
3373        ///
3374        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3375        #[serde_as(deserialize_as = "DefaultOnError")]
3376        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3377        #[serde(default)]
3378        #[serde(rename = "_meta")]
3379        pub meta: Option<Meta>,
3380    }
3381}
3382
3383#[cfg(feature = "unstable_session_archive")]
3384impl UnarchiveSessionResponse {
3385    /// Builds [`UnarchiveSessionResponse`] with the required response fields set. Optional fields start unset or empty.
3386    #[must_use]
3387    pub fn new() -> Self {
3388        Self::default()
3389    }
3390
3391    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3392    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3393    /// do not recognize.
3394    ///
3395    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3396    #[must_use]
3397    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3398        self.meta = meta.into_option();
3399        self
3400    }
3401}
3402
3403/// **UNSTABLE**
3404///
3405/// This capability is not part of the spec yet, and may be removed or changed at any point.
3406///
3407/// Which sessions `session/list` returns based on their archive state.
3408///
3409/// Unknown values are preserved so they can be stored, proxied, or forwarded. An Agent MUST
3410/// return `-32602` for a value it does not support rather than treating it as `exclude`.
3411#[cfg(feature = "unstable_session_archive")]
3412#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3413#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
3414#[serde(rename_all = "snake_case")]
3415#[non_exhaustive]
3416pub enum SessionArchiveFilter {
3417    /// Only sessions that are not archived. This is the default.
3418    #[default]
3419    Exclude,
3420    /// Both archived sessions and sessions that are not archived.
3421    Include,
3422    /// Only archived sessions.
3423    Only,
3424    /// Custom or future archive filter.
3425    ///
3426    /// Values beginning with `_` are reserved for implementation-specific
3427    /// extensions. Unknown values that do not begin with `_` are reserved for
3428    /// future ACP variants.
3429    #[serde(untagged)]
3430    Other(String),
3431}
3432
3433/// Information about a session returned by session/list
3434#[serde_as]
3435#[skip_serializing_none]
3436#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3437#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3438#[serde(rename_all = "camelCase")]
3439#[non_exhaustive]
3440pub struct SessionInfo {
3441    /// Unique identifier for the session
3442    pub session_id: SessionId,
3443    /// The working directory for this session. Must be an absolute path.
3444    pub cwd: AbsolutePath,
3445    /// Additional workspace roots reported for this session. Each path must be absolute.
3446    ///
3447    /// When present, this is the complete ordered additional-root list reported
3448    /// by the Agent. Omitted and empty values are equivalent: the response
3449    /// reports no additional roots.
3450    #[serde_as(deserialize_as = "DefaultOnNull")]
3451    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
3452    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3453    pub additional_directories: Vec<AbsolutePath>,
3454
3455    /// Human-readable title for the session
3456    ///
3457    /// Omitted and `null` are equivalent and mean no title is provided.
3458    #[serde_as(deserialize_as = "DefaultOnError")]
3459    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3460    #[serde(default)]
3461    pub title: Option<String>,
3462    /// RFC 3339 timestamp of last activity.
3463    ///
3464    /// Omitted and `null` are equivalent and mean the last activity time is not reported.
3465    #[serde_as(deserialize_as = "DefaultOnError")]
3466    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "format" = "date-time")))]
3467    #[serde(default)]
3468    pub updated_at: Option<String>,
3469    /// **UNSTABLE**
3470    ///
3471    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3472    ///
3473    /// Whether the session is archived.
3474    ///
3475    /// Optional. Omitted and `null` are equivalent and mean the archive state is not reported.
3476    /// Agents that advertise the `session.archive` capability MUST include it on every listed session.
3477    #[cfg(feature = "unstable_session_archive")]
3478    #[serde_as(deserialize_as = "DefaultOnError")]
3479    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3480    #[serde(default)]
3481    pub archived: Option<bool>,
3482    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3483    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3484    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3485    ///
3486    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3487    #[serde_as(deserialize_as = "DefaultOnError")]
3488    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3489    #[serde(default)]
3490    #[serde(rename = "_meta")]
3491    pub meta: Option<Meta>,
3492}
3493
3494impl SessionInfo {
3495    /// Builds [`SessionInfo`] with the required fields set. Optional fields start unset or empty.
3496    #[must_use]
3497    pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
3498        Self {
3499            session_id: session_id.into(),
3500            cwd: cwd.into(),
3501            additional_directories: vec![],
3502            title: None,
3503            updated_at: None,
3504            #[cfg(feature = "unstable_session_archive")]
3505            archived: None,
3506            meta: None,
3507        }
3508    }
3509
3510    /// Additional workspace roots reported for this session. Each path must be absolute.
3511    #[must_use]
3512    pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
3513    where
3514        I: IntoIterator<Item = P>,
3515        P: Into<AbsolutePath>,
3516    {
3517        self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
3518        self
3519    }
3520
3521    /// Human-readable title for the session
3522    #[must_use]
3523    pub fn title(mut self, title: impl IntoOption<String>) -> Self {
3524        self.title = title.into_option();
3525        self
3526    }
3527
3528    /// RFC 3339 timestamp of last activity.
3529    #[must_use]
3530    pub fn updated_at(mut self, updated_at: impl IntoOption<String>) -> Self {
3531        self.updated_at = updated_at.into_option();
3532        self
3533    }
3534
3535    /// **UNSTABLE**
3536    ///
3537    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3538    ///
3539    /// Whether the session is archived.
3540    #[cfg(feature = "unstable_session_archive")]
3541    #[must_use]
3542    pub fn archived(mut self, archived: impl IntoOption<bool>) -> Self {
3543        self.archived = archived.into_option();
3544        self
3545    }
3546
3547    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3548    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3549    /// do not recognize.
3550    ///
3551    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3552    #[must_use]
3553    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3554        self.meta = meta.into_option();
3555        self
3556    }
3557}
3558
3559// Set session title
3560
3561/// **UNSTABLE**
3562///
3563/// This capability is not part of the spec yet, and may be removed or changed at any point.
3564///
3565/// Request parameters for setting the title of a session.
3566///
3567/// Only available if the Agent supports the `session.title` capability.
3568///
3569/// The session does not need to be active on the connection. Any session the Agent would
3570/// return from `session/list` can be retitled. A session that does not exist gets `-32002`.
3571///
3572/// The Agent responds only after it has stored the title. After a successful response, the
3573/// Agent SHOULD NOT replace the title with one it generates automatically.
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 SetSessionTitleRequest {
3583    /// The ID of the session to retitle.
3584    pub session_id: SessionId,
3585    /// The new title for the session.
3586    ///
3587    /// Required and non-null. Omission and explicit `null` are both invalid. The Agent MAY
3588    /// normalize the title before storing it, for example by trimming whitespace or
3589    /// truncating it. The Agent rejects a title that fails its validation, including one
3590    /// that is empty after normalization, with `-32602`.
3591    pub title: String,
3592    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3593    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3594    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3595    ///
3596    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3597    #[serde_as(deserialize_as = "DefaultOnError")]
3598    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3599    #[serde(default)]
3600    #[serde(rename = "_meta")]
3601    pub meta: Option<Meta>,
3602}
3603
3604#[cfg(feature = "unstable_session_set_title")]
3605impl SetSessionTitleRequest {
3606    /// Builds [`SetSessionTitleRequest`] with the required request fields set. Optional fields start unset or empty.
3607    #[must_use]
3608    pub fn new(session_id: impl Into<SessionId>, title: impl Into<String>) -> Self {
3609        Self {
3610            session_id: session_id.into(),
3611            title: title.into(),
3612            meta: None,
3613        }
3614    }
3615
3616    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3617    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3618    /// do not recognize.
3619    ///
3620    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3621    #[must_use]
3622    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3623        self.meta = meta.into_option();
3624        self
3625    }
3626}
3627
3628/// **UNSTABLE**
3629///
3630/// This capability is not part of the spec yet, and may be removed or changed at any point.
3631///
3632/// Response from setting the title of a session.
3633#[cfg(feature = "unstable_session_set_title")]
3634#[serde_as]
3635#[skip_serializing_none]
3636#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3637#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3638#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_TITLE_METHOD_NAME)))]
3639#[serde(rename_all = "camelCase")]
3640#[non_exhaustive]
3641pub struct SetSessionTitleResponse {
3642    /// The title the Agent stored.
3643    ///
3644    /// This differs from the requested title if the Agent normalized it. Clients SHOULD
3645    /// display this value rather than the one they sent.
3646    pub title: String,
3647    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3648    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3649    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3650    ///
3651    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3652    #[serde_as(deserialize_as = "DefaultOnError")]
3653    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3654    #[serde(default)]
3655    #[serde(rename = "_meta")]
3656    pub meta: Option<Meta>,
3657}
3658
3659#[cfg(feature = "unstable_session_set_title")]
3660impl SetSessionTitleResponse {
3661    /// Builds [`SetSessionTitleResponse`] with the required response fields set. Optional fields start unset or empty.
3662    #[must_use]
3663    pub fn new(title: impl Into<String>) -> Self {
3664        Self {
3665            title: title.into(),
3666            meta: None,
3667        }
3668    }
3669
3670    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3671    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3672    /// do not recognize.
3673    ///
3674    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3675    #[must_use]
3676    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3677        self.meta = meta.into_option();
3678        self
3679    }
3680}
3681
3682// Session config options
3683
3684/// Unique identifier for a session configuration option.
3685#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3686#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3687#[serde(transparent)]
3688#[from(forward)]
3689#[non_exhaustive]
3690pub struct SessionConfigId(pub Arc<str>);
3691
3692impl SessionConfigId {
3693    /// Wraps a protocol string as a typed [`SessionConfigId`].
3694    #[must_use]
3695    pub fn new(id: impl Into<Self>) -> Self {
3696        id.into()
3697    }
3698}
3699
3700/// Unique identifier for a session configuration option value.
3701#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3702#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3703#[serde(transparent)]
3704#[from(forward)]
3705#[non_exhaustive]
3706pub struct SessionConfigValueId(pub Arc<str>);
3707
3708impl SessionConfigValueId {
3709    /// Wraps a protocol string as a typed [`SessionConfigValueId`].
3710    #[must_use]
3711    pub fn new(id: impl Into<Self>) -> Self {
3712        id.into()
3713    }
3714}
3715
3716/// Unique identifier for a session configuration option value group.
3717#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3718#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3719#[serde(transparent)]
3720#[from(forward)]
3721#[non_exhaustive]
3722pub struct SessionConfigGroupId(pub Arc<str>);
3723
3724impl SessionConfigGroupId {
3725    /// Wraps a protocol string as a typed [`SessionConfigGroupId`].
3726    #[must_use]
3727    pub fn new(id: impl Into<Self>) -> Self {
3728        id.into()
3729    }
3730}
3731
3732/// A possible value for a session configuration option.
3733#[serde_as]
3734#[skip_serializing_none]
3735#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3736#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3737#[serde(rename_all = "camelCase")]
3738#[non_exhaustive]
3739pub struct SessionConfigSelectOption {
3740    /// Unique identifier for this option value.
3741    pub value: SessionConfigValueId,
3742    /// Human-readable label for this option value.
3743    pub name: String,
3744    /// Optional description for this option value.
3745    ///
3746    /// Omitted and `null` are equivalent and mean no description is provided.
3747    #[serde_as(deserialize_as = "DefaultOnError")]
3748    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3749    #[serde(default)]
3750    pub description: Option<String>,
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 SessionConfigSelectOption {
3764    /// Builds [`SessionConfigSelectOption`] with the required fields set. Optional fields start unset or empty.
3765    #[must_use]
3766    pub fn new(value: impl Into<SessionConfigValueId>, name: impl Into<String>) -> Self {
3767        Self {
3768            value: value.into(),
3769            name: name.into(),
3770            description: None,
3771            meta: None,
3772        }
3773    }
3774
3775    /// Sets or clears the optional `description` field.
3776    #[must_use]
3777    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
3778        self.description = description.into_option();
3779        self
3780    }
3781
3782    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3783    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3784    /// do not recognize.
3785    ///
3786    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3787    #[must_use]
3788    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3789        self.meta = meta.into_option();
3790        self
3791    }
3792}
3793
3794/// A group of possible values for a session configuration option.
3795#[serde_as]
3796#[skip_serializing_none]
3797#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3798#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3799#[serde(rename_all = "camelCase")]
3800#[non_exhaustive]
3801pub struct SessionConfigSelectGroup {
3802    /// Unique identifier for this group.
3803    pub group_id: SessionConfigGroupId,
3804    /// Human-readable label for this group.
3805    pub name: String,
3806    /// The set of option values in this group. MUST contain at least one value.
3807    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
3808    #[cfg_attr(feature = "schemars", schemars(length(min = 1), extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3809    pub options: Vec<SessionConfigSelectOption>,
3810    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3811    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3812    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3813    ///
3814    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3815    #[serde_as(deserialize_as = "DefaultOnError")]
3816    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3817    #[serde(default)]
3818    #[serde(rename = "_meta")]
3819    pub meta: Option<Meta>,
3820}
3821
3822impl SessionConfigSelectGroup {
3823    /// Builds [`SessionConfigSelectGroup`] with the required fields set. Optional fields start unset or empty.
3824    #[must_use]
3825    pub fn new(
3826        group_id: impl Into<SessionConfigGroupId>,
3827        name: impl Into<String>,
3828        options: Vec<SessionConfigSelectOption>,
3829    ) -> Self {
3830        Self {
3831            group_id: group_id.into(),
3832            name: name.into(),
3833            options,
3834            meta: None,
3835        }
3836    }
3837
3838    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3839    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3840    /// do not recognize.
3841    ///
3842    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3843    #[must_use]
3844    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3845        self.meta = meta.into_option();
3846        self
3847    }
3848}
3849
3850/// Possible values for a session configuration option.
3851#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3852#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3853#[serde(untagged)]
3854#[non_exhaustive]
3855pub enum SessionConfigSelectOptions {
3856    /// A flat list of options with no grouping.
3857    Ungrouped(
3858        #[cfg_attr(feature = "schemars", schemars(length(min = 1)))] Vec<SessionConfigSelectOption>,
3859    ),
3860    /// A list of options grouped under headers.
3861    Grouped(
3862        #[cfg_attr(feature = "schemars", schemars(length(min = 1)))] Vec<SessionConfigSelectGroup>,
3863    ),
3864}
3865
3866impl From<Vec<SessionConfigSelectOption>> for SessionConfigSelectOptions {
3867    fn from(options: Vec<SessionConfigSelectOption>) -> Self {
3868        SessionConfigSelectOptions::Ungrouped(options)
3869    }
3870}
3871
3872impl From<Vec<SessionConfigSelectGroup>> for SessionConfigSelectOptions {
3873    fn from(groups: Vec<SessionConfigSelectGroup>) -> Self {
3874        SessionConfigSelectOptions::Grouped(groups)
3875    }
3876}
3877
3878/// A single-value selector (dropdown) session configuration option payload.
3879#[skip_serializing_none]
3880#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3881#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3882#[serde(rename_all = "camelCase")]
3883#[non_exhaustive]
3884pub struct SessionConfigSelect {
3885    /// The currently selected value. MUST be one of the `value`s in `options`.
3886    pub current_value: SessionConfigValueId,
3887    /// The set of selectable options. MUST contain at least one value, and each `value` MUST be
3888    /// unique within the option, including across groups.
3889    pub options: SessionConfigSelectOptions,
3890}
3891
3892impl SessionConfigSelect {
3893    /// Builds [`SessionConfigSelect`] with the required fields set. Optional fields start unset or empty.
3894    #[must_use]
3895    pub fn new(
3896        current_value: impl Into<SessionConfigValueId>,
3897        options: impl Into<SessionConfigSelectOptions>,
3898    ) -> Self {
3899        Self {
3900            current_value: current_value.into(),
3901            options: options.into(),
3902        }
3903    }
3904}
3905
3906/// A boolean on/off toggle session configuration option payload.
3907#[skip_serializing_none]
3908#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3909#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3910#[serde(rename_all = "camelCase")]
3911#[non_exhaustive]
3912pub struct SessionConfigBoolean {
3913    /// The current value of the boolean option.
3914    pub current_value: bool,
3915}
3916
3917impl SessionConfigBoolean {
3918    /// Builds [`SessionConfigBoolean`] with the required fields set. Optional fields start unset or empty.
3919    #[must_use]
3920    pub fn new(current_value: bool) -> Self {
3921        Self { current_value }
3922    }
3923}
3924
3925/// Semantic category for a session configuration option.
3926///
3927/// This is intended to help Clients distinguish broadly common selectors (e.g. model selector vs
3928/// session mode selector vs thought/reasoning level) for UX purposes (keyboard shortcuts, icons,
3929/// placement). It MUST NOT be required for correctness. Clients MUST handle missing or unknown
3930/// categories gracefully.
3931///
3932/// Category names beginning with `_` are free for custom use, like other ACP extension methods.
3933/// Category names that do not begin with `_` are reserved for the ACP spec.
3934#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3935#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3936#[serde(rename_all = "snake_case")]
3937#[non_exhaustive]
3938pub enum SessionConfigOptionCategory {
3939    /// Session mode selector.
3940    Mode,
3941    /// Model selector.
3942    Model,
3943    /// Model-related configuration parameter.
3944    ModelConfig,
3945    /// **UNSTABLE**
3946    ///
3947    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3948    ///
3949    /// Response speed selector, such as a fast mode toggle.
3950    #[cfg(feature = "unstable_speed_config_category")]
3951    Speed,
3952    /// Thought/reasoning level selector.
3953    ThoughtLevel,
3954    /// Custom or future category.
3955    ///
3956    /// Values beginning with `_` are reserved for implementation-specific
3957    /// extensions. Unknown values that do not begin with `_` are reserved for
3958    /// future ACP variants.
3959    #[serde(untagged)]
3960    Other(String),
3961}
3962
3963/// Type-specific session configuration option payload.
3964#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3965#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3966#[serde(tag = "type", rename_all = "snake_case")]
3967#[non_exhaustive]
3968pub enum SessionConfigKind {
3969    /// Single-value selector (dropdown).
3970    Select(SessionConfigSelect),
3971    /// Boolean on/off toggle.
3972    Boolean(SessionConfigBoolean),
3973    /// Custom or future session configuration option payload.
3974    ///
3975    /// Values beginning with `_` are reserved for implementation-specific
3976    /// extensions. Unknown values that do not begin with `_` are reserved for
3977    /// future ACP variants.
3978    ///
3979    /// Clients that do not understand this option type should preserve the raw
3980    /// payload when storing, replaying, proxying, or forwarding configuration
3981    /// data, and otherwise ignore the option. The Agent keeps using its `currentValue`.
3982    #[serde(untagged)]
3983    Other(OtherSessionConfigKind),
3984}
3985
3986/// Custom or future session configuration option payload.
3987#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3988#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
3989#[cfg_attr(feature = "schemars", schemars(inline))]
3990#[cfg_attr(feature = "schemars", schemars(transform = other_session_config_kind_schema))]
3991#[serde(rename_all = "camelCase")]
3992#[non_exhaustive]
3993pub struct OtherSessionConfigKind {
3994    /// Custom or future session configuration option type.
3995    ///
3996    /// Values beginning with `_` are reserved for implementation-specific
3997    /// extensions. Unknown values that do not begin with `_` are reserved for
3998    /// future ACP variants.
3999    #[serde(rename = "type")]
4000    pub type_: String,
4001    /// Additional fields from the unknown session configuration option payload.
4002    #[serde(flatten)]
4003    pub fields: BTreeMap<String, serde_json::Value>,
4004}
4005
4006impl OtherSessionConfigKind {
4007    /// Builds [`OtherSessionConfigKind`] from an unknown discriminator and preserves the remaining extension fields.
4008    #[must_use]
4009    pub fn new(type_: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
4010        fields.remove("type");
4011        fields.remove("_meta");
4012        Self {
4013            type_: type_.into(),
4014            fields,
4015        }
4016    }
4017}
4018
4019impl<'de> Deserialize<'de> for OtherSessionConfigKind {
4020    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4021    where
4022        D: serde::Deserializer<'de>,
4023    {
4024        let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
4025        let type_ = fields
4026            .remove("type")
4027            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4028        let serde_json::Value::String(type_) = type_ else {
4029            return Err(serde::de::Error::custom("`type` must be a string"));
4030        };
4031
4032        if is_known_session_config_kind_type(&type_) {
4033            return Err(serde::de::Error::custom(format!(
4034                "known session configuration option `{type_}` did not match its schema"
4035            )));
4036        }
4037
4038        Ok(Self { type_, fields })
4039    }
4040}
4041
4042fn is_known_session_config_kind_type(type_: &str) -> bool {
4043    matches!(type_, "select" | "boolean")
4044}
4045
4046#[cfg(feature = "schemars")]
4047fn other_session_config_kind_schema(schema: &mut Schema) {
4048    super::schema_util::reject_known_string_discriminators(schema, "type", &["select", "boolean"]);
4049}
4050
4051/// A session configuration option selector and its current state.
4052#[serde_as]
4053#[skip_serializing_none]
4054#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4055#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4056#[serde(rename_all = "camelCase")]
4057#[non_exhaustive]
4058pub struct SessionConfigOption {
4059    /// Unique identifier for the configuration option.
4060    pub config_id: SessionConfigId,
4061    /// Human-readable label for the option.
4062    pub name: String,
4063    /// Optional description for the Client to display to the user.
4064    ///
4065    /// Omitted and `null` are equivalent and mean no description is provided.
4066    #[serde_as(deserialize_as = "DefaultOnError")]
4067    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4068    #[serde(default)]
4069    pub description: Option<String>,
4070    /// Optional semantic category for this option (UX only).
4071    ///
4072    /// Omitted and `null` are equivalent and mean no category is provided.
4073    #[serde_as(deserialize_as = "DefaultOnError")]
4074    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4075    #[serde(default)]
4076    pub category: Option<SessionConfigOptionCategory>,
4077    /// Type-specific fields for this configuration option.
4078    #[serde(flatten)]
4079    pub kind: SessionConfigKind,
4080    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4081    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4082    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4083    ///
4084    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4085    #[serde_as(deserialize_as = "DefaultOnError")]
4086    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4087    #[serde(default)]
4088    #[serde(rename = "_meta")]
4089    pub meta: Option<Meta>,
4090}
4091
4092impl SessionConfigOption {
4093    /// Builds [`SessionConfigOption`] with the required fields set. Optional fields start unset or empty.
4094    #[must_use]
4095    pub fn new(
4096        config_id: impl Into<SessionConfigId>,
4097        name: impl Into<String>,
4098        kind: SessionConfigKind,
4099    ) -> Self {
4100        Self {
4101            config_id: config_id.into(),
4102            name: name.into(),
4103            description: None,
4104            category: None,
4105            kind,
4106            meta: None,
4107        }
4108    }
4109
4110    /// Builds a select-style session configuration option with its current value and choices.
4111    #[must_use]
4112    pub fn select(
4113        config_id: impl Into<SessionConfigId>,
4114        name: impl Into<String>,
4115        current_value: impl Into<SessionConfigValueId>,
4116        options: impl Into<SessionConfigSelectOptions>,
4117    ) -> Self {
4118        Self::new(
4119            config_id,
4120            name,
4121            SessionConfigKind::Select(SessionConfigSelect::new(current_value, options)),
4122        )
4123    }
4124
4125    /// Builds a boolean-style session configuration option with its current value.
4126    #[must_use]
4127    pub fn boolean(
4128        config_id: impl Into<SessionConfigId>,
4129        name: impl Into<String>,
4130        current_value: bool,
4131    ) -> Self {
4132        Self::new(
4133            config_id,
4134            name,
4135            SessionConfigKind::Boolean(SessionConfigBoolean::new(current_value)),
4136        )
4137    }
4138
4139    /// Sets or clears the optional `description` field.
4140    #[must_use]
4141    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
4142        self.description = description.into_option();
4143        self
4144    }
4145
4146    /// Sets or clears the optional `category` field.
4147    #[must_use]
4148    pub fn category(mut self, category: impl IntoOption<SessionConfigOptionCategory>) -> Self {
4149        self.category = category.into_option();
4150        self
4151    }
4152
4153    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4154    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4155    /// do not recognize.
4156    ///
4157    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4158    #[must_use]
4159    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4160        self.meta = meta.into_option();
4161        self
4162    }
4163}
4164
4165/// The value to set for a session configuration option.
4166///
4167/// The `type` field acts as the discriminator in the serialized JSON form.
4168///
4169/// The `type` discriminator describes the *shape* of the value, not the option
4170/// kind. For example every option kind that picks from a list of ids
4171/// (`select`, `radio`, …) would use [`Id`](Self::Id), while a future freeform
4172/// text option would get its own variant.
4173#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4174#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4175#[serde(tag = "type", rename_all = "snake_case")]
4176#[non_exhaustive]
4177pub enum SessionConfigOptionValue {
4178    /// A `SessionConfigValueId` string value (`type: "id"`).
4179    Id {
4180        /// The value ID.
4181        value: SessionConfigValueId,
4182    },
4183    /// A boolean value (`type: "boolean"`).
4184    Boolean {
4185        /// The boolean value.
4186        value: bool,
4187    },
4188    /// Custom or future session configuration option value payload.
4189    ///
4190    /// Values beginning with `_` are reserved for implementation-specific
4191    /// extensions. Unknown values that do not begin with `_` are reserved for
4192    /// future ACP variants.
4193    ///
4194    /// Agents MUST reject a `session/set_config_option` request with a value type
4195    /// they do not support with `-32602`.
4196    #[serde(untagged)]
4197    Other(OtherSessionConfigOptionValue),
4198}
4199
4200/// Custom or future session configuration option value payload.
4201#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4202#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4203#[cfg_attr(feature = "schemars", schemars(inline))]
4204#[cfg_attr(feature = "schemars", schemars(transform = other_session_config_option_value_schema))]
4205#[serde(rename_all = "camelCase")]
4206#[non_exhaustive]
4207pub struct OtherSessionConfigOptionValue {
4208    /// Custom or future session configuration option value type.
4209    ///
4210    /// Values beginning with `_` are reserved for implementation-specific
4211    /// extensions. Unknown values that do not begin with `_` are reserved for
4212    /// future ACP variants.
4213    #[serde(rename = "type")]
4214    pub type_: String,
4215    /// Raw value payload for the custom or future value type.
4216    pub value: serde_json::Value,
4217    /// Additional fields from the unknown session configuration option value payload.
4218    #[serde(flatten)]
4219    pub fields: BTreeMap<String, serde_json::Value>,
4220}
4221
4222impl OtherSessionConfigOptionValue {
4223    /// Builds [`OtherSessionConfigOptionValue`] from an unknown discriminator and preserves the remaining extension fields.
4224    #[must_use]
4225    pub fn new(
4226        type_: impl Into<String>,
4227        value: serde_json::Value,
4228        mut fields: BTreeMap<String, serde_json::Value>,
4229    ) -> Self {
4230        fields.remove("type");
4231        fields.remove("value");
4232        fields.remove("_meta");
4233        Self {
4234            type_: type_.into(),
4235            value,
4236            fields,
4237        }
4238    }
4239}
4240
4241impl<'de> Deserialize<'de> for OtherSessionConfigOptionValue {
4242    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4243    where
4244        D: serde::Deserializer<'de>,
4245    {
4246        let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
4247        let type_ = fields
4248            .remove("type")
4249            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4250        let serde_json::Value::String(type_) = type_ else {
4251            return Err(serde::de::Error::custom("`type` must be a string"));
4252        };
4253
4254        if is_known_session_config_option_value_type(&type_) {
4255            return Err(serde::de::Error::custom(format!(
4256                "known session configuration option value `{type_}` did not match its schema"
4257            )));
4258        }
4259
4260        let value = fields
4261            .remove("value")
4262            .ok_or_else(|| serde::de::Error::missing_field("value"))?;
4263
4264        Ok(Self {
4265            type_,
4266            value,
4267            fields,
4268        })
4269    }
4270}
4271
4272impl<'de> Deserialize<'de> for SessionConfigOptionValue {
4273    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4274    where
4275        D: serde::Deserializer<'de>,
4276    {
4277        let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
4278        let type_ = fields.remove("type");
4279        let value = fields
4280            .remove("value")
4281            .ok_or_else(|| serde::de::Error::missing_field("value"))?;
4282
4283        let type_ = type_.ok_or_else(|| serde::de::Error::missing_field("type"))?;
4284
4285        let serde_json::Value::String(type_) = type_ else {
4286            return Err(serde::de::Error::custom("`type` must be a string"));
4287        };
4288
4289        match type_.as_str() {
4290            "id" => {
4291                let value = serde_json::from_value(value).map_err(|error| {
4292                    serde::de::Error::custom(format!(
4293                        "`value` must be a string for `type: id`: {error}"
4294                    ))
4295                })?;
4296                Ok(Self::Id { value })
4297            }
4298            "boolean" => {
4299                let value = serde_json::from_value(value).map_err(|error| {
4300                    serde::de::Error::custom(format!(
4301                        "`value` must be a boolean for `type: boolean`: {error}"
4302                    ))
4303                })?;
4304                Ok(Self::Boolean { value })
4305            }
4306            _ => Ok(Self::Other(OtherSessionConfigOptionValue {
4307                type_,
4308                value,
4309                fields,
4310            })),
4311        }
4312    }
4313}
4314
4315fn is_known_session_config_option_value_type(type_: &str) -> bool {
4316    matches!(type_, "id" | "boolean")
4317}
4318
4319#[cfg(feature = "schemars")]
4320fn other_session_config_option_value_schema(schema: &mut Schema) {
4321    super::schema_util::reject_known_string_discriminators(schema, "type", &["id", "boolean"]);
4322}
4323
4324impl SessionConfigOptionValue {
4325    /// Create an id option value (used by `select` and other id-based option types).
4326    #[must_use]
4327    pub fn id(id: impl Into<SessionConfigValueId>) -> Self {
4328        Self::Id { value: id.into() }
4329    }
4330
4331    /// Create a boolean option value.
4332    #[must_use]
4333    pub fn boolean(val: bool) -> Self {
4334        Self::Boolean { value: val }
4335    }
4336
4337    /// Return the inner [`SessionConfigValueId`] if this is a
4338    /// [`Id`](Self::Id) value.
4339    #[must_use]
4340    pub fn as_id(&self) -> Option<&SessionConfigValueId> {
4341        match self {
4342            Self::Id { value } => Some(value),
4343            _ => None,
4344        }
4345    }
4346
4347    /// Return the inner [`bool`] if this is a [`Boolean`](Self::Boolean) value.
4348    #[must_use]
4349    pub fn as_bool(&self) -> Option<bool> {
4350        match self {
4351            Self::Boolean { value } => Some(*value),
4352            _ => None,
4353        }
4354    }
4355}
4356
4357impl From<SessionConfigValueId> for SessionConfigOptionValue {
4358    fn from(value: SessionConfigValueId) -> Self {
4359        Self::Id { value }
4360    }
4361}
4362
4363impl From<bool> for SessionConfigOptionValue {
4364    fn from(value: bool) -> Self {
4365        Self::Boolean { value }
4366    }
4367}
4368
4369impl From<&str> for SessionConfigOptionValue {
4370    fn from(value: &str) -> Self {
4371        Self::Id {
4372            value: SessionConfigValueId::new(value),
4373        }
4374    }
4375}
4376
4377/// Request parameters for setting a session configuration option.
4378///
4379/// Agents MUST support this method for any session where they advertise config options.
4380/// Agents MUST reject an unknown `configId` or invalid value with `-32602` and leave the
4381/// configuration unchanged.
4382///
4383/// See protocol docs: [Session Config Options](https://agentclientprotocol.com/protocol/v2/session-config-options#setting-a-config-option)
4384#[serde_as]
4385#[skip_serializing_none]
4386#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4387#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4388#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_CONFIG_OPTION_METHOD_NAME)))]
4389#[serde(rename_all = "camelCase")]
4390#[non_exhaustive]
4391pub struct SetSessionConfigOptionRequest {
4392    /// The ID of the session to set the configuration option for.
4393    pub session_id: SessionId,
4394    /// The ID of the configuration option to set.
4395    pub config_id: SessionConfigId,
4396    /// The value to set, including a `type` discriminator and the raw `value`.
4397    ///
4398    /// Payloads must send `type: "id"` for id-based options.
4399    #[serde(flatten)]
4400    pub value: SessionConfigOptionValue,
4401    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4402    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4403    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4404    ///
4405    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4406    #[serde_as(deserialize_as = "DefaultOnError")]
4407    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4408    #[serde(default)]
4409    #[serde(rename = "_meta")]
4410    pub meta: Option<Meta>,
4411}
4412
4413impl SetSessionConfigOptionRequest {
4414    /// Builds [`SetSessionConfigOptionRequest`] with the required request fields set. Optional fields start unset or empty.
4415    #[must_use]
4416    pub fn new(
4417        session_id: impl Into<SessionId>,
4418        config_id: impl Into<SessionConfigId>,
4419        value: impl Into<SessionConfigOptionValue>,
4420    ) -> Self {
4421        Self {
4422            session_id: session_id.into(),
4423            config_id: config_id.into(),
4424            value: value.into(),
4425            meta: None,
4426        }
4427    }
4428
4429    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4430    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4431    /// do not recognize.
4432    ///
4433    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4434    #[must_use]
4435    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4436        self.meta = meta.into_option();
4437        self
4438    }
4439}
4440
4441/// Response to `session/set_config_option` method.
4442#[serde_as]
4443#[skip_serializing_none]
4444#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4445#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4446#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_CONFIG_OPTION_METHOD_NAME)))]
4447#[serde(rename_all = "camelCase")]
4448#[non_exhaustive]
4449pub struct SetSessionConfigOptionResponse {
4450    /// The full set of configuration options and their current values.
4451    #[serde_as(deserialize_as = "VecSkipError<_>")]
4452    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-skip-invalid-items" = true)))]
4453    pub config_options: Vec<SessionConfigOption>,
4454    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4455    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4456    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4457    ///
4458    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4459    #[serde_as(deserialize_as = "DefaultOnError")]
4460    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4461    #[serde(default)]
4462    #[serde(rename = "_meta")]
4463    pub meta: Option<Meta>,
4464}
4465
4466impl SetSessionConfigOptionResponse {
4467    /// Builds [`SetSessionConfigOptionResponse`] with the required response fields set. Optional fields start unset or empty.
4468    #[must_use]
4469    pub fn new(config_options: Vec<SessionConfigOption>) -> Self {
4470        Self {
4471            config_options,
4472            meta: None,
4473        }
4474    }
4475
4476    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4477    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4478    /// do not recognize.
4479    ///
4480    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4481    #[must_use]
4482    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4483        self.meta = meta.into_option();
4484        self
4485    }
4486}
4487
4488// MCP
4489
4490/// Configuration for connecting to an MCP (Model Context Protocol) server.
4491///
4492/// MCP servers provide tools and context that the agent can use when
4493/// processing prompts.
4494///
4495/// See protocol docs: [MCP Servers](https://agentclientprotocol.com/protocol/v2/session-setup#mcp-servers)
4496#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4497#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4498#[serde(tag = "type", rename_all = "snake_case")]
4499#[non_exhaustive]
4500pub enum McpServer {
4501    /// HTTP transport configuration
4502    ///
4503    /// Only available when the Agent capabilities include `session.mcp.http`.
4504    Http(McpServerHttp),
4505    /// **UNSTABLE**
4506    ///
4507    /// This capability is not part of the spec yet, and may be removed or changed at any point.
4508    ///
4509    /// ACP transport configuration
4510    ///
4511    /// Only available when the Agent capabilities include `session.mcp.acp`.
4512    /// The MCP server is provided by an ACP component and communicates over the ACP channel.
4513    #[cfg(feature = "unstable_mcp_over_acp")]
4514    Acp(McpServerAcp),
4515    /// Stdio transport configuration
4516    ///
4517    /// Only available when the Agent capabilities include `session.mcp.stdio`.
4518    Stdio(McpServerStdio),
4519    /// Custom or future MCP server transport configuration.
4520    ///
4521    /// Values beginning with `_` are reserved for implementation-specific
4522    /// extensions. Unknown values that do not begin with `_` are reserved for
4523    /// future ACP variants.
4524    ///
4525    /// Receivers that do not understand this transport should preserve the raw
4526    /// payload when storing, replaying, proxying, or forwarding session setup
4527    /// data. Agents MUST reject a request with a transport they do not support
4528    /// with `-32602`.
4529    #[serde(untagged)]
4530    Other(OtherMcpServer),
4531}
4532
4533/// Custom or future MCP server transport payload.
4534#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4535#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4536#[cfg_attr(feature = "schemars", schemars(inline))]
4537#[cfg_attr(feature = "schemars", schemars(transform = other_mcp_server_schema))]
4538#[serde(rename_all = "camelCase")]
4539#[non_exhaustive]
4540pub struct OtherMcpServer {
4541    /// Custom or future MCP server transport type.
4542    ///
4543    /// Values beginning with `_` are reserved for implementation-specific
4544    /// extensions. Unknown values that do not begin with `_` are reserved for
4545    /// future ACP variants.
4546    #[serde(rename = "type")]
4547    pub type_: String,
4548    /// Additional fields from the unknown MCP server transport payload.
4549    #[serde(flatten)]
4550    pub fields: BTreeMap<String, serde_json::Value>,
4551}
4552
4553impl OtherMcpServer {
4554    /// Builds [`OtherMcpServer`] from an unknown discriminator and preserves the remaining extension fields.
4555    #[must_use]
4556    pub fn new(type_: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
4557        fields.remove("type");
4558        Self {
4559            type_: type_.into(),
4560            fields,
4561        }
4562    }
4563}
4564
4565impl<'de> Deserialize<'de> for OtherMcpServer {
4566    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4567    where
4568        D: serde::Deserializer<'de>,
4569    {
4570        let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
4571        let type_ = fields
4572            .remove("type")
4573            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4574        let serde_json::Value::String(type_) = type_ else {
4575            return Err(serde::de::Error::custom("`type` must be a string"));
4576        };
4577
4578        if is_known_mcp_server_type(&type_) {
4579            return Err(serde::de::Error::custom(format!(
4580                "known MCP server transport `{type_}` did not match its schema"
4581            )));
4582        }
4583
4584        Ok(Self { type_, fields })
4585    }
4586}
4587
4588fn is_known_mcp_server_type(type_: &str) -> bool {
4589    match type_ {
4590        "http" | "stdio" => true,
4591        #[cfg(feature = "unstable_mcp_over_acp")]
4592        "acp" => true,
4593        _ => false,
4594    }
4595}
4596
4597#[cfg(feature = "schemars")]
4598fn other_mcp_server_schema(schema: &mut Schema) {
4599    super::schema_util::reject_known_string_discriminators(
4600        schema,
4601        "type",
4602        &[
4603            "http",
4604            "stdio",
4605            #[cfg(feature = "unstable_mcp_over_acp")]
4606            "acp",
4607        ],
4608    );
4609}
4610
4611/// HTTP transport configuration for MCP.
4612#[serde_as]
4613#[skip_serializing_none]
4614#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4615#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4616#[serde(rename_all = "camelCase")]
4617#[non_exhaustive]
4618pub struct McpServerHttp {
4619    /// Human-readable name identifying this MCP server.
4620    pub name: String,
4621    /// URL to the MCP server.
4622    #[cfg_attr(feature = "schemars", schemars(url))]
4623    pub url: String,
4624    /// HTTP headers to set when making requests to the MCP server. Headers the MCP transport
4625    /// defines are owned by the transport, and Agents use the transport's values for them.
4626    #[serde_as(deserialize_as = "DefaultOnNull")]
4627    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4628    #[serde(default, skip_serializing_if = "Vec::is_empty")]
4629    pub headers: Vec<HttpHeader>,
4630    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4631    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4632    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4633    ///
4634    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4635    #[serde_as(deserialize_as = "DefaultOnError")]
4636    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4637    #[serde(default)]
4638    #[serde(rename = "_meta")]
4639    pub meta: Option<Meta>,
4640}
4641
4642impl McpServerHttp {
4643    /// Builds [`McpServerHttp`] with the required fields set. Optional fields start unset or empty.
4644    #[must_use]
4645    pub fn new(name: impl Into<String>, url: impl Into<String>) -> Self {
4646        Self {
4647            name: name.into(),
4648            url: url.into(),
4649            headers: Vec::new(),
4650            meta: None,
4651        }
4652    }
4653
4654    /// HTTP headers to set when making requests to the MCP server. Headers the MCP transport
4655    /// defines are owned by the transport, and Agents use the transport's values for them.
4656    #[must_use]
4657    pub fn headers(mut self, headers: Vec<HttpHeader>) -> Self {
4658        self.headers = headers;
4659        self
4660    }
4661
4662    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4663    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4664    /// do not recognize.
4665    ///
4666    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4667    #[must_use]
4668    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4669        self.meta = meta.into_option();
4670        self
4671    }
4672}
4673
4674/// **UNSTABLE**
4675///
4676/// This capability is not part of the spec yet, and may be removed or changed at any point.
4677///
4678/// Unique identifier for an MCP server using the ACP transport.
4679///
4680/// The value is opaque and generated by the ACP component providing the MCP server. It is
4681/// used by `mcp/message` to route requests to the component that declared the server.
4682#[cfg(feature = "unstable_mcp_over_acp")]
4683#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4684#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
4685#[serde(transparent)]
4686#[from(forward)]
4687#[non_exhaustive]
4688pub struct McpServerAcpId(pub Arc<str>);
4689
4690#[cfg(feature = "unstable_mcp_over_acp")]
4691impl McpServerAcpId {
4692    /// Wraps a protocol string as a typed [`McpServerAcpId`].
4693    #[must_use]
4694    pub fn new(id: impl Into<Self>) -> Self {
4695        id.into()
4696    }
4697}
4698
4699/// **UNSTABLE**
4700///
4701/// This capability is not part of the spec yet, and may be removed or changed at any point.
4702///
4703/// ACP transport configuration for MCP.
4704///
4705/// The MCP server is provided by an ACP component and communicates over the ACP channel
4706/// using `mcp/message`.
4707#[serde_as]
4708#[skip_serializing_none]
4709#[cfg(feature = "unstable_mcp_over_acp")]
4710#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4711#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4712#[serde(rename_all = "camelCase")]
4713#[non_exhaustive]
4714pub struct McpServerAcp {
4715    /// Human-readable name identifying this MCP server.
4716    pub name: String,
4717    /// Unique identifier for this MCP server, generated by the component providing it.
4718    ///
4719    /// Providers MUST NOT reuse an ID for multiple ACP-transport MCP servers that are visible
4720    /// on the same ACP connection.
4721    pub server_id: McpServerAcpId,
4722    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4723    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4724    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4725    ///
4726    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4727    #[serde_as(deserialize_as = "DefaultOnError")]
4728    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4729    #[serde(default)]
4730    #[serde(rename = "_meta")]
4731    pub meta: Option<Meta>,
4732}
4733
4734#[cfg(feature = "unstable_mcp_over_acp")]
4735impl McpServerAcp {
4736    /// Builds [`McpServerAcp`] with the required fields set. Optional fields start unset or empty.
4737    #[must_use]
4738    pub fn new(name: impl Into<String>, server_id: impl Into<McpServerAcpId>) -> Self {
4739        Self {
4740            name: name.into(),
4741            server_id: server_id.into(),
4742            meta: None,
4743        }
4744    }
4745
4746    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4747    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4748    /// do not recognize.
4749    ///
4750    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4751    #[must_use]
4752    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4753        self.meta = meta.into_option();
4754        self
4755    }
4756}
4757
4758/// Stdio transport configuration for MCP.
4759#[serde_as]
4760#[skip_serializing_none]
4761#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4762#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4763#[serde(rename_all = "camelCase")]
4764#[non_exhaustive]
4765pub struct McpServerStdio {
4766    /// Human-readable name identifying this MCP server.
4767    pub name: String,
4768    /// Absolute path to the MCP server executable.
4769    pub command: AbsolutePath,
4770    /// Command-line arguments to pass to the MCP server.
4771    #[serde_as(deserialize_as = "DefaultOnNull")]
4772    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4773    #[serde(default, skip_serializing_if = "Vec::is_empty")]
4774    pub args: Vec<String>,
4775    /// Environment variables to set when launching the MCP server. Names SHOULD be unique.
4776    /// Agents MAY reject duplicates with `-32602`, and otherwise the last entry wins.
4777    #[serde_as(deserialize_as = "DefaultOnNull")]
4778    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4779    #[serde(default, skip_serializing_if = "Vec::is_empty")]
4780    pub env: Vec<EnvVariable>,
4781    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4782    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4783    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4784    ///
4785    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4786    #[serde_as(deserialize_as = "DefaultOnError")]
4787    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4788    #[serde(default)]
4789    #[serde(rename = "_meta")]
4790    pub meta: Option<Meta>,
4791}
4792
4793impl McpServerStdio {
4794    /// Builds [`McpServerStdio`] with the required fields set. Optional fields start unset or empty.
4795    #[must_use]
4796    pub fn new(name: impl Into<String>, command: impl Into<AbsolutePath>) -> Self {
4797        Self {
4798            name: name.into(),
4799            command: command.into(),
4800            args: Vec::new(),
4801            env: Vec::new(),
4802            meta: None,
4803        }
4804    }
4805
4806    /// Command-line arguments to pass to the MCP server.
4807    #[must_use]
4808    pub fn args(mut self, args: Vec<String>) -> Self {
4809        self.args = args;
4810        self
4811    }
4812
4813    /// Environment variables to set when launching the MCP server. Names SHOULD be unique.
4814    /// Agents MAY reject duplicates with `-32602`, and otherwise the last entry wins.
4815    #[must_use]
4816    pub fn env(mut self, env: Vec<EnvVariable>) -> Self {
4817        self.env = env;
4818        self
4819    }
4820
4821    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4822    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4823    /// do not recognize.
4824    ///
4825    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4826    #[must_use]
4827    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4828        self.meta = meta.into_option();
4829        self
4830    }
4831}
4832
4833/// An environment variable to set when launching a process.
4834#[serde_as]
4835#[skip_serializing_none]
4836#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4837#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4838#[serde(rename_all = "camelCase")]
4839#[non_exhaustive]
4840pub struct EnvVariable {
4841    /// The name of the environment variable.
4842    pub name: String,
4843    /// The value to set for the environment variable.
4844    pub value: String,
4845    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4846    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4847    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4848    ///
4849    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4850    #[serde_as(deserialize_as = "DefaultOnError")]
4851    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4852    #[serde(default)]
4853    #[serde(rename = "_meta")]
4854    pub meta: Option<Meta>,
4855}
4856
4857impl EnvVariable {
4858    /// Builds [`EnvVariable`] with the required fields set. Optional fields start unset or empty.
4859    #[must_use]
4860    pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
4861        Self {
4862            name: name.into(),
4863            value: value.into(),
4864            meta: None,
4865        }
4866    }
4867
4868    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4869    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4870    /// do not recognize.
4871    ///
4872    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4873    #[must_use]
4874    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4875        self.meta = meta.into_option();
4876        self
4877    }
4878}
4879
4880/// An HTTP header to set when making requests to the MCP server.
4881#[serde_as]
4882#[skip_serializing_none]
4883#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4884#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4885#[serde(rename_all = "camelCase")]
4886#[non_exhaustive]
4887pub struct HttpHeader {
4888    /// The name of the HTTP header.
4889    pub name: String,
4890    /// The value to set for the HTTP header.
4891    pub value: String,
4892    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4893    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4894    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4895    ///
4896    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4897    #[serde_as(deserialize_as = "DefaultOnError")]
4898    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4899    #[serde(default)]
4900    #[serde(rename = "_meta")]
4901    pub meta: Option<Meta>,
4902}
4903
4904impl HttpHeader {
4905    /// Builds [`HttpHeader`] with the required fields set. Optional fields start unset or empty.
4906    #[must_use]
4907    pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
4908        Self {
4909            name: name.into(),
4910            value: value.into(),
4911            meta: None,
4912        }
4913    }
4914
4915    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4916    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4917    /// do not recognize.
4918    ///
4919    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4920    #[must_use]
4921    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4922        self.meta = meta.into_option();
4923        self
4924    }
4925}
4926
4927// System prompt
4928
4929/// Client-provided system-level instructions for a session.
4930///
4931/// Clients MUST only send this when the Agent advertises
4932/// `session.systemPrompt`. Agents that cannot apply it, for example because of
4933/// an unadvertised mode or an unsupported content block type, MUST return an
4934/// error instead of creating or resuming the session.
4935#[serde_as]
4936#[skip_serializing_none]
4937#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4938#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4939#[serde(rename_all = "camelCase")]
4940#[non_exhaustive]
4941pub struct SystemPrompt {
4942    /// How the Agent combines `content` with its own instructions.
4943    ///
4944    /// Required. Agents MUST return an error for a mode they do not support rather than
4945    /// treating it as `append` or `override`.
4946    pub mode: SystemPromptMode,
4947    /// The system prompt content.
4948    ///
4949    /// Agents advertising the capability MUST accept `text` content blocks.
4950    /// Clients MUST NOT send other content block types until a future
4951    /// capability allows them, and Agents MUST return an error for content
4952    /// blocks they do not support, including unknown types.
4953    ///
4954    /// Clients MUST NOT send an empty array. Agents MAY reject one with
4955    /// `-32602` without creating or resuming the session.
4956    pub content: Vec<ContentBlock>,
4957    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4958    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4959    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4960    ///
4961    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4962    #[serde_as(deserialize_as = "DefaultOnError")]
4963    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4964    #[serde(default)]
4965    #[serde(rename = "_meta")]
4966    pub meta: Option<Meta>,
4967}
4968
4969impl SystemPrompt {
4970    /// Builds [`SystemPrompt`] with the required fields set. Optional fields start unset or empty.
4971    ///
4972    /// `mode` starts as [`SystemPromptMode::Append`]. Use [`SystemPrompt::mode`]
4973    /// to request another mode.
4974    #[must_use]
4975    pub fn new(content: Vec<ContentBlock>) -> Self {
4976        Self {
4977            mode: SystemPromptMode::default(),
4978            content,
4979            meta: None,
4980        }
4981    }
4982
4983    /// How the Agent combines `content` with its own instructions.
4984    #[must_use]
4985    pub fn mode(mut self, mode: SystemPromptMode) -> Self {
4986        self.mode = mode;
4987        self
4988    }
4989
4990    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4991    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4992    /// do not recognize.
4993    ///
4994    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4995    #[must_use]
4996    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4997        self.meta = meta.into_option();
4998        self
4999    }
5000}
5001
5002/// How the Agent combines a client-provided system prompt with its own instructions.
5003///
5004/// Unknown modes are preserved so they can be stored,
5005/// proxied, or forwarded. An Agent MUST return an error for a mode it does not
5006/// support rather than treating it as `append` or `override`.
5007#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5008#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
5009#[serde(rename_all = "snake_case")]
5010#[non_exhaustive]
5011pub enum SystemPromptMode {
5012    /// Add the content to the Agent's own instructions rather than replacing them.
5013    ///
5014    /// Every Agent that advertises `session.systemPrompt` supports this mode.
5015    /// Agents SHOULD give the content system-level precedence, for example in the
5016    /// model's system prompt or developer instructions rather than in user-turn
5017    /// content. Where it is placed and how it is formatted is implementation-defined.
5018    #[default]
5019    Append,
5020    /// Replace the Agent's built-in default instructions with the content.
5021    ///
5022    /// This does not change tool availability, MCP servers, permissions, or session
5023    /// configuration. Context the Agent supplies from the workspace or environment
5024    /// MAY still be included. Clients that use this mode take responsibility for any
5025    /// tool guidance or safety instructions the Agent's default instructions
5026    /// provided, and MUST only use it when the Agent advertises
5027    /// `session.systemPrompt.mode.override`.
5028    Override,
5029    /// Custom or future system prompt mode.
5030    ///
5031    /// Values beginning with `_` are reserved for implementation-specific
5032    /// extensions. Unknown values that do not begin with `_` are reserved for
5033    /// future ACP variants.
5034    #[serde(untagged)]
5035    Other(String),
5036}
5037
5038// Prompt
5039
5040/// Request parameters for sending a user prompt to the agent.
5041///
5042/// Contains the user's message and any additional context.
5043///
5044/// See protocol docs: [User Message](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#1-user-message)
5045#[serde_as]
5046#[skip_serializing_none]
5047#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5048#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5049#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_PROMPT_METHOD_NAME)))]
5050#[serde(rename_all = "camelCase")]
5051#[non_exhaustive]
5052pub struct PromptRequest {
5053    /// The ID of the session to send this user message to
5054    pub session_id: SessionId,
5055    /// The blocks of content that compose the user's message.
5056    ///
5057    /// As a baseline, the Agent MUST support `text` and `resource_link` content blocks,
5058    /// while other variants are optionally enabled via `PromptCapabilities`.
5059    ///
5060    /// The Client MUST adapt its interface according to `PromptCapabilities`.
5061    ///
5062    /// The client MAY include referenced pieces of context as either
5063    /// `resource` or `resource_link` content blocks.
5064    ///
5065    /// When available, `resource` is preferred
5066    /// as it avoids extra round-trips and allows the message to include
5067    /// pieces of context from sources the agent may not have access to.
5068    ///
5069    /// Clients MUST NOT send an empty array. Agents MAY reject one with `-32602` without
5070    /// inserting it.
5071    #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
5072    pub prompt: Vec<ContentBlock>,
5073    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5074    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5075    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5076    ///
5077    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5078    #[serde_as(deserialize_as = "DefaultOnError")]
5079    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5080    #[serde(default)]
5081    #[serde(rename = "_meta")]
5082    pub meta: Option<Meta>,
5083}
5084
5085impl PromptRequest {
5086    /// Builds [`PromptRequest`] with the required request fields set. Optional fields start unset or empty.
5087    #[must_use]
5088    pub fn new(session_id: impl Into<SessionId>, prompt: Vec<ContentBlock>) -> Self {
5089        Self {
5090            session_id: session_id.into(),
5091            prompt,
5092            meta: None,
5093        }
5094    }
5095
5096    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5097    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5098    /// do not recognize.
5099    ///
5100    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5101    #[must_use]
5102    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5103        self.meta = meta.into_option();
5104        self
5105    }
5106}
5107
5108/// Response acknowledging that a user prompt was inserted into the ACP conversation.
5109///
5110/// This response does not indicate that the prompt was merely received or held, nor that the
5111/// agent has finished processing it.
5112/// Processing and completion are reported through `state_update` session updates.
5113///
5114/// Insertion is the logical addition of a user message with a message ID and a position
5115/// relative to other messages in the ACP conversation.
5116///
5117/// See protocol docs: [Prompt Accepted](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#2-prompt-accepted)
5118#[serde_as]
5119#[skip_serializing_none]
5120#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5121#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5122#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_PROMPT_METHOD_NAME)))]
5123#[serde(rename_all = "camelCase")]
5124#[non_exhaustive]
5125pub struct PromptResponse {
5126    /// Identifies the user message inserted into the ACP conversation.
5127    ///
5128    /// Required and non-null. Omission and explicit `null` are both invalid.
5129    ///
5130    /// The corresponding user-message session update carries this same identifier and may arrive
5131    /// before or after this response. Agents must echo the message during the live session, but are
5132    /// not required to retain it. If retained and replayed, the message keeps this identifier.
5133    pub message_id: MessageId,
5134    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5135    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5136    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5137    ///
5138    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5139    #[serde_as(deserialize_as = "DefaultOnError")]
5140    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5141    #[serde(default)]
5142    #[serde(rename = "_meta")]
5143    pub meta: Option<Meta>,
5144}
5145
5146impl PromptResponse {
5147    /// Builds [`PromptResponse`] with the required response fields set. Optional fields start unset or empty.
5148    #[must_use]
5149    pub fn new(message_id: impl Into<MessageId>) -> Self {
5150        Self {
5151            message_id: message_id.into(),
5152            meta: None,
5153        }
5154    }
5155
5156    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5157    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5158    /// do not recognize.
5159    ///
5160    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5161    #[must_use]
5162    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5163        self.meta = meta.into_option();
5164        self
5165    }
5166}
5167
5168/// Reasons why an agent stops active session work.
5169///
5170/// See protocol docs: [Stop Reasons](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#stop-reasons)
5171#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5172#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
5173#[serde(tag = "stopReason", rename_all = "snake_case")]
5174#[non_exhaustive]
5175pub enum StopReason {
5176    /// The active work ended successfully.
5177    /// Includes locally handled commands that required no model call.
5178    EndTurn,
5179    /// The active work ended because the agent reached the maximum number of tokens.
5180    MaxTokens,
5181    /// The active work ended because the agent reached the maximum number of
5182    /// model requests for the foreground work.
5183    MaxTurnRequests,
5184    /// The active work ended because the agent refused to continue.
5185    Refusal,
5186    /// The user or client chose to stop the work: via `session/cancel`, by
5187    /// closing the session, or through an interaction the agent offers, such
5188    /// as a permission option that tells the agent to stop. Work the agent
5189    /// stops for its own reasons uses another reason, such as `error` for an
5190    /// internal timeout.
5191    ///
5192    /// Agents MUST report this stop reason on an idle `state_update` when
5193    /// cancellation ends active foreground work, even if aborting causes
5194    /// exceptions. Agents MUST catch these errors and report `cancelled`, not
5195    /// `error`.
5196    Cancelled,
5197    /// The active work ended because something failed.
5198    ///
5199    /// This includes pre-insertion foreground work. A prompt failure before
5200    /// insertion also requires an error response to `session/prompt`. After
5201    /// insertion, the prompt's response remains successful.
5202    Error(ErrorStopReason),
5203    /// Custom or future stop reason.
5204    ///
5205    /// Values beginning with `_` are reserved for implementation-specific
5206    /// extensions. Unknown values that do not begin with `_` are reserved for
5207    /// future ACP variants.
5208    #[serde(untagged)]
5209    Other(OtherStopReason),
5210}
5211
5212impl From<ErrorStopReason> for StopReason {
5213    fn from(value: ErrorStopReason) -> Self {
5214        Self::Error(value)
5215    }
5216}
5217
5218/// Details of a failure that ended active work.
5219#[serde_as]
5220#[skip_serializing_none]
5221#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5222#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
5223#[serde(rename_all = "camelCase")]
5224#[non_exhaustive]
5225pub struct ErrorStopReason {
5226    /// The failure, as a JSON-RPC error object.
5227    ///
5228    /// Optional. Omitted and `null` are equivalent and mean the agent is not reporting failure details.
5229    /// Agents SHOULD include it.
5230    #[serde_as(deserialize_as = "DefaultOnError")]
5231    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5232    #[serde(default)]
5233    pub error: Option<Box<Error>>,
5234}
5235
5236impl ErrorStopReason {
5237    /// Builds [`ErrorStopReason`] with the required fields set. Optional fields start unset or empty.
5238    #[must_use]
5239    pub fn new() -> Self {
5240        Self::default()
5241    }
5242
5243    /// The failure, as a JSON-RPC error object.
5244    #[must_use]
5245    pub fn error(mut self, error: impl IntoOption<Error>) -> Self {
5246        self.error = error.into_option().map(Box::new);
5247        self
5248    }
5249}
5250
5251/// Custom or future stop reason payload.
5252#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5253#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
5254#[cfg_attr(feature = "schemars", schemars(inline))]
5255#[cfg_attr(feature = "schemars", schemars(transform = other_stop_reason_schema))]
5256#[serde(rename_all = "camelCase")]
5257#[non_exhaustive]
5258pub struct OtherStopReason {
5259    /// Custom or future stop reason.
5260    ///
5261    /// Values beginning with `_` are reserved for implementation-specific
5262    /// extensions. Unknown values that do not begin with `_` are reserved for
5263    /// future ACP variants.
5264    pub stop_reason: String,
5265    /// Additional fields from the unknown stop reason payload.
5266    #[serde(flatten)]
5267    pub fields: BTreeMap<String, serde_json::Value>,
5268}
5269
5270impl OtherStopReason {
5271    /// Builds [`OtherStopReason`] from an unknown discriminator and preserves the remaining extension fields.
5272    #[must_use]
5273    pub fn new(
5274        stop_reason: impl Into<String>,
5275        mut fields: BTreeMap<String, serde_json::Value>,
5276    ) -> Self {
5277        remove_idle_state_update_fields(&mut fields);
5278        Self {
5279            stop_reason: stop_reason.into(),
5280            fields,
5281        }
5282    }
5283}
5284
5285impl<'de> Deserialize<'de> for OtherStopReason {
5286    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
5287    where
5288        D: serde::Deserializer<'de>,
5289    {
5290        let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
5291        let stop_reason = fields
5292            .remove("stopReason")
5293            .ok_or_else(|| serde::de::Error::missing_field("stopReason"))?;
5294        let serde_json::Value::String(stop_reason) = stop_reason else {
5295            return Err(serde::de::Error::custom("`stopReason` must be a string"));
5296        };
5297
5298        if KNOWN_STOP_REASONS.contains(&stop_reason.as_str()) {
5299            return Err(serde::de::Error::custom(format!(
5300                "known stop reason `{stop_reason}` did not match its schema"
5301            )));
5302        }
5303        remove_idle_state_update_fields(&mut fields);
5304
5305        Ok(Self {
5306            stop_reason,
5307            fields,
5308        })
5309    }
5310}
5311
5312const KNOWN_STOP_REASONS: &[&str] = &[
5313    "end_turn",
5314    "max_tokens",
5315    "max_turn_requests",
5316    "refusal",
5317    "cancelled",
5318    "error",
5319];
5320
5321/// Keeps the idle update's own fields out of an unknown stop reason's payload.
5322fn remove_idle_state_update_fields(fields: &mut BTreeMap<String, serde_json::Value>) {
5323    fields.remove("stopReason");
5324    fields.remove("usage");
5325    fields.remove("_meta");
5326}
5327
5328#[cfg(feature = "schemars")]
5329fn other_stop_reason_schema(schema: &mut Schema) {
5330    super::schema_util::reject_known_string_discriminators(
5331        schema,
5332        "stopReason",
5333        KNOWN_STOP_REASONS,
5334    );
5335}
5336
5337/// **UNSTABLE**
5338///
5339/// This capability is not part of the spec yet, and may be removed or changed at any point.
5340///
5341/// Token usage for the foreground work that just completed, not cumulative for the session.
5342#[cfg(feature = "unstable_end_turn_token_usage")]
5343#[serde_as]
5344#[skip_serializing_none]
5345#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5346#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5347#[serde(rename_all = "camelCase")]
5348#[non_exhaustive]
5349pub struct Usage {
5350    /// Sum of all token types for the completed work.
5351    pub total_tokens: u64,
5352    /// Input tokens for the completed work.
5353    pub input_tokens: u64,
5354    /// Output tokens for the completed work.
5355    pub output_tokens: u64,
5356    /// Thought/reasoning tokens for the completed work.
5357    ///
5358    /// Omitted and `null` are equivalent and mean the count is not reported.
5359    #[serde_as(deserialize_as = "DefaultOnError")]
5360    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5361    #[serde(default)]
5362    pub thought_tokens: Option<u64>,
5363    /// Cache read tokens for the completed work.
5364    ///
5365    /// Omitted and `null` are equivalent and mean the count is not reported.
5366    #[serde_as(deserialize_as = "DefaultOnError")]
5367    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5368    #[serde(default)]
5369    pub cached_read_tokens: Option<u64>,
5370    /// Cache write tokens for the completed work.
5371    ///
5372    /// Omitted and `null` are equivalent and mean the count is not reported.
5373    #[serde_as(deserialize_as = "DefaultOnError")]
5374    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5375    #[serde(default)]
5376    pub cached_write_tokens: Option<u64>,
5377    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5378    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5379    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5380    ///
5381    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5382    #[serde_as(deserialize_as = "DefaultOnError")]
5383    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5384    #[serde(default)]
5385    #[serde(rename = "_meta")]
5386    pub meta: Option<Meta>,
5387}
5388
5389#[cfg(feature = "unstable_end_turn_token_usage")]
5390impl Usage {
5391    /// Builds [`Usage`] with the required fields set. Optional fields start unset or empty.
5392    #[must_use]
5393    pub fn new(total_tokens: u64, input_tokens: u64, output_tokens: u64) -> Self {
5394        Self {
5395            total_tokens,
5396            input_tokens,
5397            output_tokens,
5398            thought_tokens: None,
5399            cached_read_tokens: None,
5400            cached_write_tokens: None,
5401            meta: None,
5402        }
5403    }
5404
5405    /// Thought/reasoning tokens for the completed work.
5406    #[must_use]
5407    pub fn thought_tokens(mut self, thought_tokens: impl IntoOption<u64>) -> Self {
5408        self.thought_tokens = thought_tokens.into_option();
5409        self
5410    }
5411
5412    /// Cache read tokens for the completed work.
5413    #[must_use]
5414    pub fn cached_read_tokens(mut self, cached_read_tokens: impl IntoOption<u64>) -> Self {
5415        self.cached_read_tokens = cached_read_tokens.into_option();
5416        self
5417    }
5418
5419    /// Cache write tokens for the completed work.
5420    #[must_use]
5421    pub fn cached_write_tokens(mut self, cached_write_tokens: impl IntoOption<u64>) -> Self {
5422        self.cached_write_tokens = cached_write_tokens.into_option();
5423        self
5424    }
5425
5426    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5427    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5428    /// do not recognize.
5429    ///
5430    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5431    #[must_use]
5432    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5433        self.meta = meta.into_option();
5434        self
5435    }
5436}
5437
5438// Providers
5439
5440/// **UNSTABLE**
5441///
5442/// This capability is not part of the spec yet, and may be removed or changed at any point.
5443///
5444/// Well-known API protocol identifiers for LLM providers.
5445///
5446/// Agents and clients MUST handle unknown protocol identifiers gracefully.
5447///
5448/// Protocol names beginning with `_` are free for custom use, like other ACP extension methods.
5449/// Protocol names that do not begin with `_` are reserved for the ACP spec.
5450#[cfg(feature = "unstable_llm_providers")]
5451#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5452#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5453#[serde(rename_all = "snake_case")]
5454#[non_exhaustive]
5455#[expect(clippy::doc_markdown)]
5456pub enum LlmProtocol {
5457    /// Anthropic API protocol.
5458    Anthropic,
5459    /// OpenAI API protocol.
5460    #[serde(rename = "openai")]
5461    OpenAi,
5462    /// Azure OpenAI API protocol.
5463    Azure,
5464    /// Google Vertex AI API protocol.
5465    Vertex,
5466    /// AWS Bedrock API protocol.
5467    Bedrock,
5468    /// Custom or future protocol.
5469    ///
5470    /// Values beginning with `_` are reserved for implementation-specific
5471    /// extensions. Unknown values that do not begin with `_` are reserved for
5472    /// future ACP variants.
5473    #[serde(untagged)]
5474    Other(String),
5475}
5476
5477/// **UNSTABLE**
5478///
5479/// This capability is not part of the spec yet, and may be removed or changed at any point.
5480///
5481/// Current effective non-secret routing configuration for a provider.
5482#[cfg(feature = "unstable_llm_providers")]
5483#[serde_as]
5484#[skip_serializing_none]
5485#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5486#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5487#[serde(rename_all = "camelCase")]
5488#[non_exhaustive]
5489pub struct ProviderCurrentConfig {
5490    /// Protocol currently used by this provider.
5491    pub api_type: LlmProtocol,
5492    /// Base URL currently used by this provider.
5493    #[cfg_attr(feature = "schemars", schemars(url))]
5494    pub base_url: String,
5495    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5496    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5497    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5498    ///
5499    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5500    #[serde_as(deserialize_as = "DefaultOnError")]
5501    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5502    #[serde(default)]
5503    #[serde(rename = "_meta")]
5504    pub meta: Option<Meta>,
5505}
5506
5507#[cfg(feature = "unstable_llm_providers")]
5508impl ProviderCurrentConfig {
5509    /// Builds [`ProviderCurrentConfig`] with the required fields set. Optional fields start unset or empty.
5510    #[must_use]
5511    pub fn new(api_type: LlmProtocol, base_url: impl Into<String>) -> Self {
5512        Self {
5513            api_type,
5514            base_url: base_url.into(),
5515            meta: None,
5516        }
5517    }
5518
5519    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5520    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5521    /// do not recognize.
5522    ///
5523    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5524    #[must_use]
5525    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5526        self.meta = meta.into_option();
5527        self
5528    }
5529}
5530
5531/// **UNSTABLE**
5532///
5533/// This capability is not part of the spec yet, and may be removed or changed at any point.
5534///
5535/// Unique identifier for a configurable LLM provider.
5536#[cfg(feature = "unstable_llm_providers")]
5537#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5538#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
5539#[serde(transparent)]
5540#[from(forward)]
5541#[non_exhaustive]
5542pub struct ProviderId(pub Arc<str>);
5543
5544#[cfg(feature = "unstable_llm_providers")]
5545impl ProviderId {
5546    /// Wraps a protocol string as a typed [`ProviderId`].
5547    #[must_use]
5548    pub fn new(id: impl Into<Self>) -> Self {
5549        id.into()
5550    }
5551}
5552
5553/// **UNSTABLE**
5554///
5555/// This capability is not part of the spec yet, and may be removed or changed at any point.
5556///
5557/// Information about a configurable LLM provider.
5558#[cfg(feature = "unstable_llm_providers")]
5559#[serde_as]
5560#[skip_serializing_none]
5561#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5562#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5563#[serde(rename_all = "camelCase")]
5564#[non_exhaustive]
5565pub struct ProviderInfo {
5566    /// Provider identifier, for example "main" or "openai".
5567    pub provider_id: ProviderId,
5568    /// Supported protocol types for this provider.
5569    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
5570    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
5571    pub supported: Vec<LlmProtocol>,
5572    /// Whether this provider is mandatory and cannot be disabled via `providers/disable`.
5573    /// If true, clients must not call `providers/disable` for this provider ID.
5574    pub required: bool,
5575    /// Current effective non-secret routing config.
5576    /// Null or omitted means provider is disabled.
5577    #[serde(default)]
5578    pub current: Option<ProviderCurrentConfig>,
5579    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5580    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5581    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5582    ///
5583    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5584    #[serde_as(deserialize_as = "DefaultOnError")]
5585    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5586    #[serde(default)]
5587    #[serde(rename = "_meta")]
5588    pub meta: Option<Meta>,
5589}
5590
5591#[cfg(feature = "unstable_llm_providers")]
5592impl ProviderInfo {
5593    /// Builds [`ProviderInfo`] with the required fields set. Optional fields start unset or empty.
5594    #[must_use]
5595    pub fn new(
5596        provider_id: impl Into<ProviderId>,
5597        supported: Vec<LlmProtocol>,
5598        required: bool,
5599        current: impl IntoOption<ProviderCurrentConfig>,
5600    ) -> Self {
5601        Self {
5602            provider_id: provider_id.into(),
5603            supported,
5604            required,
5605            current: current.into_option(),
5606            meta: None,
5607        }
5608    }
5609
5610    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5611    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5612    /// do not recognize.
5613    ///
5614    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5615    #[must_use]
5616    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5617        self.meta = meta.into_option();
5618        self
5619    }
5620}
5621
5622#[cfg(feature = "unstable_llm_providers")]
5623crate::serde_util::default_on_null! {
5624    /// **UNSTABLE**
5625    ///
5626    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5627    ///
5628    /// Request parameters for `providers/list`.
5629    #[serde_as]
5630    #[skip_serializing_none]
5631    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5632    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
5633    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_LIST_METHOD_NAME)))]
5634    #[serde(rename_all = "camelCase")]
5635    #[non_exhaustive]
5636    pub struct ListProvidersRequest {
5637        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5638        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5639        /// Implementations MUST NOT assign meaning to keys they do not recognize.
5640        ///
5641        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5642        #[serde_as(deserialize_as = "DefaultOnError")]
5643        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5644        #[serde(default)]
5645        #[serde(rename = "_meta")]
5646        pub meta: Option<Meta>,
5647    }
5648}
5649
5650#[cfg(feature = "unstable_llm_providers")]
5651impl ListProvidersRequest {
5652    /// Builds [`ListProvidersRequest`] with the required request fields set. Optional fields start unset or empty.
5653    #[must_use]
5654    pub fn new() -> Self {
5655        Self::default()
5656    }
5657
5658    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5659    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5660    /// do not recognize.
5661    ///
5662    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5663    #[must_use]
5664    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5665        self.meta = meta.into_option();
5666        self
5667    }
5668}
5669
5670/// **UNSTABLE**
5671///
5672/// This capability is not part of the spec yet, and may be removed or changed at any point.
5673///
5674/// Response to `providers/list`.
5675#[cfg(feature = "unstable_llm_providers")]
5676#[serde_as]
5677#[skip_serializing_none]
5678#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5679#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5680#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_LIST_METHOD_NAME)))]
5681#[serde(rename_all = "camelCase")]
5682#[non_exhaustive]
5683pub struct ListProvidersResponse {
5684    /// Configurable providers with current routing info suitable for UI display.
5685    pub providers: Vec<ProviderInfo>,
5686    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5687    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5688    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5689    ///
5690    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5691    #[serde_as(deserialize_as = "DefaultOnError")]
5692    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5693    #[serde(default)]
5694    #[serde(rename = "_meta")]
5695    pub meta: Option<Meta>,
5696}
5697
5698#[cfg(feature = "unstable_llm_providers")]
5699impl ListProvidersResponse {
5700    /// Builds [`ListProvidersResponse`] with the required response fields set. Optional fields start unset or empty.
5701    #[must_use]
5702    pub fn new(providers: Vec<ProviderInfo>) -> Self {
5703        Self {
5704            providers,
5705            meta: None,
5706        }
5707    }
5708
5709    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5710    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5711    /// do not recognize.
5712    ///
5713    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5714    #[must_use]
5715    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5716        self.meta = meta.into_option();
5717        self
5718    }
5719}
5720
5721/// **UNSTABLE**
5722///
5723/// This capability is not part of the spec yet, and may be removed or changed at any point.
5724///
5725/// Request parameters for `providers/set`.
5726///
5727/// Replaces the full configuration for one provider ID.
5728#[cfg(feature = "unstable_llm_providers")]
5729#[serde_as]
5730#[skip_serializing_none]
5731#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5732#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
5733#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_SET_METHOD_NAME)))]
5734#[serde(rename_all = "camelCase")]
5735#[non_exhaustive]
5736pub struct SetProviderRequest {
5737    /// Provider ID to configure.
5738    pub provider_id: ProviderId,
5739    /// Protocol type for this provider.
5740    pub api_type: LlmProtocol,
5741    /// Base URL for requests sent through this provider.
5742    #[cfg_attr(feature = "schemars", schemars(url))]
5743    pub base_url: String,
5744    /// Full headers map for this provider.
5745    /// May include authorization, routing, or other integration-specific headers.
5746    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
5747    pub headers: HashMap<String, String>,
5748    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5749    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5750    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5751    ///
5752    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5753    #[serde_as(deserialize_as = "DefaultOnError")]
5754    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5755    #[serde(default)]
5756    #[serde(rename = "_meta")]
5757    pub meta: Option<Meta>,
5758}
5759
5760#[cfg(feature = "unstable_llm_providers")]
5761impl SetProviderRequest {
5762    /// Builds [`SetProviderRequest`] with the required request fields set. Optional fields start unset or empty.
5763    #[must_use]
5764    pub fn new(
5765        provider_id: impl Into<ProviderId>,
5766        api_type: LlmProtocol,
5767        base_url: impl Into<String>,
5768    ) -> Self {
5769        Self {
5770            provider_id: provider_id.into(),
5771            api_type,
5772            base_url: base_url.into(),
5773            headers: HashMap::new(),
5774            meta: None,
5775        }
5776    }
5777
5778    /// Full headers map for this provider.
5779    /// May include authorization, routing, or other integration-specific headers.
5780    #[must_use]
5781    pub fn headers(mut self, headers: HashMap<String, String>) -> Self {
5782        self.headers = headers;
5783        self
5784    }
5785
5786    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5787    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5788    /// do not recognize.
5789    ///
5790    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5791    #[must_use]
5792    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5793        self.meta = meta.into_option();
5794        self
5795    }
5796}
5797
5798#[cfg(feature = "unstable_llm_providers")]
5799crate::serde_util::default_on_null! {
5800    /// **UNSTABLE**
5801    ///
5802    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5803    ///
5804    /// Response to `providers/set`.
5805    #[serde_as]
5806    #[skip_serializing_none]
5807    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5808    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
5809    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_SET_METHOD_NAME)))]
5810    #[serde(rename_all = "camelCase")]
5811    #[non_exhaustive]
5812    pub struct SetProviderResponse {
5813        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5814        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5815        /// Implementations MUST NOT assign meaning to keys they do not recognize.
5816        ///
5817        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5818        #[serde_as(deserialize_as = "DefaultOnError")]
5819        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5820        #[serde(default)]
5821        #[serde(rename = "_meta")]
5822        pub meta: Option<Meta>,
5823    }
5824}
5825
5826#[cfg(feature = "unstable_llm_providers")]
5827impl SetProviderResponse {
5828    /// Builds [`SetProviderResponse`] with the required response fields set. Optional fields start unset or empty.
5829    #[must_use]
5830    pub fn new() -> Self {
5831        Self::default()
5832    }
5833
5834    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5835    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5836    /// do not recognize.
5837    ///
5838    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5839    #[must_use]
5840    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5841        self.meta = meta.into_option();
5842        self
5843    }
5844}
5845
5846/// **UNSTABLE**
5847///
5848/// This capability is not part of the spec yet, and may be removed or changed at any point.
5849///
5850/// Request parameters for `providers/disable`.
5851#[cfg(feature = "unstable_llm_providers")]
5852#[serde_as]
5853#[skip_serializing_none]
5854#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5855#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5856#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_DISABLE_METHOD_NAME)))]
5857#[serde(rename_all = "camelCase")]
5858#[non_exhaustive]
5859pub struct DisableProviderRequest {
5860    /// Provider ID to disable.
5861    pub provider_id: ProviderId,
5862    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5863    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5864    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5865    ///
5866    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5867    #[serde_as(deserialize_as = "DefaultOnError")]
5868    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5869    #[serde(default)]
5870    #[serde(rename = "_meta")]
5871    pub meta: Option<Meta>,
5872}
5873
5874#[cfg(feature = "unstable_llm_providers")]
5875impl DisableProviderRequest {
5876    /// Builds [`DisableProviderRequest`] with the required request fields set. Optional fields start unset or empty.
5877    #[must_use]
5878    pub fn new(provider_id: impl Into<ProviderId>) -> Self {
5879        Self {
5880            provider_id: provider_id.into(),
5881            meta: None,
5882        }
5883    }
5884
5885    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5886    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5887    /// do not recognize.
5888    ///
5889    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5890    #[must_use]
5891    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5892        self.meta = meta.into_option();
5893        self
5894    }
5895}
5896
5897#[cfg(feature = "unstable_llm_providers")]
5898crate::serde_util::default_on_null! {
5899    /// **UNSTABLE**
5900    ///
5901    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5902    ///
5903    /// Response to `providers/disable`.
5904    #[serde_as]
5905    #[skip_serializing_none]
5906    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5907    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
5908    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_DISABLE_METHOD_NAME)))]
5909    #[serde(rename_all = "camelCase")]
5910    #[non_exhaustive]
5911    pub struct DisableProviderResponse {
5912        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5913        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5914        /// Implementations MUST NOT assign meaning to keys they do not recognize.
5915        ///
5916        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5917        #[serde_as(deserialize_as = "DefaultOnError")]
5918        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5919        #[serde(default)]
5920        #[serde(rename = "_meta")]
5921        pub meta: Option<Meta>,
5922    }
5923}
5924
5925#[cfg(feature = "unstable_llm_providers")]
5926impl DisableProviderResponse {
5927    /// Builds [`DisableProviderResponse`] with the required response fields set. Optional fields start unset or empty.
5928    #[must_use]
5929    pub fn new() -> Self {
5930        Self::default()
5931    }
5932
5933    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5934    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5935    /// do not recognize.
5936    ///
5937    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5938    #[must_use]
5939    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5940        self.meta = meta.into_option();
5941        self
5942    }
5943}
5944
5945// Capabilities
5946
5947/// Capabilities supported by the agent.
5948///
5949/// Advertised during initialization to inform the client about
5950/// available features and content types.
5951///
5952/// See protocol docs: [Agent Capabilities](https://agentclientprotocol.com/protocol/v2/initialization#agent-capabilities)
5953#[serde_as]
5954#[skip_serializing_none]
5955#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5956#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5957#[serde(rename_all = "camelCase")]
5958#[non_exhaustive]
5959pub struct AgentCapabilities {
5960    /// Session capabilities supported by the agent.
5961    ///
5962    /// Optional. Omitted and `null` are equivalent and mean the agent does not support the
5963    /// `session/*` methods. Supplying `{}` means the agent supports the
5964    /// baseline session methods: `session/new`, `session/list`,
5965    /// `session/resume`, `session/close`, `session/prompt`, `session/cancel`,
5966    /// and `session/update`.
5967    #[serde_as(deserialize_as = "DefaultOnError")]
5968    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5969    #[serde(default)]
5970    pub session: Option<SessionCapabilities>,
5971    /// Authentication-related extension capabilities supported by the agent.
5972    ///
5973    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise any
5974    /// authentication-related extensions. This field does not advertise support
5975    /// for `auth/login` or `auth/logout`. Those methods are advertised by a
5976    /// non-empty `authMethods` list in the `initialize` response.
5977    #[serde_as(deserialize_as = "DefaultOnError")]
5978    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5979    #[serde(default)]
5980    pub auth: Option<AgentAuthCapabilities>,
5981    /// **UNSTABLE**
5982    ///
5983    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5984    ///
5985    /// Provider configuration capabilities supported by the agent.
5986    ///
5987    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
5988    /// Supplying `{}` means the agent supports provider configuration methods.
5989    #[cfg(feature = "unstable_llm_providers")]
5990    #[serde_as(deserialize_as = "DefaultOnError")]
5991    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5992    #[serde(default)]
5993    pub providers: Option<ProvidersCapabilities>,
5994    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5995    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5996    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5997    ///
5998    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5999    #[serde_as(deserialize_as = "DefaultOnError")]
6000    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6001    #[serde(default)]
6002    #[serde(rename = "_meta")]
6003    pub meta: Option<Meta>,
6004}
6005
6006impl AgentCapabilities {
6007    /// Builds an empty [`AgentCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6008    #[must_use]
6009    pub fn new() -> Self {
6010        Self::default()
6011    }
6012
6013    /// Session capabilities supported by the agent.
6014    ///
6015    /// Omitted and `null` are equivalent and mean the agent does not support the `session/*`
6016    /// methods. Supplying `{}` means the agent supports the baseline
6017    /// session methods: `session/new`, `session/list`, `session/resume`,
6018    /// `session/close`, `session/prompt`, `session/cancel`, and
6019    /// `session/update`.
6020    #[must_use]
6021    pub fn session(mut self, session: impl IntoOption<SessionCapabilities>) -> Self {
6022        self.session = session.into_option();
6023        self
6024    }
6025
6026    /// Authentication-related extension capabilities supported by the agent.
6027    ///
6028    /// This field does not advertise support for `auth/login` or `auth/logout`.
6029    #[must_use]
6030    pub fn auth(mut self, auth: impl IntoOption<AgentAuthCapabilities>) -> Self {
6031        self.auth = auth.into_option();
6032        self
6033    }
6034
6035    /// **UNSTABLE**
6036    ///
6037    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6038    ///
6039    /// Provider configuration capabilities supported by the agent.
6040    #[cfg(feature = "unstable_llm_providers")]
6041    #[must_use]
6042    pub fn providers(mut self, providers: impl IntoOption<ProvidersCapabilities>) -> Self {
6043        self.providers = providers.into_option();
6044        self
6045    }
6046
6047    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6048    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6049    /// do not recognize.
6050    ///
6051    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6052    #[must_use]
6053    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6054        self.meta = meta.into_option();
6055        self
6056    }
6057}
6058
6059/// **UNSTABLE**
6060///
6061/// This capability is not part of the spec yet, and may be removed or changed at any point.
6062///
6063/// Provider configuration capabilities supported by the agent.
6064///
6065/// Supplying `{}` means the agent supports provider configuration methods.
6066#[cfg(feature = "unstable_llm_providers")]
6067#[serde_as]
6068#[skip_serializing_none]
6069#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6070#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6071#[non_exhaustive]
6072pub struct ProvidersCapabilities {
6073    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6074    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6075    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6076    ///
6077    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6078    #[serde_as(deserialize_as = "DefaultOnError")]
6079    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6080    #[serde(default)]
6081    #[serde(rename = "_meta")]
6082    pub meta: Option<Meta>,
6083}
6084
6085#[cfg(feature = "unstable_llm_providers")]
6086impl ProvidersCapabilities {
6087    /// Builds an empty [`ProvidersCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6088    #[must_use]
6089    pub fn new() -> Self {
6090        Self::default()
6091    }
6092
6093    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6094    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6095    /// do not recognize.
6096    ///
6097    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6098    #[must_use]
6099    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6100        self.meta = meta.into_option();
6101        self
6102    }
6103}
6104
6105/// Session capabilities supported by the agent.
6106///
6107/// Supplying `{}` means the agent supports the baseline session methods:
6108/// `session/new`, `session/list`, `session/resume`, `session/close`,
6109/// `session/prompt`, `session/cancel`, and `session/update`.
6110///
6111/// Agents that support sessions **MAY** support additional session methods,
6112/// prompt content types, and MCP transports by specifying additional
6113/// capabilities.
6114///
6115/// See protocol docs: [Session Capabilities](https://agentclientprotocol.com/protocol/v2/initialization#session-capabilities)
6116#[serde_as]
6117#[skip_serializing_none]
6118#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6119#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6120#[serde(rename_all = "camelCase")]
6121#[non_exhaustive]
6122pub struct SessionCapabilities {
6123    /// Prompt capabilities supported by the agent in `session/prompt` requests.
6124    ///
6125    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise any
6126    /// prompt extensions beyond the baseline text and resource-link content
6127    /// required by `session/prompt`.
6128    #[serde_as(deserialize_as = "DefaultOnError")]
6129    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6130    #[serde(default)]
6131    pub prompt: Option<PromptCapabilities>,
6132    /// MCP capabilities supported by the agent for session lifecycle requests.
6133    ///
6134    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise MCP
6135    /// server transport support for sessions.
6136    #[serde_as(deserialize_as = "DefaultOnError")]
6137    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6138    #[serde(default)]
6139    pub mcp: Option<McpCapabilities>,
6140    /// Whether the agent supports `session/delete`.
6141    ///
6142    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
6143    /// Supplying `{}` means the agent supports deleting sessions from `session/list`.
6144    #[serde_as(deserialize_as = "DefaultOnError")]
6145    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6146    #[serde(default)]
6147    pub delete: Option<SessionDeleteCapabilities>,
6148    /// Whether the agent supports `additionalDirectories` on supported session lifecycle requests.
6149    ///
6150    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
6151    /// Supplying `{}` means the agent supports `additionalDirectories` on
6152    /// supported session lifecycle requests.
6153    ///
6154    /// Agents may return `SessionInfo.additionalDirectories` to report the
6155    /// complete ordered additional-root list associated with a listed session.
6156    #[serde_as(deserialize_as = "DefaultOnError")]
6157    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6158    #[serde(default)]
6159    pub additional_directories: Option<SessionAdditionalDirectoriesCapabilities>,
6160    /// Whether the agent supports `systemPrompt` on session lifecycle requests.
6161    ///
6162    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
6163    /// Supplying `{}` means the agent supports `systemPrompt` in `append` mode.
6164    #[serde_as(deserialize_as = "DefaultOnError")]
6165    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6166    #[serde(default)]
6167    pub system_prompt: Option<SessionSystemPromptCapabilities>,
6168    /// **UNSTABLE**
6169    ///
6170    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6171    ///
6172    /// Whether the agent supports `session/fork`.
6173    ///
6174    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
6175    /// Supplying `{}` means the agent supports forking sessions.
6176    #[cfg(feature = "unstable_session_fork")]
6177    #[serde_as(deserialize_as = "DefaultOnError")]
6178    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6179    #[serde(default)]
6180    pub fork: Option<SessionForkCapabilities>,
6181    /// **UNSTABLE**
6182    ///
6183    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6184    ///
6185    /// Whether the agent supports `session/archive` and `session/unarchive`.
6186    ///
6187    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
6188    /// Supplying `{}` means the agent supports both methods, the `archived` filter on
6189    /// `session/list`, and `SessionInfo.archived`.
6190    #[cfg(feature = "unstable_session_archive")]
6191    #[serde_as(deserialize_as = "DefaultOnError")]
6192    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6193    #[serde(default)]
6194    pub archive: Option<SessionArchiveCapabilities>,
6195    /// **UNSTABLE**
6196    ///
6197    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6198    ///
6199    /// Whether the agent supports `session/status`.
6200    ///
6201    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
6202    /// Supplying `{}` means the agent supports checking session status.
6203    #[cfg(feature = "unstable_session_status")]
6204    #[serde_as(deserialize_as = "DefaultOnError")]
6205    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6206    #[serde(default)]
6207    pub status: Option<SessionStatusCapabilities>,
6208    /// **UNSTABLE**
6209    ///
6210    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6211    ///
6212    /// Whether the agent supports `session/options`.
6213    ///
6214    /// Optional. Omitted or `null` both mean the agent does not advertise support.
6215    /// Supplying `{}` means the agent supports `session/options` and accepts initial
6216    /// config option values on session setup requests.
6217    #[cfg(feature = "unstable_session_options")]
6218    #[serde_as(deserialize_as = "DefaultOnError")]
6219    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6220    #[serde(default)]
6221    pub options: Option<SessionOptionsCapabilities>,
6222    /// **UNSTABLE**
6223    ///
6224    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6225    ///
6226    /// Whether the agent supports `session/set_title`.
6227    ///
6228    /// Agents report titles through `session/list` and `session_info_update` without this
6229    /// capability. It only advertises that Clients can set titles.
6230    ///
6231    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
6232    /// Supplying `{}` means the agent supports setting session titles.
6233    #[cfg(feature = "unstable_session_set_title")]
6234    #[serde_as(deserialize_as = "DefaultOnError")]
6235    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6236    #[serde(default)]
6237    pub title: Option<SessionTitleCapabilities>,
6238    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6239    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6240    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6241    ///
6242    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6243    #[serde_as(deserialize_as = "DefaultOnError")]
6244    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6245    #[serde(default)]
6246    #[serde(rename = "_meta")]
6247    pub meta: Option<Meta>,
6248}
6249
6250impl SessionCapabilities {
6251    /// Builds an empty [`SessionCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6252    #[must_use]
6253    pub fn new() -> Self {
6254        Self::default()
6255    }
6256
6257    /// Prompt capabilities supported by the agent in `session/prompt` requests.
6258    ///
6259    /// Omitted and `null` are equivalent and mean the agent does not advertise any prompt
6260    /// extensions beyond the baseline text and resource-link content required by
6261    /// `session/prompt`.
6262    #[must_use]
6263    pub fn prompt(mut self, prompt: impl IntoOption<PromptCapabilities>) -> Self {
6264        self.prompt = prompt.into_option();
6265        self
6266    }
6267
6268    /// MCP capabilities supported by the agent for session lifecycle requests.
6269    ///
6270    /// Omitted and `null` are equivalent and mean the agent does not advertise MCP server
6271    /// transport support for sessions.
6272    #[must_use]
6273    pub fn mcp(mut self, mcp: impl IntoOption<McpCapabilities>) -> Self {
6274        self.mcp = mcp.into_option();
6275        self
6276    }
6277
6278    /// Whether the agent supports `session/delete`.
6279    ///
6280    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
6281    /// Supplying `{}` means the agent supports deleting sessions from `session/list`.
6282    #[must_use]
6283    pub fn delete(mut self, delete: impl IntoOption<SessionDeleteCapabilities>) -> Self {
6284        self.delete = delete.into_option();
6285        self
6286    }
6287
6288    /// Whether the agent supports `additionalDirectories` on supported session lifecycle requests.
6289    ///
6290    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
6291    /// Supplying `{}` means the agent supports `additionalDirectories` on
6292    /// supported session lifecycle requests.
6293    ///
6294    /// Agents may return `SessionInfo.additionalDirectories` to report the
6295    /// complete ordered additional-root list associated with a listed session.
6296    #[must_use]
6297    pub fn additional_directories(
6298        mut self,
6299        additional_directories: impl IntoOption<SessionAdditionalDirectoriesCapabilities>,
6300    ) -> Self {
6301        self.additional_directories = additional_directories.into_option();
6302        self
6303    }
6304
6305    /// Whether the agent supports `systemPrompt` on session lifecycle requests.
6306    ///
6307    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
6308    /// Supplying `{}` means the agent supports `systemPrompt` in `append` mode.
6309    #[must_use]
6310    pub fn system_prompt(
6311        mut self,
6312        system_prompt: impl IntoOption<SessionSystemPromptCapabilities>,
6313    ) -> Self {
6314        self.system_prompt = system_prompt.into_option();
6315        self
6316    }
6317
6318    #[cfg(feature = "unstable_session_fork")]
6319    /// Whether the agent supports `session/fork`.
6320    ///
6321    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
6322    /// Supplying `{}` means the agent supports forking sessions.
6323    #[must_use]
6324    pub fn fork(mut self, fork: impl IntoOption<SessionForkCapabilities>) -> Self {
6325        self.fork = fork.into_option();
6326        self
6327    }
6328
6329    /// **UNSTABLE**
6330    ///
6331    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6332    ///
6333    /// Whether the agent supports `session/archive` and `session/unarchive`.
6334    ///
6335    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
6336    /// Supplying `{}` means the agent supports both methods, the `archived` filter on
6337    /// `session/list`, and `SessionInfo.archived`.
6338    #[cfg(feature = "unstable_session_archive")]
6339    #[must_use]
6340    pub fn archive(mut self, archive: impl IntoOption<SessionArchiveCapabilities>) -> Self {
6341        self.archive = archive.into_option();
6342        self
6343    }
6344
6345    /// **UNSTABLE**
6346    ///
6347    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6348    ///
6349    /// Whether the agent supports `session/status`.
6350    ///
6351    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
6352    /// Supplying `{}` means the agent supports checking session status.
6353    #[cfg(feature = "unstable_session_status")]
6354    #[must_use]
6355    pub fn status(mut self, status: impl IntoOption<SessionStatusCapabilities>) -> Self {
6356        self.status = status.into_option();
6357        self
6358    }
6359
6360    /// **UNSTABLE**
6361    ///
6362    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6363    ///
6364    /// Whether the agent supports `session/options`.
6365    ///
6366    /// Omitted or `null` both mean the agent does not advertise support.
6367    /// Supplying `{}` means the agent supports `session/options` and accepts initial
6368    /// config option values on session setup requests.
6369    #[cfg(feature = "unstable_session_options")]
6370    #[must_use]
6371    pub fn options(mut self, options: impl IntoOption<SessionOptionsCapabilities>) -> Self {
6372        self.options = options.into_option();
6373        self
6374    }
6375
6376    /// **UNSTABLE**
6377    ///
6378    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6379    ///
6380    /// Whether the agent supports `session/set_title`.
6381    ///
6382    /// Agents report titles through `session/list` and `session_info_update` without this
6383    /// capability. It only advertises that Clients can set titles.
6384    ///
6385    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
6386    /// Supplying `{}` means the agent supports setting session titles.
6387    #[cfg(feature = "unstable_session_set_title")]
6388    #[must_use]
6389    pub fn title(mut self, title: impl IntoOption<SessionTitleCapabilities>) -> Self {
6390        self.title = title.into_option();
6391        self
6392    }
6393
6394    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6395    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6396    /// do not recognize.
6397    ///
6398    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6399    #[must_use]
6400    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6401        self.meta = meta.into_option();
6402        self
6403    }
6404}
6405
6406/// Capabilities for the `session/delete` method.
6407///
6408/// Supplying `{}` means the agent supports deleting sessions from `session/list`.
6409#[serde_as]
6410#[skip_serializing_none]
6411#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6412#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6413#[non_exhaustive]
6414pub struct SessionDeleteCapabilities {
6415    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6416    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6417    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6418    ///
6419    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6420    #[serde_as(deserialize_as = "DefaultOnError")]
6421    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6422    #[serde(default)]
6423    #[serde(rename = "_meta")]
6424    pub meta: Option<Meta>,
6425}
6426
6427impl SessionDeleteCapabilities {
6428    /// Builds an empty [`SessionDeleteCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6429    #[must_use]
6430    pub fn new() -> Self {
6431        Self::default()
6432    }
6433
6434    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6435    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6436    /// do not recognize.
6437    ///
6438    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6439    #[must_use]
6440    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6441        self.meta = meta.into_option();
6442        self
6443    }
6444}
6445
6446/// Capabilities for additional session directories support.
6447///
6448/// Supplying `{}` means the agent supports the `additionalDirectories` field on
6449/// supported session lifecycle requests. Agents may return
6450/// `SessionInfo.additionalDirectories` in `session/list` to report the
6451/// complete ordered additional-root list associated with a listed session.
6452#[serde_as]
6453#[skip_serializing_none]
6454#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6455#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6456#[non_exhaustive]
6457pub struct SessionAdditionalDirectoriesCapabilities {
6458    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6459    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6460    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6461    ///
6462    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6463    #[serde_as(deserialize_as = "DefaultOnError")]
6464    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6465    #[serde(default)]
6466    #[serde(rename = "_meta")]
6467    pub meta: Option<Meta>,
6468}
6469
6470impl SessionAdditionalDirectoriesCapabilities {
6471    /// Builds an empty [`SessionAdditionalDirectoriesCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6472    #[must_use]
6473    pub fn new() -> Self {
6474        Self::default()
6475    }
6476
6477    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6478    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6479    /// do not recognize.
6480    ///
6481    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6482    #[must_use]
6483    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6484        self.meta = meta.into_option();
6485        self
6486    }
6487}
6488
6489/// Capabilities for client-provided system prompts.
6490///
6491/// Supplying `{}` means the agent supports `systemPrompt` on session lifecycle
6492/// requests in `append` mode.
6493#[serde_as]
6494#[skip_serializing_none]
6495#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6496#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6497#[serde(rename_all = "camelCase")]
6498#[non_exhaustive]
6499pub struct SessionSystemPromptCapabilities {
6500    /// Delivery modes the agent supports in addition to `append`.
6501    ///
6502    /// Optional. Omitted and `null` are equivalent and mean the agent supports only `append`.
6503    #[serde_as(deserialize_as = "DefaultOnError")]
6504    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6505    #[serde(default)]
6506    pub mode: Option<SessionSystemPromptModeCapabilities>,
6507    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6508    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6509    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6510    ///
6511    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6512    #[serde_as(deserialize_as = "DefaultOnError")]
6513    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6514    #[serde(default)]
6515    #[serde(rename = "_meta")]
6516    pub meta: Option<Meta>,
6517}
6518
6519impl SessionSystemPromptCapabilities {
6520    /// Builds an empty [`SessionSystemPromptCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6521    #[must_use]
6522    pub fn new() -> Self {
6523        Self::default()
6524    }
6525
6526    /// Delivery modes the agent supports in addition to `append`.
6527    ///
6528    /// Omitted and `null` are equivalent and mean the agent supports only `append`.
6529    #[must_use]
6530    pub fn mode(mut self, mode: impl IntoOption<SessionSystemPromptModeCapabilities>) -> Self {
6531        self.mode = mode.into_option();
6532        self
6533    }
6534
6535    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6536    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6537    /// do not recognize.
6538    ///
6539    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6540    #[must_use]
6541    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6542        self.meta = meta.into_option();
6543        self
6544    }
6545}
6546
6547/// System prompt delivery modes the agent supports in addition to `append`.
6548///
6549/// `append` has no entry because every agent advertising `session.systemPrompt`
6550/// supports it.
6551#[serde_as]
6552#[skip_serializing_none]
6553#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6554#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6555#[serde(rename_all = "camelCase")]
6556#[non_exhaustive]
6557pub struct SessionSystemPromptModeCapabilities {
6558    /// Whether the agent supports `override` mode.
6559    ///
6560    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
6561    /// Supplying `{}` means the agent supports replacing its built-in default
6562    /// instructions with the client-provided system prompt.
6563    #[serde_as(deserialize_as = "DefaultOnError")]
6564    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6565    #[serde(default, rename = "override")]
6566    pub override_: Option<SessionSystemPromptOverrideCapabilities>,
6567    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6568    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6569    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6570    ///
6571    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6572    #[serde_as(deserialize_as = "DefaultOnError")]
6573    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6574    #[serde(default)]
6575    #[serde(rename = "_meta")]
6576    pub meta: Option<Meta>,
6577}
6578
6579impl SessionSystemPromptModeCapabilities {
6580    /// Builds an empty [`SessionSystemPromptModeCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6581    #[must_use]
6582    pub fn new() -> Self {
6583        Self::default()
6584    }
6585
6586    /// Whether the agent supports `override` mode.
6587    ///
6588    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
6589    /// Supplying `{}` means the agent supports replacing its built-in default
6590    /// instructions with the client-provided system prompt.
6591    #[must_use]
6592    pub fn override_(
6593        mut self,
6594        override_: impl IntoOption<SessionSystemPromptOverrideCapabilities>,
6595    ) -> Self {
6596        self.override_ = override_.into_option();
6597        self
6598    }
6599
6600    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6601    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6602    /// do not recognize.
6603    ///
6604    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6605    #[must_use]
6606    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6607        self.meta = meta.into_option();
6608        self
6609    }
6610}
6611
6612/// Capabilities for the `override` system prompt mode.
6613///
6614/// Supplying `{}` means the agent supports replacing its built-in default
6615/// instructions with the client-provided system prompt.
6616#[serde_as]
6617#[skip_serializing_none]
6618#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6619#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6620#[non_exhaustive]
6621pub struct SessionSystemPromptOverrideCapabilities {
6622    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6623    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6624    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6625    ///
6626    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6627    #[serde_as(deserialize_as = "DefaultOnError")]
6628    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6629    #[serde(default)]
6630    #[serde(rename = "_meta")]
6631    pub meta: Option<Meta>,
6632}
6633
6634impl SessionSystemPromptOverrideCapabilities {
6635    /// Builds an empty [`SessionSystemPromptOverrideCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6636    #[must_use]
6637    pub fn new() -> Self {
6638        Self::default()
6639    }
6640
6641    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6642    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6643    /// do not recognize.
6644    ///
6645    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6646    #[must_use]
6647    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6648        self.meta = meta.into_option();
6649        self
6650    }
6651}
6652
6653/// **UNSTABLE**
6654///
6655/// This capability is not part of the spec yet, and may be removed or changed at any point.
6656///
6657/// Capabilities for the `session/fork` method.
6658///
6659/// Supplying `{}` means the agent supports forking sessions.
6660#[cfg(feature = "unstable_session_fork")]
6661#[serde_as]
6662#[skip_serializing_none]
6663#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6664#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6665#[non_exhaustive]
6666pub struct SessionForkCapabilities {
6667    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6668    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6669    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6670    ///
6671    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6672    #[serde_as(deserialize_as = "DefaultOnError")]
6673    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6674    #[serde(default)]
6675    #[serde(rename = "_meta")]
6676    pub meta: Option<Meta>,
6677}
6678
6679#[cfg(feature = "unstable_session_fork")]
6680impl SessionForkCapabilities {
6681    /// Builds an empty [`SessionForkCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6682    #[must_use]
6683    pub fn new() -> Self {
6684        Self::default()
6685    }
6686
6687    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6688    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6689    /// do not recognize.
6690    ///
6691    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6692    #[must_use]
6693    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6694        self.meta = meta.into_option();
6695        self
6696    }
6697}
6698
6699/// **UNSTABLE**
6700///
6701/// This capability is not part of the spec yet, and may be removed or changed at any point.
6702///
6703/// Capabilities for `session/archive` and `session/unarchive`.
6704///
6705/// Supplying `{}` means the agent supports both methods, the `archived` filter on
6706/// `session/list`, and `SessionInfo.archived`.
6707#[cfg(feature = "unstable_session_archive")]
6708#[serde_as]
6709#[skip_serializing_none]
6710#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6711#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6712#[non_exhaustive]
6713pub struct SessionArchiveCapabilities {
6714    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6715    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6716    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6717    ///
6718    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6719    #[serde_as(deserialize_as = "DefaultOnError")]
6720    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6721    #[serde(default)]
6722    #[serde(rename = "_meta")]
6723    pub meta: Option<Meta>,
6724}
6725
6726#[cfg(feature = "unstable_session_archive")]
6727impl SessionArchiveCapabilities {
6728    /// Builds an empty [`SessionArchiveCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6729    #[must_use]
6730    pub fn new() -> Self {
6731        Self::default()
6732    }
6733
6734    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6735    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6736    /// do not recognize.
6737    ///
6738    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6739    #[must_use]
6740    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6741        self.meta = meta.into_option();
6742        self
6743    }
6744}
6745
6746/// **UNSTABLE**
6747///
6748/// This capability is not part of the spec yet, and may be removed or changed at any point.
6749///
6750/// Capabilities for the `session/status` method.
6751///
6752/// Supplying `{}` means the agent supports checking session status.
6753#[cfg(feature = "unstable_session_status")]
6754#[serde_as]
6755#[skip_serializing_none]
6756#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6757#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6758#[non_exhaustive]
6759pub struct SessionStatusCapabilities {
6760    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6761    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6762    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6763    ///
6764    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6765    #[serde_as(deserialize_as = "DefaultOnError")]
6766    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6767    #[serde(default)]
6768    #[serde(rename = "_meta")]
6769    pub meta: Option<Meta>,
6770}
6771
6772#[cfg(feature = "unstable_session_status")]
6773impl SessionStatusCapabilities {
6774    /// Builds an empty [`SessionStatusCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6775    #[must_use]
6776    pub fn new() -> Self {
6777        Self::default()
6778    }
6779
6780    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6781    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6782    /// do not recognize.
6783    ///
6784    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6785    #[must_use]
6786    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6787        self.meta = meta.into_option();
6788        self
6789    }
6790}
6791
6792/// **UNSTABLE**
6793///
6794/// This capability is not part of the spec yet, and may be removed or changed at any point.
6795///
6796/// Capabilities for the `session/options` method.
6797///
6798/// Supplying `{}` means the agent supports `session/options` and accepts initial config
6799/// option values on session setup requests.
6800#[cfg(feature = "unstable_session_options")]
6801#[serde_as]
6802#[skip_serializing_none]
6803#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6804#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6805#[non_exhaustive]
6806pub struct SessionOptionsCapabilities {
6807    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6808    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6809    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6810    ///
6811    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6812    #[serde_as(deserialize_as = "DefaultOnError")]
6813    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6814    #[serde(default)]
6815    #[serde(rename = "_meta")]
6816    pub meta: Option<Meta>,
6817}
6818
6819#[cfg(feature = "unstable_session_options")]
6820impl SessionOptionsCapabilities {
6821    /// Builds an empty [`SessionOptionsCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6822    #[must_use]
6823    pub fn new() -> Self {
6824        Self::default()
6825    }
6826
6827    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6828    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6829    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6830    ///
6831    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6832    #[must_use]
6833    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6834        self.meta = meta.into_option();
6835        self
6836    }
6837}
6838
6839/// **UNSTABLE**
6840///
6841/// This capability is not part of the spec yet, and may be removed or changed at any point.
6842///
6843/// Capabilities for Client-set session titles.
6844///
6845/// Supplying `{}` means the agent supports `session/set_title`. Agents report titles
6846/// through `session/list` and `session_info_update` without this capability.
6847#[cfg(feature = "unstable_session_set_title")]
6848#[serde_as]
6849#[skip_serializing_none]
6850#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6851#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6852#[non_exhaustive]
6853pub struct SessionTitleCapabilities {
6854    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6855    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6856    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6857    ///
6858    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6859    #[serde_as(deserialize_as = "DefaultOnError")]
6860    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6861    #[serde(default)]
6862    #[serde(rename = "_meta")]
6863    pub meta: Option<Meta>,
6864}
6865
6866#[cfg(feature = "unstable_session_set_title")]
6867impl SessionTitleCapabilities {
6868    /// Builds an empty [`SessionTitleCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6869    #[must_use]
6870    pub fn new() -> Self {
6871        Self::default()
6872    }
6873
6874    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6875    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6876    /// do not recognize.
6877    ///
6878    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6879    #[must_use]
6880    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6881        self.meta = meta.into_option();
6882        self
6883    }
6884}
6885
6886/// Prompt capabilities supported by the agent in `session/prompt` requests.
6887///
6888/// Baseline agent functionality requires support for `text`
6889/// and `resource_link` content blocks in prompt requests.
6890///
6891/// Other variants must be explicitly opted in to.
6892/// Capabilities for different types of content in prompt requests.
6893///
6894/// Indicates which content types beyond the baseline (text and resource links)
6895/// the agent can process.
6896///
6897/// See protocol docs: [Session Prompt Capabilities](https://agentclientprotocol.com/protocol/v2/initialization#session-prompt-capabilities)
6898#[serde_as]
6899#[skip_serializing_none]
6900#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6901#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6902#[serde(rename_all = "camelCase")]
6903#[non_exhaustive]
6904pub struct PromptCapabilities {
6905    /// Agent supports `image` content blocks.
6906    ///
6907    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
6908    /// Supplying `{}` means the agent supports image content in prompts.
6909    #[serde_as(deserialize_as = "DefaultOnError")]
6910    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6911    #[serde(default)]
6912    pub image: Option<PromptImageCapabilities>,
6913    /// Agent supports `audio` content blocks.
6914    ///
6915    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
6916    /// Supplying `{}` means the agent supports audio content in prompts.
6917    #[serde_as(deserialize_as = "DefaultOnError")]
6918    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6919    #[serde(default)]
6920    pub audio: Option<PromptAudioCapabilities>,
6921    /// Agent supports embedded context in `session/prompt` requests.
6922    ///
6923    /// When enabled, the Client is allowed to include `resource` content blocks
6924    /// in prompt requests for pieces of context that are referenced in the message.
6925    ///
6926    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
6927    /// Supplying `{}` means the agent supports embedded context in prompts.
6928    #[serde_as(deserialize_as = "DefaultOnError")]
6929    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6930    #[serde(default)]
6931    pub embedded_context: Option<PromptEmbeddedContextCapabilities>,
6932    /// **UNSTABLE**
6933    ///
6934    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6935    ///
6936    /// Agent supports `skill` content blocks.
6937    ///
6938    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
6939    /// Supplying `{}` means a prompt may contain one `skill` content block, as its first block.
6940    /// An agent that sends `skill` entries in `availableCommands` MUST advertise this capability.
6941    #[cfg(feature = "unstable_agent_skills")]
6942    #[serde_as(deserialize_as = "DefaultOnError")]
6943    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6944    #[serde(default)]
6945    pub skill: Option<PromptSkillCapabilities>,
6946    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6947    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6948    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6949    ///
6950    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6951    #[serde_as(deserialize_as = "DefaultOnError")]
6952    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6953    #[serde(default)]
6954    #[serde(rename = "_meta")]
6955    pub meta: Option<Meta>,
6956}
6957
6958impl PromptCapabilities {
6959    /// Builds an empty [`PromptCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6960    #[must_use]
6961    pub fn new() -> Self {
6962        Self::default()
6963    }
6964
6965    /// Agent supports `image` content blocks.
6966    ///
6967    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
6968    /// Supplying `{}` means the agent supports image content in prompts.
6969    #[must_use]
6970    pub fn image(mut self, image: impl IntoOption<PromptImageCapabilities>) -> Self {
6971        self.image = image.into_option();
6972        self
6973    }
6974
6975    /// Agent supports `audio` content blocks.
6976    ///
6977    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
6978    /// Supplying `{}` means the agent supports audio content in prompts.
6979    #[must_use]
6980    pub fn audio(mut self, audio: impl IntoOption<PromptAudioCapabilities>) -> Self {
6981        self.audio = audio.into_option();
6982        self
6983    }
6984
6985    /// Agent supports embedded context in `session/prompt` requests.
6986    ///
6987    /// When enabled, the Client is allowed to include `resource` content blocks
6988    /// in prompt requests for pieces of context that are referenced in the message.
6989    ///
6990    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
6991    /// Supplying `{}` means the agent supports embedded context in prompts.
6992    #[must_use]
6993    pub fn embedded_context(
6994        mut self,
6995        embedded_context: impl IntoOption<PromptEmbeddedContextCapabilities>,
6996    ) -> Self {
6997        self.embedded_context = embedded_context.into_option();
6998        self
6999    }
7000
7001    /// **UNSTABLE**
7002    ///
7003    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7004    ///
7005    /// Agent supports `skill` content blocks.
7006    ///
7007    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
7008    /// Supplying `{}` means a prompt may contain one `skill` content block, as its first block.
7009    #[cfg(feature = "unstable_agent_skills")]
7010    #[must_use]
7011    pub fn skill(mut self, skill: impl IntoOption<PromptSkillCapabilities>) -> Self {
7012        self.skill = skill.into_option();
7013        self
7014    }
7015
7016    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7017    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7018    /// do not recognize.
7019    ///
7020    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7021    #[must_use]
7022    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7023        self.meta = meta.into_option();
7024        self
7025    }
7026}
7027
7028/// Capabilities for image content in prompt requests.
7029///
7030/// Supplying `{}` means the agent supports image content in prompts.
7031#[serde_as]
7032#[skip_serializing_none]
7033#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7034#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7035#[non_exhaustive]
7036pub struct PromptImageCapabilities {
7037    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7038    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7039    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7040    ///
7041    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7042    #[serde_as(deserialize_as = "DefaultOnError")]
7043    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7044    #[serde(default)]
7045    #[serde(rename = "_meta")]
7046    pub meta: Option<Meta>,
7047}
7048
7049impl PromptImageCapabilities {
7050    /// Builds an empty [`PromptImageCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7051    #[must_use]
7052    pub fn new() -> Self {
7053        Self::default()
7054    }
7055
7056    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7057    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7058    /// do not recognize.
7059    ///
7060    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7061    #[must_use]
7062    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7063        self.meta = meta.into_option();
7064        self
7065    }
7066}
7067
7068/// Capabilities for audio content in prompt requests.
7069///
7070/// Supplying `{}` means the agent supports audio content in prompts.
7071#[serde_as]
7072#[skip_serializing_none]
7073#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7074#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7075#[non_exhaustive]
7076pub struct PromptAudioCapabilities {
7077    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7078    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7079    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7080    ///
7081    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7082    #[serde_as(deserialize_as = "DefaultOnError")]
7083    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7084    #[serde(default)]
7085    #[serde(rename = "_meta")]
7086    pub meta: Option<Meta>,
7087}
7088
7089impl PromptAudioCapabilities {
7090    /// Builds an empty [`PromptAudioCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7091    #[must_use]
7092    pub fn new() -> Self {
7093        Self::default()
7094    }
7095
7096    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7097    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7098    /// do not recognize.
7099    ///
7100    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7101    #[must_use]
7102    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7103        self.meta = meta.into_option();
7104        self
7105    }
7106}
7107
7108/// Capabilities for embedded context in prompt requests.
7109///
7110/// Supplying `{}` means the agent supports embedded context in prompts.
7111#[serde_as]
7112#[skip_serializing_none]
7113#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7114#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7115#[non_exhaustive]
7116pub struct PromptEmbeddedContextCapabilities {
7117    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7118    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7119    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7120    ///
7121    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7122    #[serde_as(deserialize_as = "DefaultOnError")]
7123    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7124    #[serde(default)]
7125    #[serde(rename = "_meta")]
7126    pub meta: Option<Meta>,
7127}
7128
7129impl PromptEmbeddedContextCapabilities {
7130    /// Builds an empty [`PromptEmbeddedContextCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7131    #[must_use]
7132    pub fn new() -> Self {
7133        Self::default()
7134    }
7135
7136    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7137    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7138    /// do not recognize.
7139    ///
7140    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7141    #[must_use]
7142    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7143        self.meta = meta.into_option();
7144        self
7145    }
7146}
7147
7148/// **UNSTABLE**
7149///
7150/// This capability is not part of the spec yet, and may be removed or changed at any point.
7151///
7152/// Capabilities for `skill` content blocks in prompt requests.
7153///
7154/// Supplying `{}` means a prompt may contain one `skill` content block, as
7155/// its first block. The agent opts in to more with the `inline` field.
7156#[cfg(feature = "unstable_agent_skills")]
7157#[serde_as]
7158#[skip_serializing_none]
7159#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7160#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7161#[serde(rename_all = "camelCase")]
7162#[non_exhaustive]
7163pub struct PromptSkillCapabilities {
7164    /// Agent supports `skill` content blocks at any position in a prompt.
7165    ///
7166    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
7167    /// Supplying `{}` means a prompt may contain any number of `skill` content blocks, at any
7168    /// position.
7169    #[serde_as(deserialize_as = "DefaultOnError")]
7170    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7171    #[serde(default)]
7172    pub inline: Option<PromptSkillInlineCapabilities>,
7173    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7174    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7175    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7176    ///
7177    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7178    #[serde_as(deserialize_as = "DefaultOnError")]
7179    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7180    #[serde(default)]
7181    #[serde(rename = "_meta")]
7182    pub meta: Option<Meta>,
7183}
7184
7185#[cfg(feature = "unstable_agent_skills")]
7186impl PromptSkillCapabilities {
7187    /// Builds an empty [`PromptSkillCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7188    #[must_use]
7189    pub fn new() -> Self {
7190        Self::default()
7191    }
7192
7193    /// Agent supports `skill` content blocks at any position in a prompt.
7194    ///
7195    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
7196    /// Supplying `{}` means a prompt may contain any number of `skill` content blocks, at any
7197    /// position.
7198    #[must_use]
7199    pub fn inline(mut self, inline: impl IntoOption<PromptSkillInlineCapabilities>) -> Self {
7200        self.inline = inline.into_option();
7201        self
7202    }
7203
7204    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7205    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7206    /// do not recognize.
7207    ///
7208    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7209    #[must_use]
7210    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7211        self.meta = meta.into_option();
7212        self
7213    }
7214}
7215
7216/// **UNSTABLE**
7217///
7218/// This capability is not part of the spec yet, and may be removed or changed at any point.
7219///
7220/// Capabilities for `skill` content blocks at any position in a prompt.
7221///
7222/// Supplying `{}` means a prompt may contain any number of `skill` content
7223/// blocks, at any position.
7224#[cfg(feature = "unstable_agent_skills")]
7225#[serde_as]
7226#[skip_serializing_none]
7227#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7228#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7229#[non_exhaustive]
7230pub struct PromptSkillInlineCapabilities {
7231    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7232    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7233    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7234    ///
7235    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7236    #[serde_as(deserialize_as = "DefaultOnError")]
7237    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7238    #[serde(default)]
7239    #[serde(rename = "_meta")]
7240    pub meta: Option<Meta>,
7241}
7242
7243#[cfg(feature = "unstable_agent_skills")]
7244impl PromptSkillInlineCapabilities {
7245    /// Builds an empty [`PromptSkillInlineCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7246    #[must_use]
7247    pub fn new() -> Self {
7248        Self::default()
7249    }
7250
7251    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7252    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7253    /// do not recognize.
7254    ///
7255    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7256    #[must_use]
7257    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7258        self.meta = meta.into_option();
7259        self
7260    }
7261}
7262
7263/// MCP capabilities supported by the agent for session lifecycle requests.
7264#[serde_as]
7265#[skip_serializing_none]
7266#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7267#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7268#[serde(rename_all = "camelCase")]
7269#[non_exhaustive]
7270pub struct McpCapabilities {
7271    /// Agent supports `stdio` MCP servers.
7272    ///
7273    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
7274    /// Supplying `{}` means the agent supports stdio MCP server transports.
7275    #[serde_as(deserialize_as = "DefaultOnError")]
7276    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7277    #[serde(default)]
7278    pub stdio: Option<McpStdioCapabilities>,
7279    /// Agent supports `http` MCP servers.
7280    ///
7281    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
7282    /// Supplying `{}` means the agent supports HTTP MCP server transports.
7283    #[serde_as(deserialize_as = "DefaultOnError")]
7284    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7285    #[serde(default)]
7286    pub http: Option<McpHttpCapabilities>,
7287    /// **UNSTABLE**
7288    ///
7289    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7290    ///
7291    /// Agent supports `acp` MCP servers.
7292    ///
7293    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
7294    /// Supplying `{}` means the agent supports ACP MCP server transports.
7295    #[cfg(feature = "unstable_mcp_over_acp")]
7296    #[serde_as(deserialize_as = "DefaultOnError")]
7297    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7298    #[serde(default)]
7299    pub acp: Option<McpAcpCapabilities>,
7300    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7301    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7302    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7303    ///
7304    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7305    #[serde_as(deserialize_as = "DefaultOnError")]
7306    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7307    #[serde(default)]
7308    #[serde(rename = "_meta")]
7309    pub meta: Option<Meta>,
7310}
7311
7312impl McpCapabilities {
7313    /// Builds an empty [`McpCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7314    #[must_use]
7315    pub fn new() -> Self {
7316        Self::default()
7317    }
7318
7319    /// Agent supports `stdio` MCP servers.
7320    ///
7321    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
7322    /// Supplying `{}` means the agent supports stdio MCP server transports.
7323    #[must_use]
7324    pub fn stdio(mut self, stdio: impl IntoOption<McpStdioCapabilities>) -> Self {
7325        self.stdio = stdio.into_option();
7326        self
7327    }
7328
7329    /// Agent supports `http` MCP servers.
7330    ///
7331    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
7332    /// Supplying `{}` means the agent supports HTTP MCP server transports.
7333    #[must_use]
7334    pub fn http(mut self, http: impl IntoOption<McpHttpCapabilities>) -> Self {
7335        self.http = http.into_option();
7336        self
7337    }
7338
7339    /// **UNSTABLE**
7340    ///
7341    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7342    ///
7343    /// Agent supports `acp` MCP servers.
7344    #[cfg(feature = "unstable_mcp_over_acp")]
7345    ///
7346    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
7347    /// Supplying `{}` means the agent supports ACP MCP server transports.
7348    #[must_use]
7349    pub fn acp(mut self, acp: impl IntoOption<McpAcpCapabilities>) -> Self {
7350        self.acp = acp.into_option();
7351        self
7352    }
7353
7354    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7355    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7356    /// do not recognize.
7357    ///
7358    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7359    #[must_use]
7360    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7361        self.meta = meta.into_option();
7362        self
7363    }
7364}
7365
7366/// Capabilities for stdio MCP server transports.
7367///
7368/// Supplying `{}` means the agent supports stdio MCP server transports.
7369#[serde_as]
7370#[skip_serializing_none]
7371#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7372#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7373#[non_exhaustive]
7374pub struct McpStdioCapabilities {
7375    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7376    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7377    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7378    ///
7379    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7380    #[serde_as(deserialize_as = "DefaultOnError")]
7381    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7382    #[serde(default)]
7383    #[serde(rename = "_meta")]
7384    pub meta: Option<Meta>,
7385}
7386
7387impl McpStdioCapabilities {
7388    /// Builds an empty [`McpStdioCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7389    #[must_use]
7390    pub fn new() -> Self {
7391        Self::default()
7392    }
7393
7394    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7395    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7396    /// do not recognize.
7397    ///
7398    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7399    #[must_use]
7400    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7401        self.meta = meta.into_option();
7402        self
7403    }
7404}
7405
7406/// Capabilities for HTTP MCP server transports.
7407///
7408/// Supplying `{}` means the agent supports HTTP MCP server transports.
7409#[serde_as]
7410#[skip_serializing_none]
7411#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7412#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7413#[non_exhaustive]
7414pub struct McpHttpCapabilities {
7415    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7416    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7417    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7418    ///
7419    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7420    #[serde_as(deserialize_as = "DefaultOnError")]
7421    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7422    #[serde(default)]
7423    #[serde(rename = "_meta")]
7424    pub meta: Option<Meta>,
7425}
7426
7427impl McpHttpCapabilities {
7428    /// Builds an empty [`McpHttpCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7429    #[must_use]
7430    pub fn new() -> Self {
7431        Self::default()
7432    }
7433
7434    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7435    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7436    /// do not recognize.
7437    ///
7438    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7439    #[must_use]
7440    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7441        self.meta = meta.into_option();
7442        self
7443    }
7444}
7445
7446/// **UNSTABLE**
7447///
7448/// This capability is not part of the spec yet, and may be removed or changed at any point.
7449///
7450/// Capabilities for ACP MCP server transports.
7451///
7452/// Supplying `{}` means the agent supports ACP MCP server transports.
7453#[cfg(feature = "unstable_mcp_over_acp")]
7454#[serde_as]
7455#[skip_serializing_none]
7456#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7457#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7458#[non_exhaustive]
7459pub struct McpAcpCapabilities {
7460    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7461    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7462    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7463    ///
7464    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7465    #[serde_as(deserialize_as = "DefaultOnError")]
7466    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7467    #[serde(default)]
7468    #[serde(rename = "_meta")]
7469    pub meta: Option<Meta>,
7470}
7471
7472#[cfg(feature = "unstable_mcp_over_acp")]
7473impl McpAcpCapabilities {
7474    /// Builds an empty [`McpAcpCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7475    #[must_use]
7476    pub fn new() -> Self {
7477        Self::default()
7478    }
7479
7480    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7481    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7482    /// do not recognize.
7483    ///
7484    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7485    #[must_use]
7486    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7487        self.meta = meta.into_option();
7488        self
7489    }
7490}
7491
7492/// Notification to cancel a session's foreground work and its prompts not yet inserted.
7493///
7494/// See protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#cancellation)
7495#[serde_as]
7496#[skip_serializing_none]
7497#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7498#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7499#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CANCEL_METHOD_NAME)))]
7500#[serde(rename_all = "camelCase")]
7501#[non_exhaustive]
7502pub struct CancelSessionNotification {
7503    /// The ID of the session whose foreground work to cancel.
7504    pub session_id: SessionId,
7505    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7506    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7507    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7508    ///
7509    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7510    #[serde_as(deserialize_as = "DefaultOnError")]
7511    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7512    #[serde(default)]
7513    #[serde(rename = "_meta")]
7514    pub meta: Option<Meta>,
7515}
7516
7517impl CancelSessionNotification {
7518    /// Builds [`CancelSessionNotification`] with the required notification fields set. Optional fields start unset or empty.
7519    #[must_use]
7520    pub fn new(session_id: impl Into<SessionId>) -> Self {
7521        Self {
7522            session_id: session_id.into(),
7523            meta: None,
7524        }
7525    }
7526
7527    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7528    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7529    /// do not recognize.
7530    ///
7531    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7532    #[must_use]
7533    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7534        self.meta = meta.into_option();
7535        self
7536    }
7537}
7538
7539// Method schema
7540
7541/// Names of all methods that agents handle.
7542///
7543/// Provides a centralized definition of method names used in the protocol.
7544#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7545#[non_exhaustive]
7546pub struct AgentMethodNames {
7547    /// Method for initializing the connection.
7548    pub initialize: &'static str,
7549    /// Method for authenticating with the agent.
7550    pub auth_login: &'static str,
7551    /// Method for listing configurable providers.
7552    #[cfg(feature = "unstable_llm_providers")]
7553    pub providers_list: &'static str,
7554    /// Method for setting provider configuration.
7555    #[cfg(feature = "unstable_llm_providers")]
7556    pub providers_set: &'static str,
7557    /// Method for disabling a provider.
7558    #[cfg(feature = "unstable_llm_providers")]
7559    pub providers_disable: &'static str,
7560    /// Method for creating a new session.
7561    pub session_new: &'static str,
7562    /// Method for setting a configuration option for a session.
7563    pub session_set_config_option: &'static str,
7564    /// Method for sending a prompt to the agent.
7565    pub session_prompt: &'static str,
7566    /// Notification for cancelling operations.
7567    pub session_cancel: &'static str,
7568    /// Method for exchanging MCP-over-ACP messages.
7569    #[cfg(feature = "unstable_mcp_over_acp")]
7570    pub mcp_message: &'static str,
7571    /// Method for listing existing sessions.
7572    pub session_list: &'static str,
7573    /// Method for deleting an existing session.
7574    pub session_delete: &'static str,
7575    /// Method for forking an existing session.
7576    #[cfg(feature = "unstable_session_fork")]
7577    pub session_fork: &'static str,
7578    /// Method for archiving a session.
7579    #[cfg(feature = "unstable_session_archive")]
7580    pub session_archive: &'static str,
7581    /// Method for unarchiving a session.
7582    #[cfg(feature = "unstable_session_archive")]
7583    pub session_unarchive: &'static str,
7584    /// Method for checking the status of a session.
7585    #[cfg(feature = "unstable_session_status")]
7586    pub session_status: &'static str,
7587    /// Method for querying the config options a session would start with.
7588    #[cfg(feature = "unstable_session_options")]
7589    pub session_options: &'static str,
7590    /// Method for setting the title of a session.
7591    #[cfg(feature = "unstable_session_set_title")]
7592    pub session_set_title: &'static str,
7593    /// Method for resuming an existing session.
7594    pub session_resume: &'static str,
7595    /// Method for closing an active session.
7596    pub session_close: &'static str,
7597    /// Method for cancelling one tool call.
7598    pub tool_call_cancel: &'static str,
7599    /// Method for cancelling one terminal's process.
7600    pub terminal_cancel: &'static str,
7601    /// Method for logging out of an authenticated session.
7602    pub auth_logout: &'static str,
7603    /// Method for querying the agent's authentication state.
7604    #[cfg(feature = "unstable_auth_status")]
7605    pub auth_status: &'static str,
7606}
7607
7608/// Constant containing all agent method names.
7609pub const AGENT_METHOD_NAMES: AgentMethodNames = AgentMethodNames {
7610    initialize: INITIALIZE_METHOD_NAME,
7611    auth_login: AUTH_LOGIN_METHOD_NAME,
7612    #[cfg(feature = "unstable_llm_providers")]
7613    providers_list: PROVIDERS_LIST_METHOD_NAME,
7614    #[cfg(feature = "unstable_llm_providers")]
7615    providers_set: PROVIDERS_SET_METHOD_NAME,
7616    #[cfg(feature = "unstable_llm_providers")]
7617    providers_disable: PROVIDERS_DISABLE_METHOD_NAME,
7618    session_new: SESSION_NEW_METHOD_NAME,
7619    session_set_config_option: SESSION_SET_CONFIG_OPTION_METHOD_NAME,
7620    session_prompt: SESSION_PROMPT_METHOD_NAME,
7621    session_cancel: SESSION_CANCEL_METHOD_NAME,
7622    #[cfg(feature = "unstable_mcp_over_acp")]
7623    mcp_message: MCP_MESSAGE_METHOD_NAME,
7624    session_list: SESSION_LIST_METHOD_NAME,
7625    session_delete: SESSION_DELETE_METHOD_NAME,
7626    #[cfg(feature = "unstable_session_fork")]
7627    session_fork: SESSION_FORK_METHOD_NAME,
7628    #[cfg(feature = "unstable_session_archive")]
7629    session_archive: SESSION_ARCHIVE_METHOD_NAME,
7630    #[cfg(feature = "unstable_session_archive")]
7631    session_unarchive: SESSION_UNARCHIVE_METHOD_NAME,
7632    #[cfg(feature = "unstable_session_status")]
7633    session_status: SESSION_STATUS_METHOD_NAME,
7634    #[cfg(feature = "unstable_session_options")]
7635    session_options: SESSION_OPTIONS_METHOD_NAME,
7636    #[cfg(feature = "unstable_session_set_title")]
7637    session_set_title: SESSION_SET_TITLE_METHOD_NAME,
7638    session_resume: SESSION_RESUME_METHOD_NAME,
7639    session_close: SESSION_CLOSE_METHOD_NAME,
7640    tool_call_cancel: TOOL_CALL_CANCEL_METHOD_NAME,
7641    terminal_cancel: TERMINAL_CANCEL_METHOD_NAME,
7642    auth_logout: AUTH_LOGOUT_METHOD_NAME,
7643    #[cfg(feature = "unstable_auth_status")]
7644    auth_status: AUTH_STATUS_METHOD_NAME,
7645};
7646
7647/// Method name for the initialize request.
7648pub(crate) const INITIALIZE_METHOD_NAME: &str = "initialize";
7649/// Method name for the `auth/login` request.
7650pub(crate) const AUTH_LOGIN_METHOD_NAME: &str = "auth/login";
7651/// Method name for listing configurable providers.
7652#[cfg(feature = "unstable_llm_providers")]
7653pub(crate) const PROVIDERS_LIST_METHOD_NAME: &str = "providers/list";
7654/// Method name for setting provider configuration.
7655#[cfg(feature = "unstable_llm_providers")]
7656pub(crate) const PROVIDERS_SET_METHOD_NAME: &str = "providers/set";
7657/// Method name for disabling a provider.
7658#[cfg(feature = "unstable_llm_providers")]
7659pub(crate) const PROVIDERS_DISABLE_METHOD_NAME: &str = "providers/disable";
7660/// Method name for creating a new session.
7661pub(crate) const SESSION_NEW_METHOD_NAME: &str = "session/new";
7662/// Method name for setting a configuration option for a session.
7663pub(crate) const SESSION_SET_CONFIG_OPTION_METHOD_NAME: &str = "session/set_config_option";
7664/// Method name for sending a prompt.
7665pub(crate) const SESSION_PROMPT_METHOD_NAME: &str = "session/prompt";
7666/// Method name for the cancel notification.
7667pub(crate) const SESSION_CANCEL_METHOD_NAME: &str = "session/cancel";
7668/// Method name for listing existing sessions.
7669pub(crate) const SESSION_LIST_METHOD_NAME: &str = "session/list";
7670/// Method name for deleting an existing session.
7671pub(crate) const SESSION_DELETE_METHOD_NAME: &str = "session/delete";
7672/// Method name for forking an existing session.
7673#[cfg(feature = "unstable_session_fork")]
7674pub(crate) const SESSION_FORK_METHOD_NAME: &str = "session/fork";
7675/// Method name for archiving a session.
7676#[cfg(feature = "unstable_session_archive")]
7677pub(crate) const SESSION_ARCHIVE_METHOD_NAME: &str = "session/archive";
7678/// Method name for unarchiving a session.
7679#[cfg(feature = "unstable_session_archive")]
7680pub(crate) const SESSION_UNARCHIVE_METHOD_NAME: &str = "session/unarchive";
7681/// Method name for checking the status of a session.
7682#[cfg(feature = "unstable_session_status")]
7683pub(crate) const SESSION_STATUS_METHOD_NAME: &str = "session/status";
7684/// Method name for querying the config options a session would start with.
7685#[cfg(feature = "unstable_session_options")]
7686pub(crate) const SESSION_OPTIONS_METHOD_NAME: &str = "session/options";
7687/// Method name for setting the title of a session.
7688#[cfg(feature = "unstable_session_set_title")]
7689pub(crate) const SESSION_SET_TITLE_METHOD_NAME: &str = "session/set_title";
7690/// Method name for resuming an existing session.
7691pub(crate) const SESSION_RESUME_METHOD_NAME: &str = "session/resume";
7692/// Method name for closing an active session.
7693pub(crate) const SESSION_CLOSE_METHOD_NAME: &str = "session/close";
7694/// Method name for cancelling one tool call.
7695pub(crate) const TOOL_CALL_CANCEL_METHOD_NAME: &str = "tool_call/cancel";
7696/// Method name for cancelling one terminal's process.
7697pub(crate) const TERMINAL_CANCEL_METHOD_NAME: &str = "terminal/cancel";
7698/// Method name for the `auth/logout` request.
7699pub(crate) const AUTH_LOGOUT_METHOD_NAME: &str = "auth/logout";
7700/// Method name for the `auth/status` request.
7701#[cfg(feature = "unstable_auth_status")]
7702pub(crate) const AUTH_STATUS_METHOD_NAME: &str = "auth/status";
7703
7704/// All possible requests that a client can send to an agent.
7705///
7706/// This enum is used internally for routing RPC requests. You typically won't need
7707/// to use this directly.
7708///
7709/// This enum encompasses all method calls from client to agent.
7710#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7711#[derive(Clone, Debug, Serialize, Deserialize)]
7712#[serde(untagged)]
7713#[cfg_attr(feature = "schemars", schemars(inline))]
7714#[non_exhaustive]
7715pub enum ClientRequest {
7716    /// Establishes the connection with a client and negotiates protocol capabilities.
7717    ///
7718    /// This method is called at the beginning of the connection, before any other request, to:
7719    /// - Negotiate the protocol version to use
7720    /// - Exchange capability information between client and agent
7721    /// - Determine available authentication methods
7722    ///
7723    /// The Client may repeat it before its first other request. The latest successful
7724    /// `initialize` is authoritative.
7725    ///
7726    /// The agent should respond with its supported protocol version and capabilities.
7727    ///
7728    /// See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/v2/initialization)
7729    InitializeRequest(Box<InitializeRequest>),
7730    /// Authenticates the client using the specified authentication method.
7731    ///
7732    /// Agents MUST support this method when their `initialize` response included
7733    /// a non-empty `authMethods` list. Clients MUST call this method only
7734    /// with a method whose type defines a protocol-driven login flow, and MUST NOT
7735    /// call it when `authMethods` was omitted or empty.
7736    ///
7737    /// Called when the agent requires authentication before allowing session creation.
7738    /// The client provides the authentication method ID that was advertised during initialization.
7739    ///
7740    /// After successful authentication, the client can proceed to create sessions with
7741    /// `session/new` without receiving an `auth_required` (`-32000`) error.
7742    ///
7743    /// See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/v2/initialization)
7744    LoginAuthRequest(Box<LoginAuthRequest>),
7745    /// **UNSTABLE**
7746    ///
7747    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7748    ///
7749    /// Lists providers that can be configured by the client.
7750    #[cfg(feature = "unstable_llm_providers")]
7751    ListProvidersRequest(Box<ListProvidersRequest>),
7752    /// **UNSTABLE**
7753    ///
7754    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7755    ///
7756    /// Replaces the configuration for a provider.
7757    #[cfg(feature = "unstable_llm_providers")]
7758    SetProviderRequest(Box<SetProviderRequest>),
7759    /// **UNSTABLE**
7760    ///
7761    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7762    ///
7763    /// Disables a provider.
7764    #[cfg(feature = "unstable_llm_providers")]
7765    DisableProviderRequest(Box<DisableProviderRequest>),
7766    /// Logs out of the current authenticated state.
7767    ///
7768    /// Agents MUST support this method when their `initialize` response included
7769    /// a non-empty `authMethods` list. Clients MUST NOT call this method
7770    /// when `authMethods` was omitted or empty.
7771    ///
7772    /// After a successful logout, authentication-gated requests require the
7773    /// client to complete an advertised authentication flow again. There is no
7774    /// guarantee about the behavior of already running sessions.
7775    LogoutAuthRequest(Box<LogoutAuthRequest>),
7776    /// **UNSTABLE**
7777    ///
7778    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7779    ///
7780    /// Queries the agent's current authentication state.
7781    ///
7782    /// This method is only available if the agent advertises the `auth.status` capability.
7783    /// It MUST NOT change any agent state, and agents MUST NOT reject it with `auth_required`.
7784    #[cfg(feature = "unstable_auth_status")]
7785    AuthStatusRequest(Box<AuthStatusRequest>),
7786    /// Creates a new conversation session with the agent.
7787    ///
7788    /// Sessions represent independent conversation contexts with their own history and state.
7789    ///
7790    /// The agent should:
7791    /// - Create a new session context
7792    /// - Connect to any specified MCP servers
7793    /// - Return a unique session ID for future requests
7794    ///
7795    /// May return an `auth_required` (`-32000`) error if the agent requires authentication.
7796    ///
7797    /// See protocol docs: [Session Setup](https://agentclientprotocol.com/protocol/v2/session-setup)
7798    NewSessionRequest(Box<NewSessionRequest>),
7799    /// Lists existing sessions known to the agent.
7800    ///
7801    /// The agent should return metadata about sessions with optional filtering and pagination support.
7802    ListSessionsRequest(Box<ListSessionsRequest>),
7803    /// Deletes an existing session from `session/list`.
7804    ///
7805    /// This method is only available if the agent advertises the `session.delete` capability.
7806    DeleteSessionRequest(Box<DeleteSessionRequest>),
7807    #[cfg(feature = "unstable_session_fork")]
7808    /// **UNSTABLE**
7809    ///
7810    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7811    ///
7812    /// Forks an existing session to create a new independent session.
7813    ///
7814    /// This method is only available if the agent advertises the `session.fork` capability.
7815    ///
7816    /// The agent should create a new session with the same conversation context as the
7817    /// original, allowing operations like generating summaries without affecting the
7818    /// original session's history.
7819    ///
7820    /// As with `session/new`, the forked session is active once the agent responds,
7821    /// set up with the request's `cwd`, `additionalDirectories`, and `mcpServers`.
7822    /// The client can prompt it without calling `session/resume` first.
7823    ForkSessionRequest(Box<ForkSessionRequest>),
7824    #[cfg(feature = "unstable_session_archive")]
7825    /// **UNSTABLE**
7826    ///
7827    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7828    ///
7829    /// Archives a session, hiding it from default `session/list` results.
7830    ///
7831    /// This method is only available if the agent advertises the `session.archive` capability.
7832    ArchiveSessionRequest(Box<ArchiveSessionRequest>),
7833    #[cfg(feature = "unstable_session_archive")]
7834    /// **UNSTABLE**
7835    ///
7836    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7837    ///
7838    /// Unarchives a session, returning it to default `session/list` results.
7839    ///
7840    /// This method is only available if the agent advertises the `session.archive` capability.
7841    UnarchiveSessionRequest(Box<UnarchiveSessionRequest>),
7842    #[cfg(feature = "unstable_session_status")]
7843    /// **UNSTABLE**
7844    ///
7845    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7846    ///
7847    /// Checks whether the Agent has a session in memory, without changing it.
7848    ///
7849    /// This method is only available if the agent advertises the `session.status` capability.
7850    SessionStatusRequest(Box<SessionStatusRequest>),
7851    #[cfg(feature = "unstable_session_options")]
7852    /// **UNSTABLE**
7853    ///
7854    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7855    ///
7856    /// Returns the config options a session would start with, without creating or resuming a session.
7857    ///
7858    /// This method is only available if the agent advertises the `session.options` capability.
7859    SessionOptionsRequest(Box<SessionOptionsRequest>),
7860    #[cfg(feature = "unstable_session_set_title")]
7861    /// **UNSTABLE**
7862    ///
7863    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7864    ///
7865    /// Sets the title of a session.
7866    ///
7867    /// This method is only available if the agent advertises the `session.title` capability.
7868    ///
7869    /// The session does not need to be active on the connection. The agent stores the
7870    /// title and returns the stored title, which may be normalized.
7871    SetSessionTitleRequest(Box<SetSessionTitleRequest>),
7872    /// Resumes an existing session.
7873    ///
7874    /// The agent should resume the session context, allowing the conversation
7875    /// to continue. If `replayFrom` is set, the agent should replay
7876    /// retained conversation history before responding.
7877    ResumeSessionRequest(Box<ResumeSessionRequest>),
7878    /// Closes an active session and frees up any resources associated with it.
7879    ///
7880    /// The Agent MUST cancel any ongoing work as if `session/cancel` was called, stop the
7881    /// session's background work, and then free the resources associated with the session.
7882    CloseSessionRequest(Box<CloseSessionRequest>),
7883    /// Cancels one tool call without cancelling the rest of the session's work.
7884    ///
7885    /// This method is only available while the tool call advertises `capabilities.cancel`.
7886    /// The response means the Agent accepted the cancellation. A final `tool_call_update`
7887    /// confirms it.
7888    CancelToolCallRequest(Box<CancelToolCallRequest>),
7889    /// Stops one terminal's process without cancelling the rest of the session's work.
7890    ///
7891    /// This method is only available while the terminal advertises `capabilities.cancel`.
7892    /// The response means the Agent accepted the cancellation. A `terminal_update` with
7893    /// `exitStatus` confirms it.
7894    CancelTerminalRequest(Box<CancelTerminalRequest>),
7895    /// Sets the current value for a session configuration option.
7896    SetSessionConfigOptionRequest(Box<SetSessionConfigOptionRequest>),
7897    /// Processes a user prompt within a session.
7898    ///
7899    /// Acceptance means adding a logical user message with an ID and a position
7900    /// relative to other messages in the ACP conversation, not receipt or queueing.
7901    /// The Agent MUST return the inserted message's ID without waiting for
7902    /// processing to finish.
7903    ///
7904    /// The Agent reports the user message with the same ID through `session/update`.
7905    /// This notification may arrive before or after the response, but neither may
7906    /// precede insertion. Processing state, output, tool calls, and completion are
7907    /// also reported through session updates.
7908    ///
7909    /// An error response means the user message was not inserted. Once it is
7910    /// inserted, the Agent MUST NOT answer with an error, even if the work fails
7911    /// before the response is sent. It ends that work with the `error` stop reason.
7912    ///
7913    /// A rejected submission produces no user-message updates. Foreground state
7914    /// follows its normal lifecycle independently of the request outcome:
7915    /// `running` may precede insertion, and rejection alone does not imply `idle`.
7916    ///
7917    /// See protocol docs: [Prompt Lifecycle](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle)
7918    PromptRequest(Box<PromptRequest>),
7919    /// Handles extension method requests from the client.
7920    ///
7921    /// Extension methods provide a way to add custom functionality while maintaining
7922    /// protocol compatibility.
7923    ///
7924    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7925    ExtMethodRequest(Box<ExtRequest>),
7926}
7927
7928impl ClientRequest {
7929    /// Returns the corresponding method name of the request.
7930    #[must_use]
7931    pub fn method(&self) -> &str {
7932        match self {
7933            Self::InitializeRequest(_) => AGENT_METHOD_NAMES.initialize,
7934            Self::LoginAuthRequest(_) => AGENT_METHOD_NAMES.auth_login,
7935            #[cfg(feature = "unstable_llm_providers")]
7936            Self::ListProvidersRequest(_) => AGENT_METHOD_NAMES.providers_list,
7937            #[cfg(feature = "unstable_llm_providers")]
7938            Self::SetProviderRequest(_) => AGENT_METHOD_NAMES.providers_set,
7939            #[cfg(feature = "unstable_llm_providers")]
7940            Self::DisableProviderRequest(_) => AGENT_METHOD_NAMES.providers_disable,
7941            Self::LogoutAuthRequest(_) => AGENT_METHOD_NAMES.auth_logout,
7942            #[cfg(feature = "unstable_auth_status")]
7943            Self::AuthStatusRequest(_) => AGENT_METHOD_NAMES.auth_status,
7944            Self::NewSessionRequest(_) => AGENT_METHOD_NAMES.session_new,
7945            Self::ListSessionsRequest(_) => AGENT_METHOD_NAMES.session_list,
7946            Self::DeleteSessionRequest(_) => AGENT_METHOD_NAMES.session_delete,
7947            #[cfg(feature = "unstable_session_fork")]
7948            Self::ForkSessionRequest(_) => AGENT_METHOD_NAMES.session_fork,
7949            #[cfg(feature = "unstable_session_archive")]
7950            Self::ArchiveSessionRequest(_) => AGENT_METHOD_NAMES.session_archive,
7951            #[cfg(feature = "unstable_session_archive")]
7952            Self::UnarchiveSessionRequest(_) => AGENT_METHOD_NAMES.session_unarchive,
7953            #[cfg(feature = "unstable_session_status")]
7954            Self::SessionStatusRequest(_) => AGENT_METHOD_NAMES.session_status,
7955            #[cfg(feature = "unstable_session_options")]
7956            Self::SessionOptionsRequest(_) => AGENT_METHOD_NAMES.session_options,
7957            #[cfg(feature = "unstable_session_set_title")]
7958            Self::SetSessionTitleRequest(_) => AGENT_METHOD_NAMES.session_set_title,
7959            Self::ResumeSessionRequest(_) => AGENT_METHOD_NAMES.session_resume,
7960            Self::CloseSessionRequest(_) => AGENT_METHOD_NAMES.session_close,
7961            Self::CancelToolCallRequest(_) => AGENT_METHOD_NAMES.tool_call_cancel,
7962            Self::CancelTerminalRequest(_) => AGENT_METHOD_NAMES.terminal_cancel,
7963            Self::SetSessionConfigOptionRequest(_) => AGENT_METHOD_NAMES.session_set_config_option,
7964            Self::PromptRequest(_) => AGENT_METHOD_NAMES.session_prompt,
7965            Self::ExtMethodRequest(ext_request) => &ext_request.method,
7966        }
7967    }
7968}
7969
7970/// All possible responses that an agent can send to a client.
7971///
7972/// This enum is used internally for routing RPC responses. You typically won't need
7973/// to use this directly - the responses are handled automatically by the connection.
7974///
7975/// These are responses to the corresponding `ClientRequest` variants.
7976#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7977#[derive(Clone, Debug, Serialize, Deserialize)]
7978#[serde(untagged)]
7979#[cfg_attr(feature = "schemars", schemars(inline))]
7980#[non_exhaustive]
7981pub enum AgentResponse {
7982    /// Successful result returned for a `initialize` request.
7983    InitializeResponse(Box<InitializeResponse>),
7984    /// Successful result returned for an `auth/login` request.
7985    LoginAuthResponse(#[serde(default)] Box<LoginAuthResponse>),
7986    /// Successful result returned for a `providers/list` request.
7987    #[cfg(feature = "unstable_llm_providers")]
7988    ListProvidersResponse(Box<ListProvidersResponse>),
7989    /// Successful result returned for a `providers/set` request.
7990    #[cfg(feature = "unstable_llm_providers")]
7991    SetProviderResponse(#[serde(default)] Box<SetProviderResponse>),
7992    /// Successful result returned for a `providers/disable` request.
7993    #[cfg(feature = "unstable_llm_providers")]
7994    DisableProviderResponse(#[serde(default)] Box<DisableProviderResponse>),
7995    /// Successful result returned for an `auth/logout` request.
7996    LogoutAuthResponse(#[serde(default)] Box<LogoutAuthResponse>),
7997    /// Successful result returned for an `auth/status` request.
7998    #[cfg(feature = "unstable_auth_status")]
7999    AuthStatusResponse(Box<AuthStatusResponse>),
8000    /// Successful result returned for a `session/new` request.
8001    NewSessionResponse(Box<NewSessionResponse>),
8002    /// Successful result returned for a `session/list` request.
8003    ListSessionsResponse(Box<ListSessionsResponse>),
8004    /// Successful result returned for a `session/delete` request.
8005    DeleteSessionResponse(#[serde(default)] Box<DeleteSessionResponse>),
8006    /// Successful result returned for a `session/fork` request.
8007    #[cfg(feature = "unstable_session_fork")]
8008    ForkSessionResponse(Box<ForkSessionResponse>),
8009    /// Successful result returned for a `session/archive` request.
8010    #[cfg(feature = "unstable_session_archive")]
8011    ArchiveSessionResponse(#[serde(default)] Box<ArchiveSessionResponse>),
8012    /// Successful result returned for a `session/unarchive` request.
8013    #[cfg(feature = "unstable_session_archive")]
8014    UnarchiveSessionResponse(#[serde(default)] Box<UnarchiveSessionResponse>),
8015    /// Successful result returned for a `session/status` request.
8016    #[cfg(feature = "unstable_session_status")]
8017    SessionStatusResponse(Box<SessionStatusResponse>),
8018    /// Successful result returned for a `session/options` request.
8019    #[cfg(feature = "unstable_session_options")]
8020    SessionOptionsResponse(#[serde(default)] Box<SessionOptionsResponse>),
8021    /// Successful result returned for a `session/set_title` request.
8022    #[cfg(feature = "unstable_session_set_title")]
8023    SetSessionTitleResponse(Box<SetSessionTitleResponse>),
8024    /// Successful result returned for a `session/resume` request.
8025    ResumeSessionResponse(#[serde(default)] Box<ResumeSessionResponse>),
8026    /// Successful result returned for a `session/close` request.
8027    CloseSessionResponse(#[serde(default)] Box<CloseSessionResponse>),
8028    /// Successful result returned for a `tool_call/cancel` request.
8029    CancelToolCallResponse(#[serde(default)] Box<CancelToolCallResponse>),
8030    /// Successful result returned for a `terminal/cancel` request.
8031    CancelTerminalResponse(#[serde(default)] Box<CancelTerminalResponse>),
8032    /// Successful result returned for a `session/set_config_option` request.
8033    SetSessionConfigOptionResponse(Box<SetSessionConfigOptionResponse>),
8034    /// Successful result returned for a `session/prompt` request.
8035    PromptResponse(Box<PromptResponse>),
8036    /// Successful result returned by an extension method outside the core ACP method set.
8037    ExtMethodResponse(Box<ExtResponse>),
8038}
8039
8040/// All possible notifications that a client can send to an agent.
8041///
8042/// This enum is used internally for routing RPC notifications. You typically won't need
8043/// to use this directly.
8044///
8045/// Notifications do not expect a response.
8046#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
8047#[derive(Clone, Debug, Serialize, Deserialize)]
8048#[serde(untagged)]
8049#[cfg_attr(feature = "schemars", schemars(inline))]
8050#[non_exhaustive]
8051pub enum ClientNotification {
8052    /// Cancels a session's foreground work and its prompts not yet inserted.
8053    ///
8054    /// Work in the latest `background` list is not covered and keeps running. The
8055    /// Agent MAY stop background activity it does not list.
8056    ///
8057    /// Upon receiving this notification, the Agent SHOULD stop all language model
8058    /// requests and all tool call invocations of the cancelled foreground work as soon
8059    /// as possible.
8060    ///
8061    /// The Agent MUST stop waiting for pending `session/request_permission` requests of
8062    /// the cancelled work and treat them as not approved. It SHOULD cancel each of them
8063    /// with `$/cancel_request`.
8064    ///
8065    /// After all ongoing operations have been successfully aborted and pending
8066    /// updates have been sent, the Agent MUST send an idle `state_update` session
8067    /// update with the `cancelled` stop reason if cancellation ended active
8068    /// foreground work. No additional completion update is required if no
8069    /// foreground work was active.
8070    ///
8071    /// After cancellation completes, the Agent SHOULD ignore late answers rather
8072    /// than use them to resume the cancelled work.
8073    ///
8074    /// Agents MUST catch errors caused by aborting cancelled work and report the
8075    /// `cancelled` stop reason, not `error`.
8076    ///
8077    /// The Agent MAY send content or tool call updates after receiving
8078    /// `session/cancel`, but MUST send them before the idle `state_update` that
8079    /// reports cancellation.
8080    ///
8081    /// See protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#cancellation)
8082    CancelSessionNotification(Box<CancelSessionNotification>),
8083    /// **UNSTABLE**
8084    ///
8085    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8086    ///
8087    /// Sends an MCP-over-ACP notification.
8088    #[cfg(feature = "unstable_mcp_over_acp")]
8089    MessageMcpNotification(Box<MessageMcpNotification>),
8090    /// Handles extension notifications from the client.
8091    ///
8092    /// Extension notifications provide a way to send one-way messages for custom functionality
8093    /// while maintaining protocol compatibility.
8094    ///
8095    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
8096    ExtNotification(Box<ExtNotification>),
8097}
8098
8099impl ClientNotification {
8100    /// Returns the corresponding method name of the notification.
8101    #[must_use]
8102    pub fn method(&self) -> &str {
8103        match self {
8104            Self::CancelSessionNotification(_) => AGENT_METHOD_NAMES.session_cancel,
8105            #[cfg(feature = "unstable_mcp_over_acp")]
8106            Self::MessageMcpNotification(_) => AGENT_METHOD_NAMES.mcp_message,
8107            Self::ExtNotification(ext_notification) => &ext_notification.method,
8108        }
8109    }
8110}
8111
8112#[cfg(test)]
8113mod test_serialization {
8114    use std::path::PathBuf;
8115
8116    use super::*;
8117    use serde_json::json;
8118
8119    fn test_meta() -> Meta {
8120        json!({ "source": "test" }).as_object().unwrap().clone()
8121    }
8122
8123    #[test]
8124    fn list_sessions_cursor_and_session_directories_are_strict() {
8125        for cursor in [json!(null), json!("next")] {
8126            let response = json!({ "sessions": [], "nextCursor": cursor });
8127            serde_json::from_value::<ListSessionsResponse>(response).unwrap();
8128        }
8129        let malformed = json!({ "sessions": [], "nextCursor": 42 });
8130        assert!(serde_json::from_value::<ListSessionsResponse>(malformed).is_err());
8131
8132        let session = |dirs: serde_json::Value| json!({ "sessionId": "s", "cwd": "/w", "additionalDirectories": dirs });
8133        let info: SessionInfo = serde_json::from_value(session(json!(null))).unwrap();
8134        assert_eq!(info.additional_directories, Vec::<AbsolutePath>::new());
8135        for bad in [json!(["/a", 42]), json!("/a")] {
8136            assert!(serde_json::from_value::<SessionInfo>(session(bad)).is_err());
8137        }
8138        // A session with malformed directories is skipped, not truncated.
8139        let response = json!({ "sessions": [session(json!(["/a", 42]))] });
8140        let response: ListSessionsResponse = serde_json::from_value(response).unwrap();
8141        assert_eq!(response.sessions, Vec::<SessionInfo>::new());
8142    }
8143
8144    #[test]
8145    fn other_fallbacks_preserve_optional_fields_verbatim() {
8146        let valid = json!({ "type": "_custom", "methodId": "m", "name": "M",
8147            "description": "d", "_meta": { "k": 1 } });
8148        let method: AuthMethod = serde_json::from_value(valid.clone()).unwrap();
8149        assert_eq!(method.description(), Some("d"));
8150        assert_eq!(
8151            method.meta(),
8152            Some(&json!({ "k": 1 }).as_object().unwrap().clone())
8153        );
8154        assert_eq!(serde_json::to_value(&method).unwrap(), valid);
8155
8156        // Malformed optional fields are kept as sent and read as absent.
8157        let malformed = json!({ "type": "_custom", "methodId": "m", "name": "M",
8158            "description": 42, "_meta": "bad", "extra": true });
8159        let method: AuthMethod = serde_json::from_value(malformed.clone()).unwrap();
8160        assert_eq!(method.description(), None);
8161        assert_eq!(method.meta(), None);
8162        assert_eq!(serde_json::to_value(&method).unwrap(), malformed);
8163
8164        let replay = json!({ "type": "_custom", "_meta": "bad", "cursor": 3 });
8165        let decoded: ReplayFrom = serde_json::from_value(replay.clone()).unwrap();
8166        assert_eq!(serde_json::to_value(&decoded).unwrap(), replay);
8167    }
8168
8169    fn serialized_meta_key_count(value: &impl serde::Serialize) -> usize {
8170        serde_json::to_string(value)
8171            .unwrap()
8172            .matches("\"_meta\"")
8173            .count()
8174    }
8175
8176    #[test]
8177    fn prompt_response_without_metadata_round_trips() {
8178        let response = PromptResponse::new(MessageId::new("message-1"));
8179        let serialized = serde_json::to_value(&response).unwrap();
8180        assert_eq!(serialized, json!({ "messageId": "message-1" }));
8181        assert_eq!(
8182            serde_json::from_value::<PromptResponse>(serialized).unwrap(),
8183            response
8184        );
8185        assert_eq!(
8186            serde_json::from_value::<PromptResponse>(json!({
8187                "messageId": "message-1",
8188                "_meta": null
8189            }))
8190            .unwrap(),
8191            response
8192        );
8193    }
8194
8195    #[test]
8196    fn prompt_response_requires_message_id_and_preserves_metadata_tolerance() {
8197        let response = PromptResponse::new("message-1").meta(test_meta());
8198        let serialized = serde_json::to_value(&response).unwrap();
8199        assert_eq!(
8200            serialized,
8201            json!({
8202                "messageId": "message-1",
8203                "_meta": { "source": "test" }
8204            })
8205        );
8206
8207        let deserialized: PromptResponse = serde_json::from_value(serialized).unwrap();
8208        assert_eq!(deserialized.message_id, MessageId::new("message-1"));
8209        assert_eq!(deserialized.meta, Some(test_meta()));
8210
8211        let malformed_meta: PromptResponse = serde_json::from_value(json!({
8212            "messageId": "message-2",
8213            "_meta": false
8214        }))
8215        .unwrap();
8216        assert_eq!(malformed_meta.message_id, MessageId::new("message-2"));
8217        assert_eq!(malformed_meta.meta, None);
8218
8219        for invalid in [
8220            json!({}),
8221            json!({ "messageId": null }),
8222            json!({ "messageId": 1 }),
8223            json!({ "messageId": false }),
8224            json!({ "messageId": {} }),
8225            json!({ "messageId": [] }),
8226        ] {
8227            assert!(
8228                serde_json::from_value::<PromptResponse>(invalid).is_err(),
8229                "missing, null, and non-string message IDs must be rejected"
8230            );
8231        }
8232    }
8233
8234    #[cfg(feature = "schemars")]
8235    #[test]
8236    fn prompt_response_schema_requires_non_null_string_message_id_reference() {
8237        let schema = serde_json::to_value(schemars::schema_for!(PromptResponse)).unwrap();
8238
8239        assert_eq!(schema["required"], json!(["messageId"]));
8240        assert_eq!(
8241            schema["properties"]["messageId"]["$ref"],
8242            "#/$defs/MessageId"
8243        );
8244        assert_eq!(schema["$defs"]["MessageId"]["type"], "string");
8245    }
8246
8247    #[test]
8248    fn test_initialize_capabilities_default_on_malformed_values() {
8249        let request: InitializeRequest = serde_json::from_value(json!({
8250            "protocolVersion": 2,
8251            "capabilities": false,
8252            "info": {
8253                "name": "client",
8254                "version": "1.0.0"
8255            }
8256        }))
8257        .unwrap();
8258        assert_eq!(request.capabilities, ClientCapabilities::default());
8259
8260        let response: InitializeResponse = serde_json::from_value(json!({
8261            "protocolVersion": 2,
8262            "capabilities": false,
8263            "info": {
8264                "name": "agent",
8265                "version": "1.0.0"
8266            }
8267        }))
8268        .unwrap();
8269        assert_eq!(response.capabilities, AgentCapabilities::default());
8270    }
8271
8272    #[test]
8273    fn test_agent_capabilities_default_on_malformed_values() {
8274        let capabilities: AgentCapabilities = serde_json::from_value(json!({
8275            "session": false,
8276            "auth": false
8277        }))
8278        .unwrap();
8279
8280        assert!(capabilities.session.is_none());
8281        assert_eq!(capabilities.auth, None);
8282    }
8283
8284    #[test]
8285    fn test_mcp_server_stdio_serialization() {
8286        let server = McpServer::Stdio(
8287            McpServerStdio::new("test-server", "/usr/bin/server")
8288                .args(vec!["--port".to_string(), "3000".to_string()])
8289                .env(vec![EnvVariable::new("API_KEY", "secret123")]),
8290        );
8291
8292        let json = serde_json::to_value(&server).unwrap();
8293        assert_eq!(
8294            json,
8295            json!({
8296                "type": "stdio",
8297                "name": "test-server",
8298                "command": "/usr/bin/server",
8299                "args": ["--port", "3000"],
8300                "env": [
8301                    {
8302                        "name": "API_KEY",
8303                        "value": "secret123"
8304                    }
8305                ]
8306            })
8307        );
8308
8309        let deserialized: McpServer = serde_json::from_value(json).unwrap();
8310        match deserialized {
8311            McpServer::Stdio(McpServerStdio {
8312                name,
8313                command,
8314                args,
8315                env,
8316                meta: _,
8317            }) => {
8318                assert_eq!(name, "test-server");
8319                assert_eq!(command, AbsolutePath::new("/usr/bin/server"));
8320                assert_eq!(args, vec!["--port", "3000"]);
8321                assert_eq!(env.len(), 1);
8322                assert_eq!(env[0].name, "API_KEY");
8323                assert_eq!(env[0].value, "secret123");
8324            }
8325            _ => panic!("Expected Stdio variant"),
8326        }
8327    }
8328
8329    #[test]
8330    fn test_mcp_server_empty_arrays_are_optional() {
8331        let stdio = McpServer::Stdio(McpServerStdio::new("test-server", "/usr/bin/server"));
8332        assert_eq!(
8333            serde_json::to_value(&stdio).unwrap(),
8334            json!({
8335                "type": "stdio",
8336                "name": "test-server",
8337                "command": "/usr/bin/server"
8338            })
8339        );
8340
8341        let McpServer::Stdio(McpServerStdio { args, env, .. }) =
8342            serde_json::from_value::<McpServer>(json!({
8343                "type": "stdio",
8344                "name": "test-server",
8345                "command": "/usr/bin/server"
8346            }))
8347            .unwrap()
8348        else {
8349            panic!("Expected Stdio variant");
8350        };
8351        assert_eq!(args, Vec::<String>::new());
8352        assert_eq!(env, []);
8353
8354        let http = McpServer::Http(McpServerHttp::new("http-server", "https://api.example.com"));
8355        assert_eq!(
8356            serde_json::to_value(&http).unwrap(),
8357            json!({
8358                "type": "http",
8359                "name": "http-server",
8360                "url": "https://api.example.com"
8361            })
8362        );
8363
8364        let McpServer::Http(McpServerHttp { headers, .. }) =
8365            serde_json::from_value::<McpServer>(json!({
8366                "type": "http",
8367                "name": "http-server",
8368                "url": "https://api.example.com"
8369            }))
8370            .unwrap()
8371        else {
8372            panic!("Expected Http variant");
8373        };
8374        assert_eq!(headers, []);
8375    }
8376
8377    #[test]
8378    fn test_mcp_server_unknown_transport_serialization() {
8379        let json = json!({
8380            "type": "websocket",
8381            "name": "future-server",
8382            "url": "wss://example.com/mcp",
8383            "protocolVersion": "2026-01-01"
8384        });
8385
8386        let deserialized: McpServer = serde_json::from_value(json.clone()).unwrap();
8387        let McpServer::Other(OtherMcpServer { type_, fields }) = &deserialized else {
8388            panic!("Expected Other variant");
8389        };
8390
8391        assert_eq!(type_, "websocket");
8392        assert_eq!(fields["name"], "future-server");
8393        assert_eq!(fields["url"], "wss://example.com/mcp");
8394        assert_eq!(fields["protocolVersion"], "2026-01-01");
8395        assert_eq!(serde_json::to_value(&deserialized).unwrap(), json);
8396    }
8397
8398    #[test]
8399    fn test_mcp_server_stdio_requires_type() {
8400        let result = serde_json::from_value::<McpServer>(json!({
8401            "name": "test-server",
8402            "command": "/usr/bin/server",
8403            "args": [],
8404            "env": []
8405        }));
8406
8407        assert!(result.is_err());
8408    }
8409
8410    #[test]
8411    fn test_mcp_server_unknown_does_not_hide_malformed_known_transport() {
8412        let result = serde_json::from_value::<McpServer>(json!({
8413            "type": "stdio",
8414            "name": "test-server",
8415            "args": [],
8416            "env": []
8417        }));
8418
8419        assert!(result.is_err());
8420    }
8421
8422    #[test]
8423    fn test_mcp_server_http_serialization() {
8424        let server = McpServer::Http(
8425            McpServerHttp::new("http-server", "https://api.example.com").headers(vec![
8426                HttpHeader::new("Authorization", "Bearer token123"),
8427                HttpHeader::new("Content-Type", "application/json"),
8428            ]),
8429        );
8430
8431        let json = serde_json::to_value(&server).unwrap();
8432        assert_eq!(
8433            json,
8434            json!({
8435                "type": "http",
8436                "name": "http-server",
8437                "url": "https://api.example.com",
8438                "headers": [
8439                    {
8440                        "name": "Authorization",
8441                        "value": "Bearer token123"
8442                    },
8443                    {
8444                        "name": "Content-Type",
8445                        "value": "application/json"
8446                    }
8447                ]
8448            })
8449        );
8450
8451        let deserialized: McpServer = serde_json::from_value(json).unwrap();
8452        match deserialized {
8453            McpServer::Http(McpServerHttp {
8454                name,
8455                url,
8456                headers,
8457                meta: _,
8458            }) => {
8459                assert_eq!(name, "http-server");
8460                assert_eq!(url, "https://api.example.com");
8461                assert_eq!(headers.len(), 2);
8462                assert_eq!(headers[0].name, "Authorization");
8463                assert_eq!(headers[0].value, "Bearer token123");
8464                assert_eq!(headers[1].name, "Content-Type");
8465                assert_eq!(headers[1].value, "application/json");
8466            }
8467            _ => panic!("Expected Http variant"),
8468        }
8469    }
8470
8471    #[cfg(feature = "schemars")]
8472    #[test]
8473    fn mcp_server_http_schema_marks_url_as_uri() {
8474        let schema = serde_json::to_value(schemars::schema_for!(McpServerHttp)).unwrap();
8475
8476        assert_eq!(schema["properties"]["url"]["format"], "uri");
8477    }
8478
8479    #[cfg(feature = "unstable_mcp_over_acp")]
8480    #[test]
8481    fn test_client_mcp_message_method_names() {
8482        use serde_json::json;
8483
8484        assert_eq!(AGENT_METHOD_NAMES.mcp_message, "mcp/message");
8485
8486        let notification =
8487            MessageMcpNotification::new("server-1", "req-1", "notifications/progress");
8488        assert_eq!(
8489            ClientNotification::MessageMcpNotification(Box::new(notification.clone())).method(),
8490            "mcp/message"
8491        );
8492        assert_eq!(
8493            serde_json::to_value(notification).unwrap(),
8494            json!({
8495                "serverId": "server-1",
8496                "requestId": "req-1",
8497                "method": "notifications/progress"
8498            })
8499        );
8500        let notification: MessageMcpNotification = serde_json::from_value(json!({
8501            "serverId": "server-1", "requestId": "req-1", "method": "notifications/progress",
8502            "params": null, "_meta": null
8503        }))
8504        .unwrap();
8505        assert_eq!(notification.params, None);
8506        assert_eq!(notification.meta, None);
8507        for key in ["serverId", "requestId", "method"] {
8508            let mut value = json!({"serverId":"server-1", "requestId":"req-1", "method":"notifications/progress"});
8509            value.as_object_mut().unwrap().remove(key);
8510            assert!(serde_json::from_value::<MessageMcpNotification>(value).is_err());
8511        }
8512    }
8513
8514    #[test]
8515    fn test_auth_method_names() {
8516        assert_eq!(AGENT_METHOD_NAMES.auth_login, "auth/login");
8517        assert_eq!(AGENT_METHOD_NAMES.auth_logout, "auth/logout");
8518
8519        assert_eq!(
8520            ClientRequest::LoginAuthRequest(Box::new(LoginAuthRequest::new("agent-login")))
8521                .method(),
8522            "auth/login"
8523        );
8524        assert_eq!(
8525            ClientRequest::LogoutAuthRequest(Box::new(LogoutAuthRequest::new())).method(),
8526            "auth/logout"
8527        );
8528    }
8529
8530    #[test]
8531    fn test_session_config_option_category_known_variants() {
8532        // Test serialization of known variants
8533        assert_eq!(
8534            serde_json::to_value(&SessionConfigOptionCategory::Mode).unwrap(),
8535            json!("mode")
8536        );
8537        assert_eq!(
8538            serde_json::to_value(&SessionConfigOptionCategory::Model).unwrap(),
8539            json!("model")
8540        );
8541        assert_eq!(
8542            serde_json::to_value(&SessionConfigOptionCategory::ModelConfig).unwrap(),
8543            json!("model_config")
8544        );
8545        #[cfg(feature = "unstable_speed_config_category")]
8546        assert_eq!(
8547            serde_json::to_value(&SessionConfigOptionCategory::Speed).unwrap(),
8548            json!("speed")
8549        );
8550        assert_eq!(
8551            serde_json::to_value(&SessionConfigOptionCategory::ThoughtLevel).unwrap(),
8552            json!("thought_level")
8553        );
8554
8555        // Test deserialization of known variants
8556        assert_eq!(
8557            serde_json::from_str::<SessionConfigOptionCategory>("\"mode\"").unwrap(),
8558            SessionConfigOptionCategory::Mode
8559        );
8560        assert_eq!(
8561            serde_json::from_str::<SessionConfigOptionCategory>("\"model\"").unwrap(),
8562            SessionConfigOptionCategory::Model
8563        );
8564        assert_eq!(
8565            serde_json::from_str::<SessionConfigOptionCategory>("\"model_config\"").unwrap(),
8566            SessionConfigOptionCategory::ModelConfig
8567        );
8568        #[cfg(feature = "unstable_speed_config_category")]
8569        assert_eq!(
8570            serde_json::from_str::<SessionConfigOptionCategory>("\"speed\"").unwrap(),
8571            SessionConfigOptionCategory::Speed
8572        );
8573        assert_eq!(
8574            serde_json::from_str::<SessionConfigOptionCategory>("\"thought_level\"").unwrap(),
8575            SessionConfigOptionCategory::ThoughtLevel
8576        );
8577    }
8578
8579    #[test]
8580    fn test_session_config_option_category_unknown_variants() {
8581        // Test that unknown strings are captured in Other variant
8582        let unknown: SessionConfigOptionCategory =
8583            serde_json::from_str("\"some_future_category\"").unwrap();
8584        assert_eq!(
8585            unknown,
8586            SessionConfigOptionCategory::Other("some_future_category".to_string())
8587        );
8588
8589        // Test round-trip of unknown category
8590        let json = serde_json::to_value(&unknown).unwrap();
8591        assert_eq!(json, json!("some_future_category"));
8592    }
8593
8594    #[cfg(not(feature = "unstable_speed_config_category"))]
8595    #[test]
8596    fn test_session_config_option_speed_is_unknown_without_feature() {
8597        let unknown: SessionConfigOptionCategory = serde_json::from_str("\"speed\"").unwrap();
8598        assert_eq!(
8599            unknown,
8600            SessionConfigOptionCategory::Other("speed".to_string())
8601        );
8602    }
8603
8604    #[test]
8605    fn test_session_config_option_category_custom_categories() {
8606        // Category names beginning with `_` are free for custom use
8607        let custom: SessionConfigOptionCategory =
8608            serde_json::from_str("\"_my_custom_category\"").unwrap();
8609        assert_eq!(
8610            custom,
8611            SessionConfigOptionCategory::Other("_my_custom_category".to_string())
8612        );
8613
8614        // Test round-trip preserves the custom category name
8615        let json = serde_json::to_value(&custom).unwrap();
8616        assert_eq!(json, json!("_my_custom_category"));
8617
8618        // Deserialize back and verify
8619        let deserialized: SessionConfigOptionCategory = serde_json::from_value(json).unwrap();
8620        assert_eq!(
8621            deserialized,
8622            SessionConfigOptionCategory::Other("_my_custom_category".to_string()),
8623        );
8624    }
8625
8626    fn test_config_option() -> SessionConfigOption {
8627        SessionConfigOption::select(
8628            "mode",
8629            "Mode",
8630            "ask",
8631            vec![SessionConfigSelectOption::new("ask", "Ask")],
8632        )
8633    }
8634
8635    #[test]
8636    fn test_session_response_initial_state_default_empty_and_skip_serializing() {
8637        assert_eq!(
8638            serde_json::to_value(NewSessionResponse::new("sess")).unwrap(),
8639            json!({ "sessionId": "sess" })
8640        );
8641        assert_eq!(
8642            serde_json::to_value(ResumeSessionResponse::new()).unwrap(),
8643            json!({})
8644        );
8645        #[cfg(feature = "unstable_session_fork")]
8646        assert_eq!(
8647            serde_json::to_value(ForkSessionResponse::new("fork")).unwrap(),
8648            json!({ "sessionId": "fork" })
8649        );
8650
8651        let json = serde_json::to_value(
8652            NewSessionResponse::new("sess").config_options(vec![test_config_option()]),
8653        )
8654        .unwrap();
8655        assert_eq!(json["configOptions"].as_array().unwrap().len(), 1);
8656    }
8657
8658    #[test]
8659    fn test_session_response_config_options_deserialize_missing_null_and_invalid() {
8660        let missing: NewSessionResponse =
8661            serde_json::from_value(json!({ "sessionId": "sess" })).unwrap();
8662        assert_eq!(missing.config_options, []);
8663
8664        let null: NewSessionResponse = serde_json::from_value(json!({
8665            "sessionId": "sess",
8666            "configOptions": null
8667        }))
8668        .unwrap();
8669        assert_eq!(null.config_options, []);
8670
8671        let wrong_shape: NewSessionResponse = serde_json::from_value(json!({
8672            "sessionId": "sess",
8673            "configOptions": "oops"
8674        }))
8675        .unwrap();
8676        assert_eq!(wrong_shape.config_options, []);
8677
8678        let valid_option = serde_json::to_value(test_config_option()).unwrap();
8679        let mixed: NewSessionResponse = serde_json::from_value(json!({
8680            "sessionId": "sess",
8681            "configOptions": ["oops", valid_option]
8682        }))
8683        .unwrap();
8684        assert_eq!(mixed.config_options.len(), 1);
8685
8686        let resume: ResumeSessionResponse = serde_json::from_value(json!({})).unwrap();
8687        assert_eq!(resume.config_options, []);
8688        #[cfg(feature = "unstable_session_fork")]
8689        {
8690            let fork: ForkSessionResponse =
8691                serde_json::from_value(json!({ "sessionId": "fork" })).unwrap();
8692            assert_eq!(fork.config_options, []);
8693        }
8694    }
8695
8696    #[test]
8697    fn test_session_response_available_commands_roundtrip_with_config_options() {
8698        use super::super::{AvailableCommandInput, Command, TextCommandInput};
8699
8700        let commands = vec![
8701            AvailableCommand::Command(
8702                Command::new("web", "Search the web")
8703                    .input(AvailableCommandInput::Text(TextCommandInput::new("Query"))),
8704            ),
8705            AvailableCommand::Command(Command::new("test", "Run project tests")),
8706        ];
8707        let mut expected = json!({
8708            "sessionId": "sess",
8709            "configOptions": [test_config_option()],
8710            "availableCommands": [
8711                {
8712                    "type": "command",
8713                    "name": "web",
8714                    "description": "Search the web",
8715                    "input": { "type": "text", "hint": "Query" }
8716                },
8717                { "type": "command", "name": "test", "description": "Run project tests" }
8718            ]
8719        });
8720
8721        let new = NewSessionResponse::new("sess")
8722            .config_options(vec![test_config_option()])
8723            .available_commands(commands.clone());
8724        assert_eq!(serde_json::to_value(&new).unwrap(), expected);
8725        assert_eq!(
8726            serde_json::from_value::<NewSessionResponse>(expected.clone()).unwrap(),
8727            new
8728        );
8729
8730        expected.as_object_mut().unwrap().remove("sessionId");
8731        let resume = ResumeSessionResponse::new()
8732            .config_options(vec![test_config_option()])
8733            .available_commands(commands.clone());
8734        assert_eq!(serde_json::to_value(&resume).unwrap(), expected);
8735        assert_eq!(
8736            serde_json::from_value::<ResumeSessionResponse>(expected.clone()).unwrap(),
8737            resume
8738        );
8739
8740        #[cfg(feature = "unstable_session_fork")]
8741        {
8742            expected["sessionId"] = json!("fork");
8743            let fork = ForkSessionResponse::new("fork")
8744                .config_options(vec![test_config_option()])
8745                .available_commands(commands);
8746            assert_eq!(serde_json::to_value(&fork).unwrap(), expected);
8747            assert_eq!(
8748                serde_json::from_value::<ForkSessionResponse>(expected).unwrap(),
8749                fork
8750            );
8751        }
8752    }
8753
8754    #[test]
8755    fn test_session_response_available_commands_deserialize_missing_null_and_invalid() {
8756        let command =
8757            AvailableCommand::Command(super::super::Command::new("test", "Run project tests"));
8758        let config_options = vec![test_config_option()];
8759
8760        for (commands, expected) in [
8761            (None, vec![]),
8762            (Some(json!(null)), vec![]),
8763            (Some(json!([])), vec![]),
8764            (Some(json!("oops")), vec![]),
8765            (Some(json!({})), vec![]),
8766            (Some(json!([null, {}, { "name": "invalid" }])), vec![]),
8767            (
8768                Some(json!([{ "name": "test", "description": "Run project tests" }])),
8769                vec![],
8770            ),
8771            (
8772                Some(json!([null, command, { "name": "invalid" }])),
8773                vec![command.clone()],
8774            ),
8775        ] {
8776            let mut value = json!({
8777                "sessionId": "sess",
8778                "configOptions": config_options
8779            });
8780            if let Some(commands) = commands {
8781                value["availableCommands"] = commands;
8782            }
8783
8784            let new: NewSessionResponse = serde_json::from_value(value.clone()).unwrap();
8785            assert_eq!(new.available_commands, expected);
8786            assert_eq!(new.config_options, config_options);
8787
8788            #[cfg(feature = "unstable_session_fork")]
8789            {
8790                let fork: ForkSessionResponse = serde_json::from_value(value.clone()).unwrap();
8791                assert_eq!(fork.available_commands, expected);
8792                assert_eq!(fork.config_options, config_options);
8793            }
8794
8795            value.as_object_mut().unwrap().remove("sessionId");
8796            let resume: ResumeSessionResponse = serde_json::from_value(value).unwrap();
8797            assert_eq!(resume.available_commands, expected);
8798            assert_eq!(resume.config_options, config_options);
8799        }
8800
8801        let resume: ResumeSessionResponse = serde_json::from_value(json!(null)).unwrap();
8802        assert_eq!(resume.available_commands, []);
8803    }
8804
8805    #[test]
8806    fn test_resume_session_replay_from_serialization() {
8807        assert_eq!(
8808            serde_json::to_value(ResumeSessionRequest::new(
8809                "sess_abc123",
8810                "/home/user/project"
8811            ))
8812            .unwrap(),
8813            json!({
8814                "sessionId": "sess_abc123",
8815                "cwd": "/home/user/project"
8816            })
8817        );
8818        assert_eq!(
8819            serde_json::to_value(
8820                ResumeSessionRequest::new("sess_abc123", "/home/user/project")
8821                    .replay_from(ReplayFrom::from(ReplayFromStart::new()))
8822            )
8823            .unwrap(),
8824            json!({
8825                "sessionId": "sess_abc123",
8826                "cwd": "/home/user/project",
8827                "replayFrom": {
8828                    "type": "start"
8829                }
8830            })
8831        );
8832
8833        let replay: ResumeSessionRequest = serde_json::from_value(json!({
8834            "sessionId": "sess_abc123",
8835            "cwd": "/home/user/project",
8836            "replayFrom": {
8837                "type": "start"
8838            }
8839        }))
8840        .unwrap();
8841        assert!(matches!(replay.replay_from, Some(ReplayFrom::Start(_))));
8842
8843        let none: ResumeSessionRequest = serde_json::from_value(json!({
8844            "sessionId": "sess_abc123",
8845            "cwd": "/home/user/project",
8846            "replayFrom": null
8847        }))
8848        .unwrap();
8849        assert!(none.replay_from.is_none());
8850    }
8851
8852    #[test]
8853    fn test_auth_method_agent_serialization() {
8854        let method = AuthMethod::Agent(AuthMethodAgent::new("default-auth", "Default Auth"));
8855
8856        let json = serde_json::to_value(&method).unwrap();
8857        assert_eq!(
8858            json,
8859            json!({
8860                "methodId": "default-auth",
8861                "name": "Default Auth",
8862                "type": "agent"
8863            })
8864        );
8865        // description should be omitted when None
8866        assert!(!json.as_object().unwrap().contains_key("description"));
8867
8868        let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
8869        match deserialized {
8870            AuthMethod::Agent(AuthMethodAgent {
8871                method_id, name, ..
8872            }) => {
8873                assert_eq!(method_id.0.as_ref(), "default-auth");
8874                assert_eq!(name, "Default Auth");
8875            }
8876            _ => panic!("Expected Agent variant"),
8877        }
8878    }
8879
8880    #[test]
8881    fn test_auth_method_agent_deserialization() {
8882        let json = json!({
8883            "methodId": "agent-auth",
8884            "name": "Agent Auth",
8885            "type": "agent"
8886        });
8887
8888        let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
8889        assert!(matches!(deserialized, AuthMethod::Agent(_)));
8890    }
8891
8892    #[test]
8893    fn test_auth_method_agent_requires_type() {
8894        assert!(
8895            serde_json::from_value::<AuthMethod>(json!({
8896                "methodId": "agent-auth",
8897                "name": "Agent Auth"
8898            }))
8899            .is_err()
8900        );
8901    }
8902
8903    #[test]
8904    fn test_auth_method_agent_rejects_null_type() {
8905        assert!(
8906            serde_json::from_value::<AuthMethod>(json!({
8907                "methodId": "agent-auth",
8908                "name": "Agent Auth",
8909                "type": null
8910            }))
8911            .is_err()
8912        );
8913    }
8914
8915    #[test]
8916    fn test_auth_method_unknown_does_not_hide_malformed_agent() {
8917        assert!(
8918            serde_json::from_value::<AuthMethod>(json!({
8919                "methodId": "agent-auth",
8920                "type": "agent"
8921            }))
8922            .is_err()
8923        );
8924        assert!(
8925            serde_json::from_value::<AuthMethod>(json!({
8926                "methodId": "api-key",
8927                "type": "env_var",
8928                "vars": [{"name": "API_KEY"}]
8929            }))
8930            .is_err()
8931        );
8932    }
8933
8934    #[test]
8935    fn test_auth_method_unknown_variant_roundtrip() {
8936        let method: AuthMethod = serde_json::from_value(json!({
8937            "methodId": "oauth",
8938            "name": "OAuth",
8939            "type": "_oauth",
8940            "authorizationUrl": "https://example.com/auth"
8941        }))
8942        .unwrap();
8943
8944        assert_eq!(method.method_id().0.as_ref(), "oauth");
8945        assert_eq!(method.name(), "OAuth");
8946        let AuthMethod::Other(unknown) = method else {
8947            panic!("expected unknown auth method");
8948        };
8949        assert_eq!(unknown.type_, "_oauth");
8950        assert_eq!(
8951            unknown.fields.get("authorizationUrl"),
8952            Some(&json!("https://example.com/auth"))
8953        );
8954
8955        assert_eq!(
8956            serde_json::to_value(AuthMethod::Other(unknown)).unwrap(),
8957            json!({
8958                "methodId": "oauth",
8959                "name": "OAuth",
8960                "type": "_oauth",
8961                "authorizationUrl": "https://example.com/auth"
8962            })
8963        );
8964    }
8965
8966    #[test]
8967    fn test_auth_method_unknown_does_not_hide_malformed_known_variant() {
8968        assert!(
8969            serde_json::from_value::<AuthMethod>(json!({
8970                "methodId": "terminal-auth",
8971                "type": "terminal"
8972            }))
8973            .is_err()
8974        );
8975    }
8976
8977    #[test]
8978    fn test_tool_call_and_terminal_cancel_serialization() {
8979        assert_eq!(AGENT_METHOD_NAMES.tool_call_cancel, "tool_call/cancel");
8980        assert_eq!(AGENT_METHOD_NAMES.terminal_cancel, "terminal/cancel");
8981        assert_eq!(
8982            ClientRequest::CancelToolCallRequest(Box::new(CancelToolCallRequest::new(
8983                "sess_abc123",
8984                "call_012"
8985            )))
8986            .method(),
8987            "tool_call/cancel"
8988        );
8989        assert_eq!(
8990            ClientRequest::CancelTerminalRequest(Box::new(CancelTerminalRequest::new(
8991                "sess_abc123",
8992                "term_003"
8993            )))
8994            .method(),
8995            "terminal/cancel"
8996        );
8997        assert_eq!(
8998            serde_json::to_value(CancelToolCallRequest::new("sess_abc123", "call_012")).unwrap(),
8999            json!({"sessionId": "sess_abc123", "toolCallId": "call_012"})
9000        );
9001        assert_eq!(
9002            serde_json::to_value(CancelTerminalRequest::new("sess_abc123", "term_003")).unwrap(),
9003            json!({"sessionId": "sess_abc123", "terminalId": "term_003"})
9004        );
9005        assert!(
9006            serde_json::from_value::<CancelToolCallRequest>(json!({"sessionId": "sess_abc123"}))
9007                .is_err()
9008        );
9009        assert_eq!(
9010            serde_json::to_value(CancelTerminalResponse::new()).unwrap(),
9011            json!({})
9012        );
9013    }
9014
9015    #[test]
9016    fn test_session_delete_serialization() {
9017        assert_eq!(AGENT_METHOD_NAMES.session_delete, "session/delete");
9018        assert_eq!(
9019            ClientRequest::DeleteSessionRequest(Box::new(DeleteSessionRequest::new("sess_abc123")))
9020                .method(),
9021            "session/delete"
9022        );
9023        assert_eq!(
9024            serde_json::to_value(DeleteSessionRequest::new("sess_abc123")).unwrap(),
9025            json!({
9026                "sessionId": "sess_abc123"
9027            })
9028        );
9029        assert_eq!(
9030            serde_json::to_value(DeleteSessionResponse::new()).unwrap(),
9031            json!({})
9032        );
9033        assert_eq!(
9034            serde_json::to_value(
9035                SessionCapabilities::new().delete(SessionDeleteCapabilities::new())
9036            )
9037            .unwrap(),
9038            json!({
9039                "delete": {}
9040            })
9041        );
9042    }
9043    #[cfg(feature = "unstable_session_set_title")]
9044    #[test]
9045    fn test_session_set_title_serialization() {
9046        assert_eq!(AGENT_METHOD_NAMES.session_set_title, "session/set_title");
9047        assert_eq!(
9048            ClientRequest::SetSessionTitleRequest(Box::new(SetSessionTitleRequest::new(
9049                "sess_abc123",
9050                "Investigate OAuth timeout"
9051            )))
9052            .method(),
9053            "session/set_title"
9054        );
9055        assert_eq!(
9056            serde_json::to_value(SetSessionTitleRequest::new(
9057                "sess_abc123",
9058                "Investigate OAuth timeout"
9059            ))
9060            .unwrap(),
9061            json!({
9062                "sessionId": "sess_abc123",
9063                "title": "Investigate OAuth timeout"
9064            })
9065        );
9066        assert_eq!(
9067            serde_json::to_value(SetSessionTitleResponse::new("Investigate OAuth timeout"))
9068                .unwrap(),
9069            json!({
9070                "title": "Investigate OAuth timeout"
9071            })
9072        );
9073        assert_eq!(
9074            serde_json::to_value(SessionCapabilities::new().title(SessionTitleCapabilities::new()))
9075                .unwrap(),
9076            json!({
9077                "title": {}
9078            })
9079        );
9080    }
9081
9082    #[cfg(feature = "unstable_session_set_title")]
9083    #[test]
9084    fn test_session_set_title_requires_title() {
9085        for params in [
9086            json!({"sessionId": "sess_abc123"}),
9087            json!({"sessionId": "sess_abc123", "title": null}),
9088            json!({"sessionId": "sess_abc123", "title": 42}),
9089        ] {
9090            assert!(serde_json::from_value::<SetSessionTitleRequest>(params).is_err());
9091        }
9092        for result in [json!({}), json!({"title": null})] {
9093            assert!(serde_json::from_value::<SetSessionTitleResponse>(result).is_err());
9094        }
9095    }
9096
9097    #[cfg(feature = "unstable_session_options")]
9098    #[test]
9099    fn test_session_options_serialization() {
9100        assert_eq!(AGENT_METHOD_NAMES.session_options, "session/options");
9101        assert_eq!(
9102            ClientRequest::SessionOptionsRequest(Box::new(SessionOptionsRequest::new(
9103                "/home/user/project"
9104            )))
9105            .method(),
9106            "session/options"
9107        );
9108        assert_eq!(
9109            serde_json::to_value(
9110                SessionOptionsRequest::new("/home/user/project")
9111                    .session_id(SessionId::new("sess_abc123"))
9112            )
9113            .unwrap(),
9114            json!({"cwd": "/home/user/project", "sessionId": "sess_abc123"})
9115        );
9116        assert_eq!(
9117            serde_json::from_value::<SessionOptionsRequest>(
9118                json!({"cwd": "/home/user/project", "additionalDirectories": null, "sessionId": null})
9119            )
9120            .unwrap(),
9121            SessionOptionsRequest::new("/home/user/project")
9122        );
9123        let request = NewSessionRequest::new("/home/user/project").config_options(vec![
9124            InitialSessionConfigOption::new("model", SessionConfigOptionValue::id("model-2")),
9125            InitialSessionConfigOption::new("fast", SessionConfigOptionValue::boolean(true)),
9126        ]);
9127        let value = serde_json::to_value(&request).unwrap();
9128        assert_eq!(
9129            value["configOptions"],
9130            json!([
9131                {"configId": "model", "type": "id", "value": "model-2"},
9132                {"configId": "fast", "type": "boolean", "value": true}
9133            ])
9134        );
9135        assert_eq!(
9136            serde_json::from_value::<NewSessionRequest>(value).unwrap(),
9137            request
9138        );
9139        assert!(
9140            serde_json::from_value::<NewSessionRequest>(json!({
9141                "cwd": "/home/user/project",
9142                "mcpServers": [],
9143                "configOptions": [{"type": "boolean", "value": true}]
9144            }))
9145            .is_err()
9146        );
9147        assert_eq!(
9148            serde_json::to_value(SessionOptionsResponse::new()).unwrap(),
9149            json!({})
9150        );
9151        #[cfg(feature = "unstable_session_fork")]
9152        {
9153            let fork =
9154                ForkSessionRequest::new("sess_abc123", "/home/user/project").config_options(vec![
9155                    InitialSessionConfigOption::new(
9156                        "model",
9157                        SessionConfigOptionValue::id("model-2"),
9158                    ),
9159                ]);
9160            let value = serde_json::to_value(&fork).unwrap();
9161            assert_eq!(
9162                value["configOptions"],
9163                json!([{"configId": "model", "type": "id", "value": "model-2"}])
9164            );
9165            assert_eq!(
9166                serde_json::from_value::<ForkSessionRequest>(value).unwrap(),
9167                fork
9168            );
9169            // `null` is an empty list, and a malformed entry fails the request.
9170            assert_eq!(
9171                serde_json::from_value::<ForkSessionRequest>(json!({
9172                    "sessionId": "sess_abc123",
9173                    "cwd": "/home/user/project",
9174                    "configOptions": null
9175                }))
9176                .unwrap(),
9177                ForkSessionRequest::new("sess_abc123", "/home/user/project")
9178            );
9179            assert!(
9180                serde_json::from_value::<ForkSessionRequest>(json!({
9181                    "sessionId": "sess_abc123",
9182                    "cwd": "/home/user/project",
9183                    "configOptions": [{"type": "boolean", "value": true}]
9184                }))
9185                .is_err()
9186            );
9187        }
9188        assert_eq!(
9189            serde_json::to_value(
9190                SessionCapabilities::new().options(SessionOptionsCapabilities::new())
9191            )
9192            .unwrap(),
9193            json!({"options": {}})
9194        );
9195    }
9196
9197    #[cfg(feature = "unstable_session_status")]
9198    #[test]
9199    fn test_session_status_serialization() {
9200        assert_eq!(AGENT_METHOD_NAMES.session_status, "session/status");
9201        assert_eq!(
9202            ClientRequest::SessionStatusRequest(Box::new(SessionStatusRequest::new("sess_abc123")))
9203                .method(),
9204            "session/status"
9205        );
9206        assert_eq!(
9207            serde_json::to_value(SessionStatusRequest::new("sess_abc123")).unwrap(),
9208            json!({"sessionId": "sess_abc123"})
9209        );
9210        assert_eq!(
9211            serde_json::to_value(SessionStatusResponse::new(SessionStatus::Saved)).unwrap(),
9212            json!({"status": "saved"})
9213        );
9214        assert_eq!(
9215            serde_json::to_value(
9216                SessionCapabilities::new().status(SessionStatusCapabilities::new())
9217            )
9218            .unwrap(),
9219            json!({"status": {}})
9220        );
9221        assert_eq!(
9222            serde_json::to_value(SessionStatusResponse::new(SessionStatus::Open).state(
9223                StateUpdate::RequiresAction(crate::v2::RequiresActionStateUpdate::new())
9224            ))
9225            .unwrap(),
9226            json!({
9227                "status": "open",
9228                "state": {"state": "requires_action"}
9229            })
9230        );
9231        for state in [json!(null), json!("running"), json!({"state": 7})] {
9232            let response = serde_json::from_value::<SessionStatusResponse>(
9233                json!({"status": "open", "state": state}),
9234            )
9235            .unwrap();
9236            assert_eq!(response.state, None);
9237        }
9238    }
9239
9240    #[cfg(feature = "unstable_session_status")]
9241    #[test]
9242    fn test_session_status_is_strict_and_open() {
9243        let custom =
9244            serde_json::from_value::<SessionStatusResponse>(json!({"status": "_suspended"}))
9245                .unwrap();
9246        assert_eq!(
9247            custom.status,
9248            SessionStatus::Other("_suspended".to_string())
9249        );
9250        assert_eq!(
9251            serde_json::to_value(&custom).unwrap(),
9252            json!({"status": "_suspended"})
9253        );
9254        for result in [json!({}), json!({"status": null}), json!({"status": 1})] {
9255            assert!(serde_json::from_value::<SessionStatusResponse>(result).is_err());
9256        }
9257        for params in [json!({}), json!({"sessionId": null})] {
9258            assert!(serde_json::from_value::<SessionStatusRequest>(params).is_err());
9259        }
9260    }
9261
9262    #[cfg(feature = "unstable_session_archive")]
9263    #[test]
9264    fn test_session_archive_serialization() {
9265        assert_eq!(AGENT_METHOD_NAMES.session_archive, "session/archive");
9266        assert_eq!(AGENT_METHOD_NAMES.session_unarchive, "session/unarchive");
9267        assert_eq!(
9268            ClientRequest::ArchiveSessionRequest(Box::new(ArchiveSessionRequest::new(
9269                "sess_abc123"
9270            )))
9271            .method(),
9272            "session/archive"
9273        );
9274        assert_eq!(
9275            ClientRequest::UnarchiveSessionRequest(Box::new(UnarchiveSessionRequest::new(
9276                "sess_abc123"
9277            )))
9278            .method(),
9279            "session/unarchive"
9280        );
9281        assert_eq!(
9282            serde_json::to_value(ArchiveSessionRequest::new("sess_abc123")).unwrap(),
9283            json!({"sessionId": "sess_abc123"})
9284        );
9285        assert_eq!(
9286            serde_json::to_value(UnarchiveSessionResponse::new()).unwrap(),
9287            json!({})
9288        );
9289        assert_eq!(
9290            serde_json::to_value(
9291                SessionCapabilities::new().archive(SessionArchiveCapabilities::new())
9292            )
9293            .unwrap(),
9294            json!({"archive": {}})
9295        );
9296        assert_eq!(
9297            serde_json::to_value(
9298                ListSessionsRequest::new()
9299                    .cwd("/home/user/project")
9300                    .archived(SessionArchiveFilter::Only)
9301            )
9302            .unwrap(),
9303            json!({"cwd": "/home/user/project", "archived": "only"})
9304        );
9305        assert_eq!(
9306            serde_json::to_value(
9307                SessionInfo::new("sess_abc123", "/home/user/project").archived(true)
9308            )
9309            .unwrap(),
9310            json!({"sessionId": "sess_abc123", "cwd": "/home/user/project", "archived": true})
9311        );
9312    }
9313
9314    #[cfg(feature = "unstable_session_archive")]
9315    #[test]
9316    fn test_session_archive_filter_is_strict_and_open() {
9317        for (value, expected) in [
9318            (json!(null), None),
9319            (json!("include"), Some(SessionArchiveFilter::Include)),
9320            (
9321                json!("_recent"),
9322                Some(SessionArchiveFilter::Other("_recent".to_string())),
9323            ),
9324        ] {
9325            let request =
9326                serde_json::from_value::<ListSessionsRequest>(json!({"archived": value})).unwrap();
9327            assert_eq!(request.archived, expected);
9328        }
9329        for value in [json!(true), json!(1), json!({})] {
9330            assert!(
9331                serde_json::from_value::<ListSessionsRequest>(json!({"archived": value})).is_err()
9332            );
9333        }
9334        let info = serde_json::from_value::<SessionInfo>(
9335            json!({"sessionId": "sess_abc123", "cwd": "/home/user/project", "archived": "yes"}),
9336        )
9337        .unwrap();
9338        assert_eq!(info.archived, None);
9339    }
9340
9341    #[test]
9342    fn test_session_additional_directories_serialization() {
9343        assert_eq!(
9344            serde_json::to_value(NewSessionRequest::new("/home/user/project")).unwrap(),
9345            json!({
9346                "cwd": "/home/user/project",
9347            })
9348        );
9349        assert_eq!(
9350            serde_json::to_value(
9351                NewSessionRequest::new("/home/user/project").additional_directories(vec![
9352                    PathBuf::from("/home/user/shared-lib"),
9353                    PathBuf::from("/home/user/product-docs"),
9354                ])
9355            )
9356            .unwrap(),
9357            json!({
9358                "cwd": "/home/user/project",
9359                "additionalDirectories": [
9360                    "/home/user/shared-lib",
9361                    "/home/user/product-docs"
9362                ],
9363            })
9364        );
9365        assert_eq!(
9366            serde_json::to_value(ResumeSessionRequest::new(
9367                "sess_abc123",
9368                "/home/user/project"
9369            ))
9370            .unwrap(),
9371            json!({
9372                "sessionId": "sess_abc123",
9373                "cwd": "/home/user/project",
9374            })
9375        );
9376        assert_eq!(
9377            serde_json::from_value::<ResumeSessionRequest>(json!({
9378                "sessionId": "sess_abc123",
9379                "cwd": "/home/user/project"
9380            }))
9381            .unwrap()
9382            .mcp_servers,
9383            Vec::<McpServer>::new()
9384        );
9385        assert_eq!(
9386            serde_json::from_value::<ResumeSessionRequest>(json!({
9387                "sessionId": "sess_abc123",
9388                "cwd": "/home/user/project",
9389                "mcpServers": null
9390            }))
9391            .unwrap()
9392            .mcp_servers,
9393            Vec::<McpServer>::new()
9394        );
9395        assert_eq!(
9396            serde_json::to_value(SessionInfo::new("sess_abc123", "/home/user/project")).unwrap(),
9397            json!({
9398                "sessionId": "sess_abc123",
9399                "cwd": "/home/user/project"
9400            })
9401        );
9402        assert_eq!(
9403            serde_json::to_value(
9404                SessionInfo::new("sess_abc123", "/home/user/project").additional_directories(vec![
9405                    PathBuf::from("/home/user/shared-lib"),
9406                    PathBuf::from("/home/user/product-docs"),
9407                ])
9408            )
9409            .unwrap(),
9410            json!({
9411                "sessionId": "sess_abc123",
9412                "cwd": "/home/user/project",
9413                "additionalDirectories": [
9414                    "/home/user/shared-lib",
9415                    "/home/user/product-docs"
9416                ]
9417            })
9418        );
9419        assert_eq!(
9420            serde_json::from_value::<SessionInfo>(json!({
9421                "sessionId": "sess_abc123",
9422                "cwd": "/home/user/project"
9423            }))
9424            .unwrap()
9425            .additional_directories,
9426            Vec::<AbsolutePath>::new()
9427        );
9428    }
9429    #[test]
9430    fn test_session_additional_directories_capabilities_serialization() {
9431        assert_eq!(
9432            serde_json::to_value(
9433                SessionCapabilities::new()
9434                    .additional_directories(SessionAdditionalDirectoriesCapabilities::new())
9435            )
9436            .unwrap(),
9437            json!({
9438                "additionalDirectories": {}
9439            })
9440        );
9441    }
9442
9443    #[test]
9444    fn test_session_system_prompt_capabilities_serialization() {
9445        assert_eq!(
9446            serde_json::to_value(
9447                SessionCapabilities::new().system_prompt(SessionSystemPromptCapabilities::new())
9448            )
9449            .unwrap(),
9450            json!({ "systemPrompt": {} })
9451        );
9452        assert_eq!(
9453            serde_json::to_value(
9454                SessionCapabilities::new().system_prompt(
9455                    SessionSystemPromptCapabilities::new().mode(
9456                        SessionSystemPromptModeCapabilities::new()
9457                            .override_(SessionSystemPromptOverrideCapabilities::new())
9458                    )
9459                )
9460            )
9461            .unwrap(),
9462            json!({ "systemPrompt": { "mode": { "override": {} } } })
9463        );
9464        assert_eq!(
9465            serde_json::from_value::<SessionCapabilities>(
9466                json!({ "systemPrompt": { "mode": { "override": {} } } })
9467            )
9468            .unwrap()
9469            .system_prompt
9470            .and_then(|capabilities| capabilities.mode)
9471            .and_then(|mode| mode.override_),
9472            Some(SessionSystemPromptOverrideCapabilities::new())
9473        );
9474
9475        // Capabilities fall back to "not advertised" when malformed.
9476        assert_eq!(
9477            serde_json::from_value::<SessionCapabilities>(json!({ "systemPrompt": "yes" }))
9478                .unwrap()
9479                .system_prompt,
9480            None
9481        );
9482        assert_eq!(
9483            serde_json::from_value::<SessionCapabilities>(
9484                json!({ "systemPrompt": { "mode": { "override": true } } })
9485            )
9486            .unwrap()
9487            .system_prompt,
9488            Some(
9489                SessionSystemPromptCapabilities::new()
9490                    .mode(SessionSystemPromptModeCapabilities::new())
9491            )
9492        );
9493        assert_eq!(
9494            serde_json::from_value::<SessionCapabilities>(
9495                json!({ "systemPrompt": { "mode": "override" } })
9496            )
9497            .unwrap()
9498            .system_prompt,
9499            Some(SessionSystemPromptCapabilities::new())
9500        );
9501    }
9502
9503    #[test]
9504    fn test_system_prompt_lifecycle_request_serialization() {
9505        let system_prompt = SystemPrompt::new(vec![ContentBlock::from(
9506            "You are a code review specialist.",
9507        )]);
9508        let system_prompt_json = json!({
9509            "mode": "append",
9510            "content": [{ "type": "text", "text": "You are a code review specialist." }]
9511        });
9512
9513        let request =
9514            NewSessionRequest::new("/home/user/project").system_prompt(system_prompt.clone());
9515        let request_json = json!({
9516            "cwd": "/home/user/project",
9517            "systemPrompt": system_prompt_json
9518        });
9519        assert_eq!(serde_json::to_value(&request).unwrap(), request_json);
9520        assert_eq!(
9521            serde_json::from_value::<NewSessionRequest>(request_json).unwrap(),
9522            request
9523        );
9524
9525        assert_eq!(
9526            serde_json::to_value(
9527                ResumeSessionRequest::new("sess_abc123", "/home/user/project")
9528                    .system_prompt(system_prompt.clone())
9529            )
9530            .unwrap()["systemPrompt"],
9531            system_prompt_json
9532        );
9533        #[cfg(feature = "unstable_session_fork")]
9534        assert_eq!(
9535            serde_json::to_value(
9536                ForkSessionRequest::new("sess_abc123", "/home/user/project")
9537                    .system_prompt(system_prompt.clone())
9538            )
9539            .unwrap()["systemPrompt"],
9540            system_prompt_json
9541        );
9542
9543        let override_prompt =
9544            SystemPrompt::new(vec![ContentBlock::from("...")]).mode(SystemPromptMode::Override);
9545        let override_json = json!({
9546            "mode": "override",
9547            "content": [{ "type": "text", "text": "..." }]
9548        });
9549        assert_eq!(
9550            serde_json::to_value(&override_prompt).unwrap(),
9551            override_json
9552        );
9553        assert_eq!(
9554            serde_json::from_value::<SystemPrompt>(override_json).unwrap(),
9555            override_prompt
9556        );
9557    }
9558
9559    /// `SystemPrompt::new` defaults to `append` in Rust, but `mode` is required on
9560    /// the wire, so it is always serialized.
9561    #[test]
9562    fn test_system_prompt_new_defaults_to_append() {
9563        let system_prompt = SystemPrompt::new(vec![ContentBlock::from("...")]);
9564        assert_eq!(system_prompt.mode, SystemPromptMode::Append);
9565        assert_eq!(
9566            serde_json::to_value(&system_prompt).unwrap(),
9567            json!({ "mode": "append", "content": [{ "type": "text", "text": "..." }] })
9568        );
9569    }
9570
9571    /// Unknown modes follow the enum variant extension rule: they parse as
9572    /// `SystemPromptMode::Other` so they are not dropped, and an agent that does
9573    /// not support them must reject the request.
9574    #[test]
9575    fn test_system_prompt_preserves_unknown_modes() {
9576        for mode in ["_vendor_mode", "prepend"] {
9577            let system_prompt_json =
9578                json!({ "mode": mode, "content": [{ "type": "text", "text": "..." }] });
9579            let system_prompt: SystemPrompt =
9580                serde_json::from_value(system_prompt_json.clone()).unwrap();
9581            assert_eq!(
9582                system_prompt.mode,
9583                SystemPromptMode::Other(mode.to_string())
9584            );
9585            assert_eq!(
9586                serde_json::to_value(&system_prompt).unwrap(),
9587                system_prompt_json
9588            );
9589        }
9590    }
9591
9592    /// The receiver acts on `systemPrompt`, so malformed values fail the request
9593    /// (`-32602`) instead of creating a session without the prompt, and `null`
9594    /// is equivalent to omitting the field.
9595    fn assert_system_prompt_is_strict<T>(base: &serde_json::Value)
9596    where
9597        T: serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
9598    {
9599        let name = std::any::type_name::<T>();
9600        let with = |system_prompt: serde_json::Value| {
9601            let mut request = base.clone();
9602            request["systemPrompt"] = system_prompt;
9603            serde_json::from_value::<T>(request)
9604        };
9605
9606        for system_prompt in [
9607            json!("You are a code review specialist."),
9608            json!({ "content": [{ "type": "text", "text": "..." }] }),
9609            json!({ "mode": null, "content": [{ "type": "text", "text": "..." }] }),
9610            json!({ "mode": 1, "content": [{ "type": "text", "text": "..." }] }),
9611            json!({ "mode": "append" }),
9612            json!({ "mode": "append", "content": "..." }),
9613            json!({ "mode": "append", "content": [{ "type": "text" }] }),
9614        ] {
9615            assert!(
9616                with(system_prompt.clone()).is_err(),
9617                "{name}.systemPrompt: {system_prompt}"
9618            );
9619        }
9620
9621        assert_eq!(
9622            with(serde_json::Value::Null).unwrap(),
9623            serde_json::from_value::<T>(base.clone()).unwrap(),
9624            "{name}.systemPrompt"
9625        );
9626    }
9627
9628    #[test]
9629    fn test_session_setup_requests_reject_malformed_system_prompts() {
9630        assert!(
9631            serde_json::to_value(NewSessionRequest::new("/repo"))
9632                .unwrap()
9633                .get("systemPrompt")
9634                .is_none()
9635        );
9636        assert_system_prompt_is_strict::<NewSessionRequest>(&json!({ "cwd": "/repo" }));
9637        assert_system_prompt_is_strict::<ResumeSessionRequest>(&json!({
9638            "sessionId": "sess-1",
9639            "cwd": "/repo"
9640        }));
9641        #[cfg(feature = "unstable_session_fork")]
9642        assert_system_prompt_is_strict::<ForkSessionRequest>(&json!({
9643            "sessionId": "sess-1",
9644            "cwd": "/repo"
9645        }));
9646    }
9647
9648    /// Unknown content block types parse as `ContentBlock::Other` so they are not
9649    /// dropped. An agent that does not support them must reject the request.
9650    #[test]
9651    fn test_system_prompt_preserves_unknown_content_blocks() {
9652        let request: NewSessionRequest = serde_json::from_value(json!({
9653            "cwd": "/home/user/project",
9654            "systemPrompt": {
9655                "mode": "append",
9656                "content": [{ "type": "_vendor_video", "uri": "https://example.com/intro.mp4" }]
9657            }
9658        }))
9659        .unwrap();
9660        let content = request.system_prompt.unwrap().content;
9661        assert_eq!(content.len(), 1);
9662        assert!(matches!(content[0], ContentBlock::Other(_)));
9663    }
9664
9665    #[test]
9666    fn test_auth_method_terminal_serialization() {
9667        let method = AuthMethod::Terminal(AuthMethodTerminal::new("tui-auth", "Terminal Auth"));
9668
9669        let json = serde_json::to_value(&method).unwrap();
9670        assert_eq!(
9671            json,
9672            json!({
9673                "methodId": "tui-auth",
9674                "name": "Terminal Auth",
9675                "type": "terminal"
9676            })
9677        );
9678        // args and env should be omitted when empty
9679        assert!(!json.as_object().unwrap().contains_key("args"));
9680        assert!(!json.as_object().unwrap().contains_key("env"));
9681
9682        let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9683        match deserialized {
9684            AuthMethod::Terminal(AuthMethodTerminal { args, env, .. }) => {
9685                assert_eq!(args, Vec::<String>::new());
9686                assert_eq!(env, []);
9687            }
9688            _ => panic!("Expected Terminal variant"),
9689        }
9690    }
9691
9692    #[test]
9693    fn test_auth_method_terminal_with_args_and_env_serialization() {
9694        let method = AuthMethod::Terminal(
9695            AuthMethodTerminal::new("tui-auth", "Terminal Auth")
9696                .args(vec!["--interactive".to_string(), "--color".to_string()])
9697                .env(vec![EnvVariable::new("TERM", "xterm-256color")]),
9698        );
9699
9700        let json = serde_json::to_value(&method).unwrap();
9701        assert_eq!(
9702            json,
9703            json!({
9704                "methodId": "tui-auth",
9705                "name": "Terminal Auth",
9706                "type": "terminal",
9707                "args": ["--interactive", "--color"],
9708                "env": [
9709                    {
9710                        "name": "TERM",
9711                        "value": "xterm-256color"
9712                    }
9713                ]
9714            })
9715        );
9716
9717        let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9718        match deserialized {
9719            AuthMethod::Terminal(AuthMethodTerminal { args, env, .. }) => {
9720                assert_eq!(args, vec!["--interactive", "--color"]);
9721                assert_eq!(env.len(), 1);
9722                assert_eq!(env[0].name, "TERM");
9723                assert_eq!(env[0].value, "xterm-256color");
9724            }
9725            _ => panic!("Expected Terminal variant"),
9726        }
9727    }
9728
9729    #[test]
9730    fn test_session_config_option_id_serialize() {
9731        let val = SessionConfigOptionValue::id("model-1");
9732        let json = serde_json::to_value(&val).unwrap();
9733        assert_eq!(json, json!({ "type": "id", "value": "model-1" }));
9734    }
9735
9736    #[test]
9737    fn test_session_config_option_value_boolean_serialize() {
9738        let val = SessionConfigOptionValue::boolean(true);
9739        let json = serde_json::to_value(&val).unwrap();
9740        assert_eq!(json, json!({ "type": "boolean", "value": true }));
9741    }
9742
9743    #[test]
9744    fn test_session_config_option_value_deserialize_id() {
9745        let json = json!({ "type": "id", "value": "model-1" });
9746        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9747        assert_eq!(val, SessionConfigOptionValue::id("model-1"));
9748        assert_eq!(val.as_id().unwrap().to_string(), "model-1");
9749    }
9750
9751    #[test]
9752    fn test_session_config_option_value_deserialize_requires_type() {
9753        let json = json!({ "value": "model-1" });
9754        let result = serde_json::from_value::<SessionConfigOptionValue>(json);
9755        assert!(result.is_err());
9756    }
9757
9758    #[test]
9759    fn test_session_config_option_value_deserialize_boolean() {
9760        let json = json!({ "type": "boolean", "value": true });
9761        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9762        assert_eq!(val, SessionConfigOptionValue::boolean(true));
9763        assert_eq!(val.as_bool(), Some(true));
9764    }
9765
9766    #[test]
9767    fn test_session_config_option_value_deserialize_boolean_false() {
9768        let json = json!({ "type": "boolean", "value": false });
9769        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9770        assert_eq!(val, SessionConfigOptionValue::boolean(false));
9771        assert_eq!(val.as_bool(), Some(false));
9772    }
9773
9774    #[test]
9775    fn test_session_config_option_value_deserialize_unknown_type_with_string_value() {
9776        let json = json!({
9777            "type": "text",
9778            "value": "freeform input",
9779            "maxLength": 200
9780        });
9781        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9782        let SessionConfigOptionValue::Other(unknown) = val else {
9783            panic!("Expected Other variant");
9784        };
9785        assert_eq!(unknown.type_, "text");
9786        assert_eq!(unknown.value, json!("freeform input"));
9787        assert_eq!(unknown.fields["maxLength"], json!(200));
9788    }
9789
9790    #[test]
9791    fn test_session_config_option_value_deserialize_unknown_type_with_object_value() {
9792        let json = json!({
9793            "type": "range",
9794            "value": { "min": 1, "max": 5 }
9795        });
9796        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9797        let SessionConfigOptionValue::Other(unknown) = val else {
9798            panic!("Expected Other variant");
9799        };
9800        assert_eq!(unknown.type_, "range");
9801        assert_eq!(unknown.value, json!({ "min": 1, "max": 5 }));
9802    }
9803
9804    #[test]
9805    fn test_session_config_option_value_roundtrip_id() {
9806        let original = SessionConfigOptionValue::id("option-a");
9807        let json = serde_json::to_value(&original).unwrap();
9808        let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9809        assert_eq!(original, roundtripped);
9810    }
9811
9812    #[test]
9813    fn test_session_config_option_value_roundtrip_boolean() {
9814        let original = SessionConfigOptionValue::boolean(false);
9815        let json = serde_json::to_value(&original).unwrap();
9816        let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9817        assert_eq!(original, roundtripped);
9818    }
9819
9820    #[test]
9821    fn test_session_config_option_value_roundtrip_other() {
9822        let mut fields = BTreeMap::new();
9823        fields.insert("maxLength".to_string(), json!(200));
9824        let original = SessionConfigOptionValue::Other(OtherSessionConfigOptionValue::new(
9825            "text",
9826            json!("freeform input"),
9827            fields,
9828        ));
9829        let json = serde_json::to_value(&original).unwrap();
9830        let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9831        assert_eq!(original, roundtripped);
9832    }
9833
9834    #[test]
9835    fn test_session_config_option_value_type_mismatch_boolean_with_string() {
9836        let json = json!({ "type": "boolean", "value": "not a bool" });
9837        let result = serde_json::from_value::<SessionConfigOptionValue>(json);
9838        assert!(result.is_err());
9839    }
9840
9841    #[test]
9842    fn test_session_config_option_value_from_impls() {
9843        let from_str: SessionConfigOptionValue = "model-1".into();
9844        assert_eq!(from_str.as_id().unwrap().to_string(), "model-1");
9845
9846        let from_id: SessionConfigOptionValue = SessionConfigValueId::new("model-2").into();
9847        assert_eq!(from_id.as_id().unwrap().to_string(), "model-2");
9848
9849        let from_bool: SessionConfigOptionValue = true.into();
9850        assert_eq!(from_bool.as_bool(), Some(true));
9851    }
9852
9853    #[test]
9854    fn test_set_session_config_option_request_id() {
9855        let req = SetSessionConfigOptionRequest::new("sess_1", "model", "model-1");
9856        let json = serde_json::to_value(&req).unwrap();
9857        assert_eq!(
9858            json,
9859            json!({
9860                "sessionId": "sess_1",
9861                "configId": "model",
9862                "type": "id",
9863                "value": "model-1"
9864            })
9865        );
9866    }
9867
9868    #[test]
9869    fn test_set_session_config_option_request_boolean() {
9870        let req = SetSessionConfigOptionRequest::new("sess_1", "brave_mode", true);
9871        let json = serde_json::to_value(&req).unwrap();
9872        assert_eq!(
9873            json,
9874            json!({
9875                "sessionId": "sess_1",
9876                "configId": "brave_mode",
9877                "type": "boolean",
9878                "value": true
9879            })
9880        );
9881    }
9882
9883    #[test]
9884    fn test_set_session_config_option_request_deserialize_requires_type() {
9885        let json = json!({
9886            "sessionId": "sess_1",
9887            "configId": "model",
9888            "value": "model-1"
9889        });
9890        let result = serde_json::from_value::<SetSessionConfigOptionRequest>(json);
9891        assert!(result.is_err());
9892    }
9893
9894    #[test]
9895    fn test_set_session_config_option_request_deserialize_boolean() {
9896        let json = json!({
9897            "sessionId": "sess_1",
9898            "configId": "brave_mode",
9899            "type": "boolean",
9900            "value": true
9901        });
9902        let req: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
9903        assert_eq!(req.value.as_bool(), Some(true));
9904    }
9905
9906    #[test]
9907    fn test_set_session_config_option_request_roundtrip_id() {
9908        let original = SetSessionConfigOptionRequest::new("s", "c", "v");
9909        let json = serde_json::to_value(&original).unwrap();
9910        let roundtripped: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
9911        assert_eq!(original, roundtripped);
9912    }
9913
9914    #[test]
9915    fn test_set_session_config_option_request_roundtrip_boolean() {
9916        let original = SetSessionConfigOptionRequest::new("s", "c", false);
9917        let json = serde_json::to_value(&original).unwrap();
9918        let roundtripped: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
9919        assert_eq!(original, roundtripped);
9920    }
9921
9922    #[test]
9923    fn test_session_config_boolean_serialization() {
9924        let cfg = SessionConfigBoolean::new(true);
9925        let json = serde_json::to_value(&cfg).unwrap();
9926        assert_eq!(json, json!({ "currentValue": true }));
9927
9928        let deserialized: SessionConfigBoolean = serde_json::from_value(json).unwrap();
9929        assert!(deserialized.current_value);
9930    }
9931
9932    #[test]
9933    fn test_session_config_option_boolean_variant() {
9934        let opt = SessionConfigOption::boolean("brave_mode", "Brave Mode", false)
9935            .description("Skip confirmation prompts")
9936            .meta(test_meta());
9937        assert_eq!(serialized_meta_key_count(&opt), 1);
9938
9939        let json = serde_json::to_value(&opt).unwrap();
9940        assert_eq!(
9941            json,
9942            json!({
9943                "configId": "brave_mode",
9944                "name": "Brave Mode",
9945                "description": "Skip confirmation prompts",
9946                "type": "boolean",
9947                "currentValue": false,
9948                "_meta": {
9949                    "source": "test"
9950                }
9951            })
9952        );
9953
9954        let deserialized: SessionConfigOption = serde_json::from_value(json).unwrap();
9955        assert_eq!(deserialized.config_id.to_string(), "brave_mode");
9956        assert_eq!(deserialized.name, "Brave Mode");
9957        match deserialized.kind {
9958            SessionConfigKind::Boolean(ref b) => assert!(!b.current_value),
9959            _ => panic!("Expected Boolean kind"),
9960        }
9961    }
9962
9963    #[test]
9964    fn test_session_config_option_select_still_works() {
9965        // Make sure existing select options are unaffected
9966        let opt = SessionConfigOption::select(
9967            "model",
9968            "Model",
9969            "model-1",
9970            vec![
9971                SessionConfigSelectOption::new("model-1", "Model 1"),
9972                SessionConfigSelectOption::new("model-2", "Model 2"),
9973            ],
9974        )
9975        .meta(test_meta());
9976        assert_eq!(serialized_meta_key_count(&opt), 1);
9977
9978        let json = serde_json::to_value(&opt).unwrap();
9979        assert_eq!(json["type"], "select");
9980        assert_eq!(json["currentValue"], "model-1");
9981        assert_eq!(json["options"].as_array().unwrap().len(), 2);
9982        assert_eq!(json["_meta"]["source"], "test");
9983
9984        let deserialized: SessionConfigOption = serde_json::from_value(json).unwrap();
9985        match deserialized.kind {
9986            SessionConfigKind::Select(ref s) => {
9987                assert_eq!(s.current_value.to_string(), "model-1");
9988            }
9989            _ => panic!("Expected Select kind"),
9990        }
9991    }
9992
9993    #[test]
9994    fn test_session_config_option_unknown_kind_roundtrip() {
9995        let option: SessionConfigOption = serde_json::from_value(json!({
9996            "configId": "verbosity",
9997            "name": "Verbosity",
9998            "type": "_slider",
9999            "currentValue": 3,
10000            "min": 0,
10001            "max": 5,
10002            "_meta": {
10003                "source": "test"
10004            }
10005        }))
10006        .unwrap();
10007
10008        assert_eq!(option.config_id.to_string(), "verbosity");
10009        assert_eq!(option.meta.as_ref().unwrap()["source"], "test");
10010        let SessionConfigKind::Other(unknown) = &option.kind else {
10011            panic!("expected unknown config kind");
10012        };
10013        assert_eq!(unknown.type_, "_slider");
10014        assert_eq!(unknown.fields.get("currentValue"), Some(&json!(3)));
10015        assert!(!unknown.fields.contains_key("_meta"));
10016        assert_eq!(serialized_meta_key_count(&option), 1);
10017
10018        let json = serde_json::to_value(&option).unwrap();
10019        assert_eq!(json["type"], "_slider");
10020        assert_eq!(json["currentValue"], 3);
10021        assert_eq!(json["min"], 0);
10022        assert_eq!(json["max"], 5);
10023        assert_eq!(json["_meta"]["source"], "test");
10024    }
10025
10026    #[test]
10027    fn test_session_config_option_unknown_kind_does_not_duplicate_flattened_meta() {
10028        let mut fields = std::collections::BTreeMap::new();
10029        fields.insert("currentValue".to_string(), json!(3));
10030        fields.insert("_meta".to_string(), json!({ "inner": "ignored" }));
10031
10032        let option = SessionConfigOption::new(
10033            "verbosity",
10034            "Verbosity",
10035            SessionConfigKind::Other(OtherSessionConfigKind::new("_slider", fields)),
10036        )
10037        .meta(test_meta());
10038
10039        let SessionConfigKind::Other(unknown) = &option.kind else {
10040            panic!("expected unknown config kind");
10041        };
10042        assert!(!unknown.fields.contains_key("_meta"));
10043        assert_eq!(serialized_meta_key_count(&option), 1);
10044
10045        let json = serde_json::to_value(&option).unwrap();
10046        assert_eq!(json["type"], "_slider");
10047        assert_eq!(json["currentValue"], 3);
10048        assert_eq!(json["_meta"]["source"], "test");
10049    }
10050
10051    #[test]
10052    fn test_session_config_option_unknown_does_not_hide_malformed_known_kind() {
10053        assert!(
10054            serde_json::from_value::<SessionConfigOption>(json!({
10055                "configId": "model",
10056                "name": "Model",
10057                "type": "select"
10058            }))
10059            .is_err()
10060        );
10061    }
10062
10063    #[cfg(feature = "unstable_llm_providers")]
10064    #[test]
10065    fn test_llm_protocol_known_variants() {
10066        assert_eq!(
10067            serde_json::to_value(&LlmProtocol::Anthropic).unwrap(),
10068            json!("anthropic")
10069        );
10070        assert_eq!(
10071            serde_json::to_value(&LlmProtocol::OpenAi).unwrap(),
10072            json!("openai")
10073        );
10074        assert_eq!(
10075            serde_json::to_value(&LlmProtocol::Azure).unwrap(),
10076            json!("azure")
10077        );
10078        assert_eq!(
10079            serde_json::to_value(&LlmProtocol::Vertex).unwrap(),
10080            json!("vertex")
10081        );
10082        assert_eq!(
10083            serde_json::to_value(&LlmProtocol::Bedrock).unwrap(),
10084            json!("bedrock")
10085        );
10086
10087        assert_eq!(
10088            serde_json::from_str::<LlmProtocol>("\"anthropic\"").unwrap(),
10089            LlmProtocol::Anthropic
10090        );
10091        assert_eq!(
10092            serde_json::from_str::<LlmProtocol>("\"openai\"").unwrap(),
10093            LlmProtocol::OpenAi
10094        );
10095        assert_eq!(
10096            serde_json::from_str::<LlmProtocol>("\"azure\"").unwrap(),
10097            LlmProtocol::Azure
10098        );
10099        assert_eq!(
10100            serde_json::from_str::<LlmProtocol>("\"vertex\"").unwrap(),
10101            LlmProtocol::Vertex
10102        );
10103        assert_eq!(
10104            serde_json::from_str::<LlmProtocol>("\"bedrock\"").unwrap(),
10105            LlmProtocol::Bedrock
10106        );
10107    }
10108
10109    #[cfg(feature = "unstable_llm_providers")]
10110    #[test]
10111    fn test_llm_protocol_unknown_variant() {
10112        let unknown: LlmProtocol = serde_json::from_str("\"cohere\"").unwrap();
10113        assert_eq!(unknown, LlmProtocol::Other("cohere".to_string()));
10114
10115        let json = serde_json::to_value(&unknown).unwrap();
10116        assert_eq!(json, json!("cohere"));
10117    }
10118
10119    #[cfg(feature = "unstable_llm_providers")]
10120    #[test]
10121    fn test_provider_current_config_serialization() {
10122        let config =
10123            ProviderCurrentConfig::new(LlmProtocol::Anthropic, "https://api.anthropic.com");
10124
10125        let json = serde_json::to_value(&config).unwrap();
10126        assert_eq!(
10127            json,
10128            json!({
10129                "apiType": "anthropic",
10130                "baseUrl": "https://api.anthropic.com"
10131            })
10132        );
10133
10134        let deserialized: ProviderCurrentConfig = serde_json::from_value(json).unwrap();
10135        assert_eq!(deserialized.api_type, LlmProtocol::Anthropic);
10136        assert_eq!(deserialized.base_url, "https://api.anthropic.com");
10137    }
10138
10139    #[cfg(feature = "unstable_llm_providers")]
10140    #[test]
10141    fn test_provider_info_with_current_config() {
10142        let info = ProviderInfo::new(
10143            "main",
10144            vec![LlmProtocol::Anthropic, LlmProtocol::OpenAi],
10145            true,
10146            Some(ProviderCurrentConfig::new(
10147                LlmProtocol::Anthropic,
10148                "https://api.anthropic.com",
10149            )),
10150        );
10151
10152        let json = serde_json::to_value(&info).unwrap();
10153        assert_eq!(
10154            json,
10155            json!({
10156                "providerId": "main",
10157                "supported": ["anthropic", "openai"],
10158                "required": true,
10159                "current": {
10160                    "apiType": "anthropic",
10161                    "baseUrl": "https://api.anthropic.com"
10162                }
10163            })
10164        );
10165
10166        let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10167        assert_eq!(deserialized.provider_id.to_string(), "main");
10168        assert_eq!(deserialized.supported.len(), 2);
10169        assert!(deserialized.required);
10170        assert!(deserialized.current.is_some());
10171        assert_eq!(
10172            deserialized.current.as_ref().unwrap().api_type,
10173            LlmProtocol::Anthropic
10174        );
10175    }
10176
10177    #[cfg(feature = "unstable_llm_providers")]
10178    #[test]
10179    fn test_provider_info_disabled() {
10180        let info = ProviderInfo::new(
10181            "secondary",
10182            vec![LlmProtocol::OpenAi],
10183            false,
10184            None::<ProviderCurrentConfig>,
10185        );
10186
10187        let json = serde_json::to_value(&info).unwrap();
10188        assert_eq!(
10189            json,
10190            json!({
10191                "providerId": "secondary",
10192                "supported": ["openai"],
10193                "required": false
10194            })
10195        );
10196
10197        let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10198        assert_eq!(deserialized.provider_id.to_string(), "secondary");
10199        assert!(!deserialized.required);
10200        assert!(deserialized.current.is_none());
10201    }
10202
10203    #[cfg(feature = "unstable_llm_providers")]
10204    #[test]
10205    fn test_provider_info_missing_current_defaults_to_none() {
10206        // current is optional; omitting it should decode as None
10207        let json = json!({
10208            "providerId": "main",
10209            "supported": ["anthropic"],
10210            "required": true
10211        });
10212        let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10213        assert!(deserialized.current.is_none());
10214    }
10215
10216    #[cfg(feature = "unstable_llm_providers")]
10217    #[test]
10218    fn test_provider_info_explicit_null_current_decodes_to_none() {
10219        // current: null and an omitted current are equivalent on the wire;
10220        // both must deserialize into None so the disabled state is preserved
10221        // regardless of which form the peer chose to send.
10222        let json = json!({
10223            "providerId": "main",
10224            "supported": ["anthropic"],
10225            "required": true,
10226            "current": null
10227        });
10228        let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10229        assert!(deserialized.current.is_none());
10230    }
10231
10232    #[cfg(feature = "unstable_llm_providers")]
10233    #[test]
10234    fn test_list_providers_response_serialization() {
10235        let response = ListProvidersResponse::new(vec![ProviderInfo::new(
10236            "main",
10237            vec![LlmProtocol::Anthropic],
10238            true,
10239            Some(ProviderCurrentConfig::new(
10240                LlmProtocol::Anthropic,
10241                "https://api.anthropic.com",
10242            )),
10243        )]);
10244
10245        let json = serde_json::to_value(&response).unwrap();
10246        assert_eq!(json["providers"].as_array().unwrap().len(), 1);
10247        assert_eq!(json["providers"][0]["providerId"], "main");
10248
10249        let deserialized: ListProvidersResponse = serde_json::from_value(json).unwrap();
10250        assert_eq!(deserialized.providers.len(), 1);
10251    }
10252
10253    #[cfg(feature = "unstable_llm_providers")]
10254    #[test]
10255    fn test_set_provider_request_serialization() {
10256        use std::collections::HashMap;
10257
10258        let mut headers = HashMap::new();
10259        headers.insert("Authorization".to_string(), "Bearer sk-test".to_string());
10260
10261        let request =
10262            SetProviderRequest::new("main", LlmProtocol::OpenAi, "https://api.openai.com/v1")
10263                .headers(headers);
10264
10265        let json = serde_json::to_value(&request).unwrap();
10266        assert_eq!(
10267            json,
10268            json!({
10269                "providerId": "main",
10270                "apiType": "openai",
10271                "baseUrl": "https://api.openai.com/v1",
10272                "headers": {
10273                    "Authorization": "Bearer sk-test"
10274                }
10275            })
10276        );
10277
10278        let deserialized: SetProviderRequest = serde_json::from_value(json).unwrap();
10279        assert_eq!(deserialized.provider_id.to_string(), "main");
10280        assert_eq!(deserialized.api_type, LlmProtocol::OpenAi);
10281        assert_eq!(deserialized.base_url, "https://api.openai.com/v1");
10282        assert_eq!(deserialized.headers.len(), 1);
10283        assert_eq!(
10284            deserialized.headers.get("Authorization").unwrap(),
10285            "Bearer sk-test"
10286        );
10287    }
10288
10289    #[cfg(feature = "unstable_llm_providers")]
10290    #[test]
10291    fn test_set_provider_request_omits_empty_headers() {
10292        let request =
10293            SetProviderRequest::new("main", LlmProtocol::Anthropic, "https://api.anthropic.com");
10294
10295        let json = serde_json::to_value(&request).unwrap();
10296        // headers should be omitted when empty
10297        assert!(!json.as_object().unwrap().contains_key("headers"));
10298    }
10299
10300    #[cfg(feature = "unstable_llm_providers")]
10301    #[test]
10302    fn test_disable_provider_request_serialization() {
10303        let request = DisableProviderRequest::new("secondary");
10304
10305        let json = serde_json::to_value(&request).unwrap();
10306        assert_eq!(json, json!({ "providerId": "secondary" }));
10307
10308        let deserialized: DisableProviderRequest = serde_json::from_value(json).unwrap();
10309        assert_eq!(deserialized.provider_id.to_string(), "secondary");
10310    }
10311
10312    #[cfg(feature = "unstable_llm_providers")]
10313    #[test]
10314    fn test_providers_capabilities_serialization() {
10315        let caps = ProvidersCapabilities::new();
10316
10317        let json = serde_json::to_value(&caps).unwrap();
10318        assert_eq!(json, json!({}));
10319
10320        let deserialized: ProvidersCapabilities = serde_json::from_value(json).unwrap();
10321        assert!(deserialized.meta.is_none());
10322    }
10323
10324    #[cfg(feature = "unstable_llm_providers")]
10325    #[test]
10326    fn test_agent_capabilities_with_providers() {
10327        let caps = AgentCapabilities::new().providers(ProvidersCapabilities::new());
10328
10329        let json = serde_json::to_value(&caps).unwrap();
10330        assert_eq!(json["providers"], json!({}));
10331
10332        let deserialized: AgentCapabilities = serde_json::from_value(json).unwrap();
10333        assert!(deserialized.providers.is_some());
10334    }
10335
10336    #[test]
10337    fn test_agent_capabilities_session_is_explicit() {
10338        let json = serde_json::to_value(AgentCapabilities::new()).unwrap();
10339        assert!(json.get("session").is_none());
10340
10341        let caps = AgentCapabilities::new().session(
10342            SessionCapabilities::new()
10343                .prompt(PromptCapabilities::new().image(PromptImageCapabilities::new()))
10344                .mcp(McpCapabilities::new().stdio(McpStdioCapabilities::new())),
10345        );
10346
10347        assert_eq!(
10348            serde_json::to_value(&caps).unwrap(),
10349            json!({
10350                "session": {
10351                    "prompt": {
10352                        "image": {}
10353                    },
10354                    "mcp": {
10355                        "stdio": {}
10356                    }
10357                }
10358            })
10359        );
10360
10361        let deserialized: AgentCapabilities = serde_json::from_value(json!({
10362            "session": false
10363        }))
10364        .unwrap();
10365        assert!(deserialized.session.is_none());
10366    }
10367
10368    #[test]
10369    fn test_prompt_capabilities_serialize_supported_content_as_objects() {
10370        let caps = PromptCapabilities::new()
10371            .image(PromptImageCapabilities::new())
10372            .audio(PromptAudioCapabilities::new())
10373            .embedded_context(PromptEmbeddedContextCapabilities::new());
10374
10375        assert_eq!(
10376            serde_json::to_value(&caps).unwrap(),
10377            json!({
10378                "image": {},
10379                "audio": {},
10380                "embeddedContext": {}
10381            })
10382        );
10383
10384        let deserialized: PromptCapabilities = serde_json::from_value(json!({
10385            "image": null,
10386            "audio": false,
10387            "embeddedContext": {}
10388        }))
10389        .unwrap();
10390        assert!(deserialized.image.is_none());
10391        assert!(deserialized.audio.is_none());
10392        assert!(deserialized.embedded_context.is_some());
10393    }
10394
10395    #[cfg(feature = "unstable_agent_skills")]
10396    #[test]
10397    fn prompt_skill_capability_has_two_levels() {
10398        // `{}` allows one leading skill block. `inline` allows them anywhere.
10399        let leading = PromptCapabilities::new().skill(PromptSkillCapabilities::new());
10400        assert_eq!(
10401            serde_json::to_value(&leading).unwrap(),
10402            json!({ "skill": {} })
10403        );
10404
10405        let inline = PromptCapabilities::new()
10406            .skill(PromptSkillCapabilities::new().inline(PromptSkillInlineCapabilities::new()));
10407        let wire = json!({ "skill": { "inline": {} } });
10408        assert_eq!(serde_json::to_value(&inline).unwrap(), wire);
10409        assert_eq!(
10410            serde_json::from_value::<PromptCapabilities>(wire).unwrap(),
10411            inline
10412        );
10413
10414        for unsupported in [
10415            json!({}),
10416            json!({ "skill": null }),
10417            json!({ "skill": false }),
10418            json!({ "skill": true }),
10419        ] {
10420            let caps: PromptCapabilities = serde_json::from_value(unsupported).unwrap();
10421            assert!(caps.skill.is_none());
10422        }
10423
10424        // A malformed `inline` does not withdraw the first level.
10425        for leading_only in [
10426            json!({ "skill": { "inline": null } }),
10427            json!({ "skill": { "inline": true } }),
10428        ] {
10429            assert_eq!(
10430                serde_json::from_value::<PromptCapabilities>(leading_only).unwrap(),
10431                leading
10432            );
10433        }
10434    }
10435
10436    #[test]
10437    fn test_mcp_capabilities_serialize_supported_transports_as_objects() {
10438        let caps = McpCapabilities::new()
10439            .stdio(McpStdioCapabilities::new())
10440            .http(McpHttpCapabilities::new());
10441
10442        assert_eq!(
10443            serde_json::to_value(&caps).unwrap(),
10444            json!({
10445                "stdio": {},
10446                "http": {}
10447            })
10448        );
10449
10450        let deserialized: McpCapabilities = serde_json::from_value(json!({
10451            "stdio": null,
10452            "http": false
10453        }))
10454        .unwrap();
10455        assert!(deserialized.stdio.is_none());
10456        assert!(deserialized.http.is_none());
10457    }
10458
10459    #[cfg(feature = "unstable_mcp_over_acp")]
10460    #[test]
10461    fn test_mcp_capabilities_serialize_acp_support_as_object() {
10462        let caps = McpCapabilities::new().acp(McpAcpCapabilities::new());
10463
10464        assert_eq!(
10465            serde_json::to_value(&caps).unwrap(),
10466            json!({
10467                "acp": {}
10468            })
10469        );
10470    }
10471
10472    #[test]
10473    fn prompt_request_rejects_malformed_content_block() {
10474        use serde_json::json;
10475
10476        assert!(
10477            serde_json::from_value::<PromptRequest>(json!({
10478                "sessionId": "sess-1",
10479                "prompt": [{"type": "text"}]
10480            }))
10481            .is_err()
10482        );
10483    }
10484
10485    #[test]
10486    fn prompt_request_rejects_non_array_prompt() {
10487        use serde_json::json;
10488
10489        assert!(
10490            serde_json::from_value::<PromptRequest>(json!({
10491                "sessionId": "sess-1",
10492                "prompt": "hello"
10493            }))
10494            .is_err()
10495        );
10496    }
10497
10498    fn assert_session_setup_lists_are_strict<T>(base: &serde_json::Value)
10499    where
10500        T: serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
10501    {
10502        let name = std::any::type_name::<T>();
10503        let with = |field: &str, value: serde_json::Value| {
10504            let mut request = base.clone();
10505            request[field] = value;
10506            serde_json::from_value::<T>(request)
10507        };
10508
10509        for (field, value) in [
10510            // Dropping the malformed server would start the session without it.
10511            (
10512                "mcpServers",
10513                json!([
10514                    {"type": "stdio", "name": "github", "command": "/usr/bin/gh-mcp", "env": [{"name": "GITHUB_TOKEN", "value": null}]},
10515                    {"type": "stdio", "name": "fs", "command": "/usr/bin/fs-mcp"}
10516                ]),
10517            ),
10518            ("mcpServers", json!({"type": "stdio", "name": "fs"})),
10519            ("additionalDirectories", json!(["/repo/lib", 42])),
10520            ("additionalDirectories", json!("/repo/lib")),
10521        ] {
10522            assert!(
10523                with(field, value.clone()).is_err(),
10524                "{name}.{field}: {value}"
10525            );
10526        }
10527
10528        let empty = serde_json::from_value::<T>(base.clone()).unwrap();
10529        for field in ["mcpServers", "additionalDirectories"] {
10530            assert_eq!(
10531                with(field, serde_json::Value::Null).unwrap(),
10532                empty,
10533                "{name}.{field}"
10534            );
10535        }
10536    }
10537
10538    #[test]
10539    fn session_setup_requests_reject_malformed_mcp_servers_and_directories() {
10540        assert_session_setup_lists_are_strict::<NewSessionRequest>(&json!({"cwd": "/repo"}));
10541        assert_session_setup_lists_are_strict::<ResumeSessionRequest>(&json!({
10542            "sessionId": "sess-1",
10543            "cwd": "/repo"
10544        }));
10545        #[cfg(feature = "unstable_session_fork")]
10546        assert_session_setup_lists_are_strict::<ForkSessionRequest>(&json!({
10547            "sessionId": "sess-1",
10548            "cwd": "/repo"
10549        }));
10550    }
10551
10552    #[test]
10553    fn resume_session_request_rejects_malformed_replay_from() {
10554        let request = |replay_from: serde_json::Value| {
10555            serde_json::from_value::<ResumeSessionRequest>(json!({
10556                "sessionId": "sess-1",
10557                "cwd": "/repo",
10558                "replayFrom": replay_from
10559            }))
10560        };
10561
10562        // Treating this as omitted would reconnect without the requested replay.
10563        assert!(request(json!("start")).is_err());
10564        assert_eq!(request(serde_json::Value::Null).unwrap().replay_from, None);
10565        assert!(matches!(
10566            request(json!({"type": "start"})).unwrap().replay_from,
10567            Some(ReplayFrom::Start(_))
10568        ));
10569    }
10570
10571    #[test]
10572    fn mcp_server_lists_treat_null_as_empty() {
10573        let servers: Vec<McpServer> = serde_json::from_value(json!([
10574            {"type": "stdio", "name": "fs", "command": "/usr/bin/fs-mcp", "args": null, "env": null},
10575            {"type": "http", "name": "api", "url": "https://example.com/mcp", "headers": null}
10576        ]))
10577        .unwrap();
10578
10579        assert_eq!(
10580            servers,
10581            vec![
10582                McpServer::Stdio(McpServerStdio::new("fs", "/usr/bin/fs-mcp")),
10583                McpServer::Http(McpServerHttp::new("api", "https://example.com/mcp")),
10584            ]
10585        );
10586    }
10587
10588    #[test]
10589    fn terminal_auth_methods_reject_malformed_launch_config() {
10590        // The client spawns a process from `args` and `env`, so a malformed
10591        // method is dropped from `authMethods` instead of launched with
10592        // altered arguments or preserved as an unknown method.
10593        let response: InitializeResponse = serde_json::from_value(json!({
10594            "protocolVersion": 2,
10595            "info": {"name": "agent", "version": "1.0.0"},
10596            "authMethods": [
10597                {"type": "terminal", "methodId": "bad-args", "name": "Log in", "args": ["auth", "--port", 8123]},
10598                {"type": "terminal", "methodId": "bad-env", "name": "Log in", "env": [{"name": "DEBUG", "value": 1}]},
10599                {"type": "terminal", "methodId": "null-config", "name": "Log in", "args": null, "env": null},
10600                {"type": "agent", "methodId": "agent", "name": "Agent login"}
10601            ]
10602        }))
10603        .unwrap();
10604
10605        assert_eq!(
10606            response.auth_methods,
10607            vec![
10608                AuthMethod::Terminal(AuthMethodTerminal::new("null-config", "Log in")),
10609                AuthMethod::Agent(AuthMethodAgent::new("agent", "Agent login")),
10610            ]
10611        );
10612    }
10613
10614    #[cfg(feature = "unstable_auth_status")]
10615    #[test]
10616    fn auth_status_response_round_trips() {
10617        let response = AuthStatusResponse::new(AuthState::Authenticated).accounts(vec![
10618            AuthAccount::new("Anthropic API key")
10619                .description("API key helper".to_string())
10620                .active(true),
10621            AuthAccount::new("Claude Max").email("user@example.com".to_string()),
10622        ]);
10623        let json = serde_json::to_value(&response).unwrap();
10624        assert_eq!(
10625            json,
10626            json!({
10627                "state": "authenticated",
10628                "accounts": [
10629                    {
10630                        "label": "Anthropic API key",
10631                        "description": "API key helper",
10632                        "active": true
10633                    },
10634                    {
10635                        "label": "Claude Max",
10636                        "email": "user@example.com"
10637                    }
10638                ]
10639            })
10640        );
10641        assert_eq!(
10642            serde_json::from_value::<AuthStatusResponse>(json).unwrap(),
10643            response
10644        );
10645        assert_eq!(
10646            serde_json::to_value(AuthStatusResponse::new(AuthState::NotRequired)).unwrap(),
10647            json!({"state": "not_required"})
10648        );
10649    }
10650
10651    #[cfg(feature = "unstable_auth_status")]
10652    #[test]
10653    fn auth_status_state_is_strict_and_accounts_are_lenient() {
10654        assert!(serde_json::from_value::<AuthStatusResponse>(json!({})).is_err());
10655        assert!(serde_json::from_value::<AuthStatusResponse>(json!({"state": null})).is_err());
10656        assert!(serde_json::from_value::<AuthStatusResponse>(json!({"state": 1})).is_err());
10657
10658        let response: AuthStatusResponse = serde_json::from_value(json!({
10659            "state": "_vendor_state",
10660            "accounts": [
10661                {"active": true},
10662                {
10663                    "label": "Vertex AI",
10664                    "description": 42,
10665                    "active": "yes",
10666                    "email": ["not", "a", "string"]
10667                }
10668            ]
10669        }))
10670        .unwrap();
10671        assert_eq!(
10672            response,
10673            AuthStatusResponse::new(AuthState::Other("_vendor_state".to_string()))
10674                .accounts(vec![AuthAccount::new("Vertex AI")])
10675        );
10676        assert_eq!(
10677            serde_json::from_value::<AuthStatusResponse>(
10678                json!({"state": "unknown", "accounts": null})
10679            )
10680            .unwrap(),
10681            AuthStatusResponse::new(AuthState::Unknown)
10682        );
10683    }
10684
10685    #[cfg(feature = "unstable_auth_status")]
10686    #[test]
10687    fn auth_status_update_notification_routes() {
10688        use crate::v2::{AgentNotification, CLIENT_METHOD_NAMES};
10689
10690        assert_eq!(AGENT_METHOD_NAMES.auth_status, "auth/status");
10691        assert_eq!(CLIENT_METHOD_NAMES.auth_status_update, "auth/status_update");
10692        let notification = AgentNotification::AuthStatusUpdateNotification(Box::new(
10693            AuthStatusUpdateNotification::new(AuthState::Unauthenticated),
10694        ));
10695        assert_eq!(notification.method(), "auth/status_update");
10696        assert_eq!(
10697            serde_json::to_value(&notification).unwrap(),
10698            json!({"state": "unauthenticated"})
10699        );
10700    }
10701}