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(all(
24    feature = "unstable_session_fork",
25    feature = "unstable_session_cursors"
26))]
27use super::CursorId;
28#[cfg(feature = "unstable_session_status")]
29use super::StateUpdate;
30
31#[cfg(all(feature = "unstable_auth_status", feature = "schemars"))]
32use super::AUTH_STATUS_UPDATE_NOTIFICATION;
33#[cfg(feature = "unstable_mcp_over_acp")]
34use super::mcp::{MCP_MESSAGE_METHOD_NAME, MessageMcpNotification};
35
36// Initialize
37
38/// Request parameters for the initialize method.
39///
40/// Sent by the client to establish connection and negotiate capabilities.
41///
42/// See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/v2/initialization)
43#[serde_as]
44#[skip_serializing_none]
45#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
46#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
47#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = INITIALIZE_METHOD_NAME)))]
48#[serde(rename_all = "camelCase")]
49#[non_exhaustive]
50pub struct InitializeRequest {
51    /// The latest protocol version supported by the client.
52    pub protocol_version: ProtocolVersion,
53    /// Information about the implementation sending this initialize request.
54    pub info: Implementation,
55    /// Capabilities supported by the client.
56    #[serde_as(deserialize_as = "DefaultOnError")]
57    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
58    #[serde(default)]
59    pub capabilities: ClientCapabilities,
60    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
61    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
62    /// Implementations MUST NOT assign meaning to keys they do not recognize.
63    ///
64    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
65    #[serde_as(deserialize_as = "DefaultOnError")]
66    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
67    #[serde(default)]
68    #[serde(rename = "_meta")]
69    pub meta: Option<Meta>,
70}
71
72impl InitializeRequest {
73    /// Builds [`InitializeRequest`] with the required request fields set. Optional fields start unset or empty.
74    #[must_use]
75    pub fn new(protocol_version: ProtocolVersion, info: Implementation) -> Self {
76        Self {
77            protocol_version,
78            capabilities: ClientCapabilities::default(),
79            info,
80            meta: None,
81        }
82    }
83
84    /// Capabilities supported by the client.
85    #[must_use]
86    pub fn capabilities(mut self, capabilities: ClientCapabilities) -> Self {
87        self.capabilities = capabilities;
88        self
89    }
90
91    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
92    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
93    /// do not recognize.
94    ///
95    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
96    #[must_use]
97    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
98        self.meta = meta.into_option();
99        self
100    }
101}
102
103/// Response to the `initialize` method.
104///
105/// Contains the negotiated protocol version and agent capabilities.
106///
107/// See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/v2/initialization)
108#[serde_as]
109#[skip_serializing_none]
110#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
111#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
112#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = INITIALIZE_METHOD_NAME)))]
113#[serde(rename_all = "camelCase")]
114#[non_exhaustive]
115pub struct InitializeResponse {
116    /// The highest protocol version supported by the agent that is at or below
117    /// the version requested by the client. If no such version exists,
118    /// initialization fails with error code -32022.
119    ///
120    /// The client must check that it supports this version and should disconnect
121    /// if it does not.
122    pub protocol_version: ProtocolVersion,
123    /// Information about the implementation sending this initialize response.
124    pub info: Implementation,
125    /// Capabilities supported by the agent.
126    #[serde_as(deserialize_as = "DefaultOnError")]
127    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
128    #[serde(default)]
129    pub capabilities: AgentCapabilities,
130    /// Authentication methods supported by the agent.
131    ///
132    /// Optional. Omitted or empty means the agent does not advertise the
133    /// `auth/login` and `auth/logout` methods. Supplying one or more methods means
134    /// the agent MUST support both `auth/login` and `auth/logout`.
135    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
136    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
137    #[serde(default, skip_serializing_if = "Vec::is_empty")]
138    pub auth_methods: Vec<AuthMethod>,
139    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
140    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
141    /// Implementations MUST NOT assign meaning to keys they do not recognize.
142    ///
143    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
144    #[serde_as(deserialize_as = "DefaultOnError")]
145    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
146    #[serde(default)]
147    #[serde(rename = "_meta")]
148    pub meta: Option<Meta>,
149}
150
151impl InitializeResponse {
152    /// Builds [`InitializeResponse`] with the required response fields set. Optional fields start unset or empty.
153    #[must_use]
154    pub fn new(protocol_version: ProtocolVersion, info: Implementation) -> Self {
155        Self {
156            protocol_version,
157            capabilities: AgentCapabilities::default(),
158            auth_methods: vec![],
159            info,
160            meta: None,
161        }
162    }
163
164    /// Capabilities supported by the agent.
165    #[must_use]
166    pub fn capabilities(mut self, capabilities: AgentCapabilities) -> Self {
167        self.capabilities = capabilities;
168        self
169    }
170
171    /// Authentication methods supported by the agent.
172    ///
173    /// Supplying one or more methods means the agent MUST support both
174    /// `auth/login` and `auth/logout`.
175    #[must_use]
176    pub fn auth_methods(mut self, auth_methods: Vec<AuthMethod>) -> Self {
177        self.auth_methods = auth_methods;
178        self
179    }
180
181    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
182    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
183    /// do not recognize.
184    ///
185    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
186    #[must_use]
187    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
188        self.meta = meta.into_option();
189        self
190    }
191}
192
193/// Metadata about the implementation of the client or agent.
194/// Describes the name and version of an ACP implementation, with an optional
195/// title for UI representation.
196#[serde_as]
197#[skip_serializing_none]
198#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
199#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
200#[serde(rename_all = "camelCase")]
201#[non_exhaustive]
202pub struct Implementation {
203    /// Intended for programmatic or logical use, but can be used as a display
204    /// name fallback if title isn't present.
205    pub name: String,
206    /// Intended for UI and end-user contexts and optimized to be human-readable
207    /// and easily understood.
208    ///
209    /// If not provided, the name should be used for display.
210    ///
211    /// Omitted and `null` are equivalent and mean the `name` is used for display.
212    #[serde_as(deserialize_as = "DefaultOnError")]
213    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
214    #[serde(default)]
215    pub title: Option<String>,
216    /// Version of the implementation. Can be displayed to the user or used
217    /// for debugging or metrics purposes. (e.g. "1.0.0").
218    pub version: String,
219    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
220    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
221    /// Implementations MUST NOT assign meaning to keys they do not recognize.
222    ///
223    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
224    #[serde_as(deserialize_as = "DefaultOnError")]
225    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
226    #[serde(default)]
227    #[serde(rename = "_meta")]
228    pub meta: Option<Meta>,
229}
230
231impl Implementation {
232    /// Builds [`Implementation`] with the required fields set. Optional fields start unset or empty.
233    #[must_use]
234    pub fn new(name: impl Into<String>, version: impl Into<String>) -> Self {
235        Self {
236            name: name.into(),
237            title: None,
238            version: version.into(),
239            meta: None,
240        }
241    }
242
243    /// Intended for UI and end-user contexts and optimized to be human-readable
244    /// and easily understood.
245    ///
246    /// If not provided, the name should be used for display.
247    #[must_use]
248    pub fn title(mut self, title: impl IntoOption<String>) -> Self {
249        self.title = title.into_option();
250        self
251    }
252
253    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
254    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
255    /// do not recognize.
256    ///
257    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
258    #[must_use]
259    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
260        self.meta = meta.into_option();
261        self
262    }
263}
264
265// Authentication
266
267/// Request parameters for the `auth/login` method.
268///
269/// Specifies which authentication method to use.
270///
271/// Agents MUST support this method when their `initialize` response included
272/// a non-empty `authMethods` list. Clients MUST NOT call this method
273/// when `authMethods` was omitted or empty.
274#[serde_as]
275#[skip_serializing_none]
276#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
277#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
278#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGIN_METHOD_NAME)))]
279#[serde(rename_all = "camelCase")]
280#[non_exhaustive]
281pub struct LoginAuthRequest {
282    /// The ID of the authentication method to use.
283    /// Must be one of the methods advertised in the initialize response.
284    pub method_id: AuthMethodId,
285    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
286    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
287    /// Implementations MUST NOT assign meaning to keys they do not recognize.
288    ///
289    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
290    #[serde_as(deserialize_as = "DefaultOnError")]
291    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
292    #[serde(default)]
293    #[serde(rename = "_meta")]
294    pub meta: Option<Meta>,
295}
296
297impl LoginAuthRequest {
298    /// Builds [`LoginAuthRequest`] with the required request fields set. Optional fields start unset or empty.
299    #[must_use]
300    pub fn new(method_id: impl Into<AuthMethodId>) -> Self {
301        Self {
302            method_id: method_id.into(),
303            meta: None,
304        }
305    }
306
307    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
308    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
309    /// do not recognize.
310    ///
311    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
312    #[must_use]
313    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
314        self.meta = meta.into_option();
315        self
316    }
317}
318
319crate::serde_util::default_on_null! {
320    /// Response to the `auth/login` method.
321    #[serde_as]
322    #[skip_serializing_none]
323    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
324    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
325    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGIN_METHOD_NAME)))]
326    #[serde(rename_all = "camelCase")]
327    #[non_exhaustive]
328    pub struct LoginAuthResponse {
329        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
330        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
331        /// Implementations MUST NOT assign meaning to keys they do not recognize.
332        ///
333        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
334        #[serde_as(deserialize_as = "DefaultOnError")]
335        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
336        #[serde(default)]
337        #[serde(rename = "_meta")]
338        pub meta: Option<Meta>,
339    }
340}
341
342impl LoginAuthResponse {
343    /// Builds [`LoginAuthResponse`] with the required response fields set. Optional fields start unset or empty.
344    #[must_use]
345    pub fn new() -> Self {
346        Self::default()
347    }
348
349    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
350    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
351    /// do not recognize.
352    ///
353    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
354    #[must_use]
355    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
356        self.meta = meta.into_option();
357        self
358    }
359}
360
361// Logout
362
363crate::serde_util::default_on_null! {
364    /// Request parameters for the `auth/logout` method.
365    ///
366    /// Terminates the current authenticated session.
367    ///
368    /// Agents MUST support this method when their `initialize` response included
369    /// a non-empty `authMethods` list. Clients MUST NOT call this method
370    /// when `authMethods` was omitted or empty.
371    #[serde_as]
372    #[skip_serializing_none]
373    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
374    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
375    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGOUT_METHOD_NAME)))]
376    #[serde(rename_all = "camelCase")]
377    #[non_exhaustive]
378    pub struct LogoutAuthRequest {
379        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
380        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
381        /// Implementations MUST NOT assign meaning to keys they do not recognize.
382        ///
383        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
384        #[serde_as(deserialize_as = "DefaultOnError")]
385        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
386        #[serde(default)]
387        #[serde(rename = "_meta")]
388        pub meta: Option<Meta>,
389    }
390}
391
392impl LogoutAuthRequest {
393    /// Builds [`LogoutAuthRequest`] with the required request fields set. Optional fields start unset or empty.
394    #[must_use]
395    pub fn new() -> Self {
396        Self::default()
397    }
398
399    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
400    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
401    /// do not recognize.
402    ///
403    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
404    #[must_use]
405    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
406        self.meta = meta.into_option();
407        self
408    }
409}
410
411crate::serde_util::default_on_null! {
412    /// Response to the `auth/logout` method.
413    #[serde_as]
414    #[skip_serializing_none]
415    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
416    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
417    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGOUT_METHOD_NAME)))]
418    #[serde(rename_all = "camelCase")]
419    #[non_exhaustive]
420    pub struct LogoutAuthResponse {
421        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
422        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
423        /// Implementations MUST NOT assign meaning to keys they do not recognize.
424        ///
425        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
426        #[serde_as(deserialize_as = "DefaultOnError")]
427        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
428        #[serde(default)]
429        #[serde(rename = "_meta")]
430        pub meta: Option<Meta>,
431    }
432}
433
434impl LogoutAuthResponse {
435    /// Builds [`LogoutAuthResponse`] with the required response fields set. Optional fields start unset or empty.
436    #[must_use]
437    pub fn new() -> Self {
438        Self::default()
439    }
440
441    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
442    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
443    /// do not recognize.
444    ///
445    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
446    #[must_use]
447    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
448        self.meta = meta.into_option();
449        self
450    }
451}
452
453// Auth status
454
455#[cfg(feature = "unstable_auth_status")]
456crate::serde_util::default_on_null! {
457    /// **UNSTABLE**
458    ///
459    /// This capability is not part of the spec yet, and may be removed or changed at any point.
460    ///
461    /// Request parameters for the `auth/status` method.
462    ///
463    /// Queries the agent's current authentication state without changing it.
464    ///
465    /// Agents MUST NOT reject it with `auth_required` (`-32000`), since Clients call it to learn
466    /// whether authentication is required.
467    #[serde_as]
468    #[skip_serializing_none]
469    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
470    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
471    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_STATUS_METHOD_NAME)))]
472    #[serde(rename_all = "camelCase")]
473    #[non_exhaustive]
474    pub struct AuthStatusRequest {
475        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
476        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
477        /// Implementations MUST NOT assign meaning to keys they do not recognize.
478        ///
479        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
480        #[serde_as(deserialize_as = "DefaultOnError")]
481        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
482        #[serde(default)]
483        #[serde(rename = "_meta")]
484        pub meta: Option<Meta>,
485    }
486}
487
488#[cfg(feature = "unstable_auth_status")]
489impl AuthStatusRequest {
490    /// Builds [`AuthStatusRequest`] with the required request fields set. Optional fields start unset or empty.
491    #[must_use]
492    pub fn new() -> Self {
493        Self::default()
494    }
495
496    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
497    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
498    /// do not recognize.
499    ///
500    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
501    #[must_use]
502    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
503        self.meta = meta.into_option();
504        self
505    }
506}
507
508/// **UNSTABLE**
509///
510/// This capability is not part of the spec yet, and may be removed or changed at any point.
511///
512/// Response to the `auth/status` method.
513#[cfg(feature = "unstable_auth_status")]
514#[serde_as]
515#[skip_serializing_none]
516#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
517#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
518#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_STATUS_METHOD_NAME)))]
519#[serde(rename_all = "camelCase")]
520#[non_exhaustive]
521pub struct AuthStatusResponse {
522    /// Whether the agent can start sessions without the user signing in first.
523    ///
524    /// Clients use this field to decide whether sign-in is needed. Clients MUST treat
525    /// values they do not recognize as `unknown`.
526    pub state: AuthState,
527    /// The accounts the agent has configured, for display.
528    ///
529    /// Optional. Omitted and empty are equivalent and mean no accounts are reported.
530    /// Agents that hold credentials for several providers or accounts SHOULD list each
531    /// of them and mark the ones in effect with `active`.
532    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
533    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
534    #[serde(default, skip_serializing_if = "Vec::is_empty")]
535    pub accounts: Vec<AuthAccount>,
536    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
537    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
538    /// Implementations MUST NOT assign meaning to keys they do not recognize.
539    ///
540    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
541    #[serde_as(deserialize_as = "DefaultOnError")]
542    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
543    #[serde(default)]
544    #[serde(rename = "_meta")]
545    pub meta: Option<Meta>,
546}
547
548#[cfg(feature = "unstable_auth_status")]
549impl AuthStatusResponse {
550    /// Builds [`AuthStatusResponse`] with the required fields set. Optional fields start unset or empty.
551    #[must_use]
552    pub fn new(state: AuthState) -> Self {
553        Self {
554            state,
555            accounts: vec![],
556            meta: None,
557        }
558    }
559
560    /// The accounts the agent has configured, for display.
561    #[must_use]
562    pub fn accounts(mut self, accounts: Vec<AuthAccount>) -> Self {
563        self.accounts = accounts;
564        self
565    }
566
567    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
568    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
569    /// do not recognize.
570    ///
571    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
572    #[must_use]
573    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
574        self.meta = meta.into_option();
575        self
576    }
577}
578
579/// **UNSTABLE**
580///
581/// This capability is not part of the spec yet, and may be removed or changed at any point.
582///
583/// Notification sent by the agent when its authentication status changes.
584///
585/// Carries the same fields as the `auth/status` response. Agents that advertise the
586/// `auth.status` capability MAY send it at any time after `initialize`, and SHOULD only
587/// send it when the reported status differs from the last one sent on the connection.
588#[cfg(feature = "unstable_auth_status")]
589#[serde_as]
590#[skip_serializing_none]
591#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
592#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
593#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = AUTH_STATUS_UPDATE_NOTIFICATION)))]
594#[serde(rename_all = "camelCase")]
595#[non_exhaustive]
596pub struct AuthStatusUpdateNotification {
597    /// Whether the agent can start sessions without the user signing in first.
598    ///
599    /// Clients use this field to decide whether sign-in is needed. Clients MUST treat
600    /// values they do not recognize as `unknown`.
601    pub state: AuthState,
602    /// The accounts the agent has configured, for display.
603    ///
604    /// Optional. Omitted and empty are equivalent and mean no accounts are reported.
605    /// Agents that hold credentials for several providers or accounts SHOULD list each
606    /// of them and mark the ones in effect with `active`.
607    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
608    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
609    #[serde(default, skip_serializing_if = "Vec::is_empty")]
610    pub accounts: Vec<AuthAccount>,
611    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
612    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
613    /// Implementations MUST NOT assign meaning to keys they do not recognize.
614    ///
615    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
616    #[serde_as(deserialize_as = "DefaultOnError")]
617    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
618    #[serde(default)]
619    #[serde(rename = "_meta")]
620    pub meta: Option<Meta>,
621}
622
623#[cfg(feature = "unstable_auth_status")]
624impl AuthStatusUpdateNotification {
625    /// Builds [`AuthStatusUpdateNotification`] with the required fields set. Optional fields start unset or empty.
626    #[must_use]
627    pub fn new(state: AuthState) -> Self {
628        Self {
629            state,
630            accounts: vec![],
631            meta: None,
632        }
633    }
634
635    /// The accounts the agent has configured, for display.
636    #[must_use]
637    pub fn accounts(mut self, accounts: Vec<AuthAccount>) -> Self {
638        self.accounts = accounts;
639        self
640    }
641
642    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
643    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
644    /// do not recognize.
645    ///
646    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
647    #[must_use]
648    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
649        self.meta = meta.into_option();
650        self
651    }
652}
653
654/// **UNSTABLE**
655///
656/// This capability is not part of the spec yet, and may be removed or changed at any point.
657///
658/// The agent's overall authentication state.
659#[cfg(feature = "unstable_auth_status")]
660#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
661#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
662#[serde(rename_all = "snake_case")]
663#[non_exhaustive]
664pub enum AuthState {
665    /// Credentials are configured. This does not guarantee that they are valid.
666    Authenticated,
667    /// The user needs to sign in. This includes credentials that are missing,
668    /// expired, or known to be invalid.
669    Unauthenticated,
670    /// No authentication is needed, for example because the agent uses a local model.
671    NotRequired,
672    /// The agent cannot currently determine the state.
673    Unknown,
674    /// Custom or future authentication state.
675    ///
676    /// Values beginning with `_` are reserved for implementation-specific
677    /// extensions. Unknown values that do not begin with `_` are reserved for
678    /// future ACP variants.
679    #[serde(untagged)]
680    Other(String),
681}
682
683/// **UNSTABLE**
684///
685/// This capability is not part of the spec yet, and may be removed or changed at any point.
686///
687/// An account or credential the agent has configured, such as a signed-in user
688/// account or an API key.
689///
690/// All fields are display information only. Clients MUST NOT use them as stable
691/// account identifiers, and SHOULD NOT log them or send them elsewhere, such as to
692/// telemetry.
693#[cfg(feature = "unstable_auth_status")]
694#[serde_as]
695#[skip_serializing_none]
696#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
697#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
698#[serde(rename_all = "camelCase")]
699#[non_exhaustive]
700pub struct AuthAccount {
701    /// Human-readable name for the account, suitable for display on its own,
702    /// for example `Claude Max`, `OpenAI API key`, or `Vertex AI`.
703    pub label: String,
704    /// Short text shown with the label, such as the credential source, for example
705    /// `API key helper`. MUST NOT contain credentials.
706    ///
707    /// Optional. Omitted and `null` are equivalent and mean no description is reported.
708    #[serde_as(deserialize_as = "DefaultOnError")]
709    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
710    #[serde(default)]
711    pub description: Option<String>,
712    /// Whether the agent currently uses this account by default.
713    ///
714    /// Several accounts MAY be active, for example one per provider.
715    ///
716    /// Optional. Omitted and `null` are equivalent and mean the agent does not indicate whether this account is in effect.
717    #[serde_as(deserialize_as = "DefaultOnError")]
718    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
719    #[serde(default)]
720    pub active: Option<bool>,
721    /// Display name of the user, such as a username or full name.
722    ///
723    /// Optional. Omitted and `null` are equivalent and mean no name is reported.
724    #[serde_as(deserialize_as = "DefaultOnError")]
725    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
726    #[serde(default)]
727    pub name: Option<String>,
728    /// Email address of the user.
729    ///
730    /// Optional. Omitted and `null` are equivalent and mean no email is reported.
731    #[serde_as(deserialize_as = "DefaultOnError")]
732    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
733    #[serde(default)]
734    pub email: Option<String>,
735    /// Display name of the organization, team, or workspace the account is using.
736    ///
737    /// Optional. Omitted and `null` are equivalent and mean no organization is reported.
738    #[serde_as(deserialize_as = "DefaultOnError")]
739    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
740    #[serde(default)]
741    pub organization: Option<String>,
742    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
743    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
744    /// Implementations MUST NOT assign meaning to keys they do not recognize.
745    ///
746    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
747    #[serde_as(deserialize_as = "DefaultOnError")]
748    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
749    #[serde(default)]
750    #[serde(rename = "_meta")]
751    pub meta: Option<Meta>,
752}
753
754#[cfg(feature = "unstable_auth_status")]
755impl AuthAccount {
756    /// Builds [`AuthAccount`] with the required fields set. Optional fields start unset or empty.
757    #[must_use]
758    pub fn new(label: impl Into<String>) -> Self {
759        Self {
760            label: label.into(),
761            description: None,
762            active: None,
763            name: None,
764            email: None,
765            organization: None,
766            meta: None,
767        }
768    }
769
770    /// Short text shown with the label, such as the credential source.
771    #[must_use]
772    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
773        self.description = description.into_option();
774        self
775    }
776
777    /// Whether the agent currently uses this account by default.
778    #[must_use]
779    pub fn active(mut self, active: impl IntoOption<bool>) -> Self {
780        self.active = active.into_option();
781        self
782    }
783
784    /// Display name of the user, such as a username or full name.
785    #[must_use]
786    pub fn name(mut self, name: impl IntoOption<String>) -> Self {
787        self.name = name.into_option();
788        self
789    }
790
791    /// Email address of the user.
792    #[must_use]
793    pub fn email(mut self, email: impl IntoOption<String>) -> Self {
794        self.email = email.into_option();
795        self
796    }
797
798    /// Display name of the organization, team, or workspace the account is using.
799    #[must_use]
800    pub fn organization(mut self, organization: impl IntoOption<String>) -> Self {
801        self.organization = organization.into_option();
802        self
803    }
804
805    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
806    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
807    /// do not recognize.
808    ///
809    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
810    #[must_use]
811    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
812        self.meta = meta.into_option();
813        self
814    }
815}
816
817/// **UNSTABLE**
818///
819/// This capability is not part of the spec yet, and may be removed or changed at any point.
820///
821/// Auth status capabilities supported by the agent.
822///
823/// Supplying `{}` means the agent supports the `auth/status` method.
824#[cfg(feature = "unstable_auth_status")]
825#[serde_as]
826#[skip_serializing_none]
827#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
828#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
829#[non_exhaustive]
830pub struct AuthStatusCapabilities {
831    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
832    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
833    /// Implementations MUST NOT assign meaning to keys they do not recognize.
834    ///
835    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
836    #[serde_as(deserialize_as = "DefaultOnError")]
837    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
838    #[serde(default)]
839    #[serde(rename = "_meta")]
840    pub meta: Option<Meta>,
841}
842
843#[cfg(feature = "unstable_auth_status")]
844impl AuthStatusCapabilities {
845    /// Builds an empty [`AuthStatusCapabilities`]. Use builder methods to advertise supported sub-capabilities.
846    #[must_use]
847    pub fn new() -> Self {
848        Self::default()
849    }
850
851    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
852    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
853    /// do not recognize.
854    ///
855    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
856    #[must_use]
857    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
858        self.meta = meta.into_option();
859        self
860    }
861}
862
863/// Authentication-related extension capabilities supported by the agent.
864///
865/// This object does not advertise support for `auth/login` or `auth/logout`.
866/// Those methods are advertised by a non-empty `authMethods` list in the
867/// `initialize` response.
868#[serde_as]
869#[skip_serializing_none]
870#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
871#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
872#[serde(rename_all = "camelCase")]
873#[non_exhaustive]
874pub struct AgentAuthCapabilities {
875    /// **UNSTABLE**
876    ///
877    /// This capability is not part of the spec yet, and may be removed or changed at any point.
878    ///
879    /// Whether the agent supports the `auth/status` method.
880    ///
881    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
882    /// Supplying `{}` means the agent supports the `auth/status` method.
883    #[cfg(feature = "unstable_auth_status")]
884    #[serde_as(deserialize_as = "DefaultOnError")]
885    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
886    #[serde(default)]
887    pub status: Option<AuthStatusCapabilities>,
888    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
889    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
890    /// Implementations MUST NOT assign meaning to keys they do not recognize.
891    ///
892    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
893    #[serde_as(deserialize_as = "DefaultOnError")]
894    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
895    #[serde(default)]
896    #[serde(rename = "_meta")]
897    pub meta: Option<Meta>,
898}
899
900impl AgentAuthCapabilities {
901    /// Builds an empty [`AgentAuthCapabilities`].
902    #[must_use]
903    pub fn new() -> Self {
904        Self::default()
905    }
906
907    /// **UNSTABLE**
908    ///
909    /// This capability is not part of the spec yet, and may be removed or changed at any point.
910    ///
911    /// Whether the agent supports the `auth/status` method.
912    #[cfg(feature = "unstable_auth_status")]
913    #[must_use]
914    pub fn status(mut self, status: impl IntoOption<AuthStatusCapabilities>) -> Self {
915        self.status = status.into_option();
916        self
917    }
918
919    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
920    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
921    /// do not recognize.
922    ///
923    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
924    #[must_use]
925    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
926        self.meta = meta.into_option();
927        self
928    }
929}
930
931/// Typed identifier used for auth method values on the wire.
932#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
933#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
934#[serde(transparent)]
935#[from(forward)]
936#[non_exhaustive]
937pub struct AuthMethodId(pub Arc<str>);
938
939impl AuthMethodId {
940    /// Wraps a protocol string as a typed [`AuthMethodId`].
941    #[must_use]
942    pub fn new(id: impl Into<Self>) -> Self {
943        id.into()
944    }
945}
946
947/// Describes an available authentication method.
948///
949/// The `type` field acts as the discriminator in the serialized JSON form.
950#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
951#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
952#[serde(tag = "type", rename_all = "snake_case")]
953#[non_exhaustive]
954pub enum AuthMethod {
955    /// Client runs the configured agent program as a separate interactive
956    /// process, without passing this method to `auth/login`.
957    Terminal(AuthMethodTerminal),
958    /// Agent handles authentication itself through `auth/login`.
959    ///
960    /// The `type` discriminator value is `agent`.
961    Agent(AuthMethodAgent),
962    /// Custom or future authentication method.
963    ///
964    /// Values beginning with `_` are reserved for implementation-specific
965    /// extensions. Unknown values that do not begin with `_` are reserved for
966    /// future ACP variants.
967    ///
968    /// Clients that do not understand this method type should preserve the raw
969    /// payload when storing, replaying, proxying, or forwarding initialization
970    /// data, and otherwise ignore the method or display it generically.
971    #[serde(untagged)]
972    Other(OtherAuthMethod),
973}
974
975impl AuthMethod {
976    /// The unique identifier for this authentication method.
977    #[must_use]
978    pub fn method_id(&self) -> &AuthMethodId {
979        match self {
980            Self::Agent(a) => &a.method_id,
981            Self::Other(a) => &a.method_id,
982            Self::Terminal(t) => &t.method_id,
983        }
984    }
985
986    /// The human-readable name of this authentication method.
987    #[must_use]
988    pub fn name(&self) -> &str {
989        match self {
990            Self::Agent(a) => &a.name,
991            Self::Other(a) => &a.name,
992            Self::Terminal(t) => &t.name,
993        }
994    }
995
996    /// Optional human-readable description of this authentication method.
997    #[must_use]
998    pub fn description(&self) -> Option<&str> {
999        match self {
1000            Self::Agent(a) => a.description.as_deref(),
1001            Self::Other(a) => a
1002                .fields
1003                .get("description")
1004                .and_then(serde_json::Value::as_str),
1005            Self::Terminal(t) => t.description.as_deref(),
1006        }
1007    }
1008
1009    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1010    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1011    /// do not recognize.
1012    ///
1013    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1014    #[must_use]
1015    pub fn meta(&self) -> Option<&Meta> {
1016        match self {
1017            Self::Agent(a) => a.meta.as_ref(),
1018            Self::Other(a) => a.fields.get("_meta").and_then(serde_json::Value::as_object),
1019            Self::Terminal(t) => t.meta.as_ref(),
1020        }
1021    }
1022}
1023
1024/// Custom or future authentication method payload.
1025#[serde_as]
1026#[skip_serializing_none]
1027#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1028#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1029#[cfg_attr(feature = "schemars", schemars(inline))]
1030#[cfg_attr(feature = "schemars", schemars(transform = other_auth_method_schema))]
1031#[serde(rename_all = "camelCase")]
1032#[non_exhaustive]
1033pub struct OtherAuthMethod {
1034    /// Custom or future authentication method type.
1035    ///
1036    /// Values beginning with `_` are reserved for implementation-specific
1037    /// extensions. Unknown values that do not begin with `_` are reserved for
1038    /// future ACP variants.
1039    #[serde(rename = "type")]
1040    pub type_: String,
1041    /// Unique identifier for this authentication method.
1042    pub method_id: AuthMethodId,
1043    /// Human-readable name of the authentication method.
1044    pub name: String,
1045    /// The remaining fields of the unknown authentication method payload, preserved verbatim,
1046    /// including `description` and `_meta`.
1047    #[serde(flatten)]
1048    pub fields: BTreeMap<String, serde_json::Value>,
1049}
1050
1051impl OtherAuthMethod {
1052    /// Builds [`OtherAuthMethod`] from an unknown discriminator and preserves the remaining extension fields.
1053    #[must_use]
1054    pub fn new(
1055        type_: impl Into<String>,
1056        method_id: impl Into<AuthMethodId>,
1057        name: impl Into<String>,
1058        mut fields: BTreeMap<String, serde_json::Value>,
1059    ) -> Self {
1060        fields.remove("type");
1061        fields.remove("methodId");
1062        fields.remove("name");
1063        Self {
1064            type_: type_.into(),
1065            method_id: method_id.into(),
1066            name: name.into(),
1067            fields,
1068        }
1069    }
1070}
1071
1072impl<'de> Deserialize<'de> for OtherAuthMethod {
1073    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1074    where
1075        D: serde::Deserializer<'de>,
1076    {
1077        #[derive(Deserialize)]
1078        #[serde(rename_all = "camelCase")]
1079        struct RawOtherAuthMethod {
1080            #[serde(rename = "type")]
1081            type_: String,
1082            method_id: AuthMethodId,
1083            name: String,
1084            #[serde(flatten)]
1085            fields: BTreeMap<String, serde_json::Value>,
1086        }
1087
1088        let raw = RawOtherAuthMethod::deserialize(deserializer)?;
1089        if is_known_auth_method_type(&raw.type_) {
1090            return Err(serde::de::Error::custom(format!(
1091                "known authentication method `{}` did not match its schema",
1092                raw.type_
1093            )));
1094        }
1095
1096        Ok(Self {
1097            type_: raw.type_,
1098            method_id: raw.method_id,
1099            name: raw.name,
1100            fields: raw.fields,
1101        })
1102    }
1103}
1104
1105fn is_known_auth_method_type(type_: &str) -> bool {
1106    matches!(type_, "agent" | "terminal")
1107}
1108
1109#[cfg(feature = "schemars")]
1110fn other_auth_method_schema(schema: &mut Schema) {
1111    super::schema_util::reject_known_string_discriminators(schema, "type", &["agent", "terminal"]);
1112}
1113
1114/// Agent handles authentication itself through `auth/login`.
1115///
1116/// The `type` discriminator value is `agent`.
1117#[serde_as]
1118#[skip_serializing_none]
1119#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1120#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1121#[serde(rename_all = "camelCase")]
1122#[non_exhaustive]
1123pub struct AuthMethodAgent {
1124    /// Unique identifier for this authentication method.
1125    pub method_id: AuthMethodId,
1126    /// Human-readable name of the authentication method.
1127    pub name: String,
1128    /// Optional human-readable description of this authentication method.
1129    ///
1130    /// Omitted and `null` are equivalent and mean no description is provided.
1131    #[serde_as(deserialize_as = "DefaultOnError")]
1132    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1133    #[serde(default)]
1134    pub description: Option<String>,
1135    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1136    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1137    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1138    ///
1139    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1140    #[serde_as(deserialize_as = "DefaultOnError")]
1141    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1142    #[serde(default)]
1143    #[serde(rename = "_meta")]
1144    pub meta: Option<Meta>,
1145}
1146
1147impl AuthMethodAgent {
1148    /// Builds [`AuthMethodAgent`] with the required fields set. Optional fields start unset or empty.
1149    #[must_use]
1150    pub fn new(method_id: impl Into<AuthMethodId>, name: impl Into<String>) -> Self {
1151        Self {
1152            method_id: method_id.into(),
1153            name: name.into(),
1154            description: None,
1155            meta: None,
1156        }
1157    }
1158
1159    /// Optional human-readable description of this authentication method.
1160    #[must_use]
1161    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
1162        self.description = description.into_option();
1163        self
1164    }
1165
1166    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1167    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1168    /// do not recognize.
1169    ///
1170    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1171    #[must_use]
1172    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1173        self.meta = meta.into_option();
1174        self
1175    }
1176}
1177
1178/// Terminal-based authentication method.
1179///
1180/// The client runs the configured agent program as a separate interactive
1181/// process for the user to authenticate via a TUI. Agents MUST advertise this
1182/// method only when the client enabled its terminal authentication capability.
1183/// A zero exit status signals success. Any other termination signals failure.
1184/// The client MUST NOT pass this method to `auth/login`.
1185#[serde_as]
1186#[skip_serializing_none]
1187#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1188#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1189#[serde(rename_all = "camelCase")]
1190#[non_exhaustive]
1191pub struct AuthMethodTerminal {
1192    /// Unique identifier for this authentication method.
1193    pub method_id: AuthMethodId,
1194    /// Human-readable name of the authentication method.
1195    pub name: String,
1196    /// Optional human-readable description of this authentication method.
1197    ///
1198    /// Omitted and `null` are equivalent and mean no description is provided.
1199    #[serde_as(deserialize_as = "DefaultOnError")]
1200    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1201    #[serde(default)]
1202    pub description: Option<String>,
1203    /// Additional arguments to append to the configured agent invocation for terminal auth.
1204    #[serde_as(deserialize_as = "DefaultOnNull")]
1205    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1206    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1207    pub args: Vec<String>,
1208    /// Additional environment variables to set on the configured agent invocation for terminal auth.
1209    /// Names MUST be unique. These values override same-named variables in the
1210    /// base launch configuration.
1211    #[serde_as(deserialize_as = "DefaultOnNull")]
1212    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1213    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1214    pub env: Vec<EnvVariable>,
1215    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1216    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1217    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1218    ///
1219    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1220    #[serde_as(deserialize_as = "DefaultOnError")]
1221    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1222    #[serde(default)]
1223    #[serde(rename = "_meta")]
1224    pub meta: Option<Meta>,
1225}
1226
1227impl AuthMethodTerminal {
1228    /// Builds [`AuthMethodTerminal`] with the required fields set. Optional fields start unset or empty.
1229    #[must_use]
1230    pub fn new(method_id: impl Into<AuthMethodId>, name: impl Into<String>) -> Self {
1231        Self {
1232            method_id: method_id.into(),
1233            name: name.into(),
1234            description: None,
1235            args: Vec::new(),
1236            env: Vec::new(),
1237            meta: None,
1238        }
1239    }
1240
1241    /// Additional arguments to append to the configured agent invocation for terminal auth.
1242    #[must_use]
1243    pub fn args(mut self, args: Vec<String>) -> Self {
1244        self.args = args;
1245        self
1246    }
1247
1248    /// Additional environment variables to set on the configured agent invocation for terminal auth.
1249    /// Names MUST be unique. These values override same-named variables in the
1250    /// base launch configuration.
1251    #[must_use]
1252    pub fn env(mut self, env: Vec<EnvVariable>) -> Self {
1253        self.env = env;
1254        self
1255    }
1256
1257    /// Optional human-readable description of this authentication method.
1258    #[must_use]
1259    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
1260        self.description = description.into_option();
1261        self
1262    }
1263
1264    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1265    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1266    /// do not recognize.
1267    ///
1268    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1269    #[must_use]
1270    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1271        self.meta = meta.into_option();
1272        self
1273    }
1274}
1275
1276// New session
1277
1278/// Request parameters for creating a new session.
1279///
1280/// See protocol docs: [Creating a Session](https://agentclientprotocol.com/protocol/v2/session-setup#creating-a-session)
1281#[serde_as]
1282#[skip_serializing_none]
1283#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1284#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1285#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_NEW_METHOD_NAME)))]
1286#[serde(rename_all = "camelCase")]
1287#[non_exhaustive]
1288pub struct NewSessionRequest {
1289    /// The working directory for this session. Must be an absolute path.
1290    pub cwd: AbsolutePath,
1291    /// Additional workspace roots for this session. Each path must be absolute.
1292    ///
1293    /// These expand the session's workspace scope without changing `cwd`, which
1294    /// remains the base for relative paths. When omitted or empty, no
1295    /// additional roots are activated for the new session.
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 additional_directories: Vec<AbsolutePath>,
1300    /// List of MCP (Model Context Protocol) servers the agent should connect to.
1301    #[serde_as(deserialize_as = "DefaultOnNull")]
1302    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1303    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1304    pub mcp_servers: Vec<McpServer>,
1305    /// System-level instructions for the new session.
1306    ///
1307    /// Optional. Omitted and `null` are equivalent and mean the Agent uses its
1308    /// own default instructions. Clients MUST only send this when the Agent
1309    /// advertises `session.systemPrompt`.
1310    #[serde(default)]
1311    pub system_prompt: Option<SystemPrompt>,
1312    /// **UNSTABLE**
1313    ///
1314    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1315    ///
1316    /// Initial values for the session's config options.
1317    ///
1318    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1319    /// this when the Agent advertises `session.options`.
1320    ///
1321    /// The Agent applies the entries in list order, as if the Client had called
1322    /// `session/set_config_option` for each entry after the session was set up. Malformed
1323    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1324    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1325    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1326    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries,
1327    /// and SHOULD NOT send other `session/update` notifications caused by applying them
1328    /// before it responds.
1329    #[cfg(feature = "unstable_session_options")]
1330    #[serde_as(deserialize_as = "DefaultOnNull")]
1331    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1332    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1333    pub config_options: Vec<InitialSessionConfigOption>,
1334    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1335    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1336    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1337    ///
1338    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1339    #[serde_as(deserialize_as = "DefaultOnError")]
1340    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1341    #[serde(default)]
1342    #[serde(rename = "_meta")]
1343    pub meta: Option<Meta>,
1344}
1345
1346impl NewSessionRequest {
1347    /// Builds [`NewSessionRequest`] with the required request fields set. Optional fields start unset or empty.
1348    #[must_use]
1349    pub fn new(cwd: impl Into<AbsolutePath>) -> Self {
1350        Self {
1351            cwd: cwd.into(),
1352            additional_directories: vec![],
1353            mcp_servers: vec![],
1354            system_prompt: None,
1355            #[cfg(feature = "unstable_session_options")]
1356            config_options: vec![],
1357            meta: None,
1358        }
1359    }
1360
1361    /// Additional workspace roots for this session. Each path must be absolute.
1362    #[must_use]
1363    pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1364    where
1365        I: IntoIterator<Item = P>,
1366        P: Into<AbsolutePath>,
1367    {
1368        self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1369        self
1370    }
1371
1372    /// List of MCP (Model Context Protocol) servers the agent should connect to.
1373    #[must_use]
1374    pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1375        self.mcp_servers = mcp_servers;
1376        self
1377    }
1378
1379    /// System-level instructions for the new session.
1380    #[must_use]
1381    pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1382        self.system_prompt = system_prompt.into_option();
1383        self
1384    }
1385
1386    /// **UNSTABLE**
1387    ///
1388    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1389    ///
1390    /// Initial values for the session's config options.
1391    ///
1392    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1393    /// this when the Agent advertises `session.options`.
1394    ///
1395    /// The Agent applies the entries in list order, as if the Client had called
1396    /// `session/set_config_option` for each entry after the session was set up. Malformed
1397    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1398    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1399    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1400    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries,
1401    /// and SHOULD NOT send other `session/update` notifications caused by applying them
1402    /// before it responds.
1403    #[cfg(feature = "unstable_session_options")]
1404    #[must_use]
1405    pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1406        self.config_options = config_options;
1407        self
1408    }
1409
1410    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1411    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1412    /// do not recognize.
1413    ///
1414    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1415    #[must_use]
1416    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1417        self.meta = meta.into_option();
1418        self
1419    }
1420}
1421
1422/// Response from creating a new session.
1423///
1424/// New sessions default to `idle` until a state update reports otherwise.
1425/// Updates may arrive before or after this response. Clients MUST NOT overwrite
1426/// an already-reported state when the response arrives.
1427///
1428/// See protocol docs: [Creating a Session](https://agentclientprotocol.com/protocol/v2/session-setup#creating-a-session)
1429#[serde_as]
1430#[skip_serializing_none]
1431#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1432#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1433#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_NEW_METHOD_NAME)))]
1434#[serde(rename_all = "camelCase")]
1435#[non_exhaustive]
1436pub struct NewSessionResponse {
1437    /// Unique identifier for the created session.
1438    ///
1439    /// Used in all subsequent requests for this conversation.
1440    pub session_id: SessionId,
1441    /// Initial session configuration options.
1442    ///
1443    /// Optional. Omitted or empty means no config options are advertised.
1444    /// Senders MUST use an array, not `null`. Receivers treat `null` like omission.
1445    /// Later `config_option_update` notifications replace this list.
1446    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1447    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1448    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1449    pub config_options: Vec<SessionConfigOption>,
1450    /// Initial commands the agent can execute in this session.
1451    ///
1452    /// Optional. Omitted or empty means no initial commands are advertised.
1453    /// Senders MUST use an array, not `null`. Receivers treat `null` like omission.
1454    /// Later `available_commands_update` notifications replace this list.
1455    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1456    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1457    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1458    pub available_commands: Vec<AvailableCommand>,
1459    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1460    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1461    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1462    ///
1463    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1464    #[serde_as(deserialize_as = "DefaultOnError")]
1465    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1466    #[serde(default)]
1467    #[serde(rename = "_meta")]
1468    pub meta: Option<Meta>,
1469}
1470
1471impl NewSessionResponse {
1472    /// Builds [`NewSessionResponse`] with the required response fields set. Optional fields start unset or empty.
1473    #[must_use]
1474    pub fn new(session_id: impl Into<SessionId>) -> Self {
1475        Self {
1476            session_id: session_id.into(),
1477            config_options: Vec::new(),
1478            available_commands: Vec::new(),
1479            meta: None,
1480        }
1481    }
1482
1483    /// Initial session configuration options.
1484    ///
1485    /// Optional. Omitted or empty means no config options are advertised.
1486    /// Senders MUST use an array, not `null`. Receivers treat `null` like omission.
1487    /// Later `config_option_update` notifications replace this list.
1488    #[must_use]
1489    pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
1490        self.config_options = config_options;
1491        self
1492    }
1493
1494    /// Initial commands the agent can execute in this session.
1495    #[must_use]
1496    pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
1497        self.available_commands = available_commands;
1498        self
1499    }
1500
1501    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1502    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1503    /// do not recognize.
1504    ///
1505    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1506    #[must_use]
1507    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1508        self.meta = meta.into_option();
1509        self
1510    }
1511}
1512
1513// Fork session
1514
1515/// **UNSTABLE**
1516///
1517/// This capability is not part of the spec yet, and may be removed or changed at any point.
1518///
1519/// Request parameters for forking an existing session.
1520///
1521/// Creates a new session based on the context of an existing one, allowing
1522/// operations like generating summaries without affecting the original session's history.
1523///
1524/// Only available if the Agent supports the `session.fork` capability.
1525#[cfg(feature = "unstable_session_fork")]
1526#[serde_as]
1527#[skip_serializing_none]
1528#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1529#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1530#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_FORK_METHOD_NAME)))]
1531#[serde(rename_all = "camelCase")]
1532#[non_exhaustive]
1533pub struct ForkSessionRequest {
1534    /// The ID of the session to fork.
1535    pub session_id: SessionId,
1536    /// **UNSTABLE**
1537    ///
1538    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1539    ///
1540    /// The session cursor to fork at. The new session's history is the source
1541    /// session's history before the cursor.
1542    ///
1543    /// Optional. Omitted and `null` are equivalent and fork the whole session.
1544    /// Clients MUST only send the ID of a cursor that the Agent announced on the
1545    /// source session and that currently advertises `capabilities.fork`. The Agent
1546    /// rejects any other ID with `-32602`. It does not fall back to forking the
1547    /// whole session.
1548    #[cfg(feature = "unstable_session_cursors")]
1549    #[serde(default)]
1550    pub cursor_id: Option<CursorId>,
1551    /// The working directory for this session. Must be an absolute path.
1552    pub cwd: AbsolutePath,
1553    /// Additional workspace roots to activate for this session. Each path must be absolute.
1554    ///
1555    /// When omitted or empty, no additional roots are activated. When non-empty,
1556    /// this is the complete resulting additional-root list for the forked
1557    /// session.
1558    #[serde_as(deserialize_as = "DefaultOnNull")]
1559    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1560    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1561    pub additional_directories: Vec<AbsolutePath>,
1562    /// List of MCP servers to connect to for this session.
1563    #[serde_as(deserialize_as = "DefaultOnNull")]
1564    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1565    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1566    pub mcp_servers: Vec<McpServer>,
1567    /// System-level instructions for the forked session.
1568    ///
1569    /// Optional. Omitted and `null` are equivalent. The Agent may then keep a
1570    /// system prompt it stored with the source session or use its default
1571    /// instructions. Clients MUST only send this when the Agent advertises
1572    /// `session.systemPrompt`, and SHOULD send the same value they used for the
1573    /// source session.
1574    #[serde(default)]
1575    pub system_prompt: Option<SystemPrompt>,
1576    /// **UNSTABLE**
1577    ///
1578    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1579    ///
1580    /// Initial values for the forked session's config options.
1581    ///
1582    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1583    /// this when the Agent advertises `session.options`.
1584    ///
1585    /// The Agent applies the entries in list order on top of the configuration the fork
1586    /// starts with, as if the Client had called `session/set_config_option` for each entry
1587    /// after the session was set up. Malformed entries and duplicate `configId` values fail
1588    /// the request with `-32602`. The Agent MUST ignore an entry whose `configId` is unknown,
1589    /// whose `type` does not match the option, or whose value is not allowed when it is
1590    /// applied. The `configOptions` in the response contain the values the session actually
1591    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries,
1592    /// and SHOULD NOT send other `session/update` notifications caused by applying them
1593    /// before it responds.
1594    #[cfg(feature = "unstable_session_options")]
1595    #[serde_as(deserialize_as = "DefaultOnNull")]
1596    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1597    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1598    pub config_options: Vec<InitialSessionConfigOption>,
1599    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1600    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1601    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1602    ///
1603    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1604    #[serde_as(deserialize_as = "DefaultOnError")]
1605    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1606    #[serde(default)]
1607    #[serde(rename = "_meta")]
1608    pub meta: Option<Meta>,
1609}
1610
1611#[cfg(feature = "unstable_session_fork")]
1612impl ForkSessionRequest {
1613    /// Builds [`ForkSessionRequest`] with the required request fields set. Optional fields start unset or empty.
1614    #[must_use]
1615    pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
1616        Self {
1617            session_id: session_id.into(),
1618            #[cfg(feature = "unstable_session_cursors")]
1619            cursor_id: None,
1620            cwd: cwd.into(),
1621            additional_directories: vec![],
1622            mcp_servers: vec![],
1623            system_prompt: None,
1624            #[cfg(feature = "unstable_session_options")]
1625            config_options: vec![],
1626            meta: None,
1627        }
1628    }
1629
1630    /// **UNSTABLE**
1631    ///
1632    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1633    ///
1634    /// The session cursor to fork at. Omitting it forks the whole session.
1635    ///
1636    /// Clients MUST only send the ID of a cursor that the Agent announced on the
1637    /// source session and that currently advertises `capabilities.fork`.
1638    #[cfg(feature = "unstable_session_cursors")]
1639    #[must_use]
1640    pub fn cursor_id(mut self, cursor_id: impl IntoOption<CursorId>) -> Self {
1641        self.cursor_id = cursor_id.into_option();
1642        self
1643    }
1644
1645    /// Additional workspace roots to activate for this session. Each path must be absolute.
1646    #[must_use]
1647    pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1648    where
1649        I: IntoIterator<Item = P>,
1650        P: Into<AbsolutePath>,
1651    {
1652        self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1653        self
1654    }
1655
1656    /// List of MCP servers to connect to for this session.
1657    #[must_use]
1658    pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1659        self.mcp_servers = mcp_servers;
1660        self
1661    }
1662
1663    /// System-level instructions for the forked session.
1664    #[must_use]
1665    pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1666        self.system_prompt = system_prompt.into_option();
1667        self
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    /// Initial values for the forked session's config options.
1675    ///
1676    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1677    /// this when the Agent advertises `session.options`.
1678    ///
1679    /// The Agent applies the entries in list order on top of the configuration the fork
1680    /// starts with, as if the Client had called `session/set_config_option` for each entry
1681    /// after the session was set up. Malformed entries and duplicate `configId` values fail
1682    /// the request with `-32602`. The Agent MUST ignore an entry whose `configId` is unknown,
1683    /// whose `type` does not match the option, or whose value is not allowed when it is
1684    /// applied. The `configOptions` in the response contain the values the session actually
1685    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries,
1686    /// and SHOULD NOT send other `session/update` notifications caused by applying them
1687    /// before it responds.
1688    #[cfg(feature = "unstable_session_options")]
1689    #[must_use]
1690    pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1691        self.config_options = config_options;
1692        self
1693    }
1694
1695    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1696    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1697    /// do not recognize.
1698    ///
1699    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1700    #[must_use]
1701    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1702        self.meta = meta.into_option();
1703        self
1704    }
1705}
1706
1707/// **UNSTABLE**
1708///
1709/// This capability is not part of the spec yet, and may be removed or changed at any point.
1710///
1711/// Response from forking an existing session.
1712#[cfg(feature = "unstable_session_fork")]
1713#[serde_as]
1714#[skip_serializing_none]
1715#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1716#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1717#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_FORK_METHOD_NAME)))]
1718#[serde(rename_all = "camelCase")]
1719#[non_exhaustive]
1720pub struct ForkSessionResponse {
1721    /// Unique identifier for the newly created forked session.
1722    pub session_id: SessionId,
1723    /// Initial session configuration options.
1724    ///
1725    /// Optional. Omitted or empty means no config options are advertised.
1726    /// Senders MUST use an array, not `null`. Receivers treat `null` like omission.
1727    /// Later `config_option_update` notifications replace this list.
1728    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1729    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1730    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1731    pub config_options: Vec<SessionConfigOption>,
1732    /// Initial commands the agent can execute in this session.
1733    ///
1734    /// Optional. Omitted or empty means no initial commands are advertised.
1735    /// Senders MUST use an array, not `null`. Receivers treat `null` like omission.
1736    /// Later `available_commands_update` notifications replace this list.
1737    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1738    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1739    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1740    pub available_commands: Vec<AvailableCommand>,
1741    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1742    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1743    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1744    ///
1745    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1746    #[serde_as(deserialize_as = "DefaultOnError")]
1747    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1748    #[serde(default)]
1749    #[serde(rename = "_meta")]
1750    pub meta: Option<Meta>,
1751}
1752
1753#[cfg(feature = "unstable_session_fork")]
1754impl ForkSessionResponse {
1755    /// Builds [`ForkSessionResponse`] with the required response fields set. Optional fields start unset or empty.
1756    #[must_use]
1757    pub fn new(session_id: impl Into<SessionId>) -> Self {
1758        Self {
1759            session_id: session_id.into(),
1760            config_options: Vec::new(),
1761            available_commands: Vec::new(),
1762            meta: None,
1763        }
1764    }
1765
1766    /// Initial session configuration options.
1767    ///
1768    /// Optional. Omitted or empty means no config options are advertised.
1769    /// Senders MUST use an array, not `null`. Receivers treat `null` like omission.
1770    /// Later `config_option_update` notifications replace this list.
1771    #[must_use]
1772    pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
1773        self.config_options = config_options;
1774        self
1775    }
1776
1777    /// Initial commands the agent can execute in this session.
1778    #[must_use]
1779    pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
1780        self.available_commands = available_commands;
1781        self
1782    }
1783
1784    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1785    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1786    /// do not recognize.
1787    ///
1788    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1789    #[must_use]
1790    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1791        self.meta = meta.into_option();
1792        self
1793    }
1794}
1795
1796// Resume session
1797
1798/// Request parameters for resuming an existing session.
1799///
1800/// Resumes an existing session and optionally replays retained conversation
1801/// history according to `replayFrom`.
1802#[serde_as]
1803#[skip_serializing_none]
1804#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1805#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1806#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_RESUME_METHOD_NAME)))]
1807#[serde(rename_all = "camelCase")]
1808#[non_exhaustive]
1809pub struct ResumeSessionRequest {
1810    /// The ID of the session to resume.
1811    pub session_id: SessionId,
1812    /// The working directory for this session. Must be an absolute path.
1813    ///
1814    /// Clients MUST send the session's working directory. Agents MAY reject a different directory
1815    /// with `-32602`, and MAY normalize paths when comparing.
1816    pub cwd: AbsolutePath,
1817    /// Additional workspace roots to activate for this session. Each path must be absolute.
1818    ///
1819    /// When omitted or empty, no additional roots are activated. When non-empty,
1820    /// this is the complete resulting additional-root list for the resumed
1821    /// session. It may differ from any previously used or reported list as long as
1822    /// the request `cwd` matches the session's `cwd`.
1823    #[serde_as(deserialize_as = "DefaultOnNull")]
1824    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1825    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1826    pub additional_directories: Vec<AbsolutePath>,
1827    /// List of MCP servers to connect to for this session.
1828    ///
1829    /// The complete set of Client-provided servers. Omitted and `[]` mean none. Agents SHOULD
1830    /// NOT restore servers from earlier requests.
1831    #[serde_as(deserialize_as = "DefaultOnNull")]
1832    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1833    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1834    pub mcp_servers: Vec<McpServer>,
1835    /// Inclusive cursor describing where conversation replay should begin.
1836    ///
1837    /// Optional. Omitted and `null` are equivalent and mean the Agent should resume without
1838    /// replaying previous conversation history. Replay cursors are inclusive:
1839    /// replay includes the position identified by the cursor. Supplying
1840    /// `{ "type": "start" }` means the Agent should replay all retained
1841    /// conversation history before responding.
1842    ///
1843    /// Agents MUST reject unsupported cursor types or malformed cursor values
1844    /// with `-32602` (Invalid params), rather than substituting another cursor
1845    /// or resuming without replay.
1846    #[serde(default)]
1847    pub replay_from: Option<ReplayFrom>,
1848    /// System-level instructions for the resumed session.
1849    ///
1850    /// Optional. Omitted and `null` are equivalent. The Agent may then keep a
1851    /// system prompt it stored with the session or use its default instructions.
1852    /// Clients MUST only send this when the Agent advertises
1853    /// `session.systemPrompt`, and SHOULD send the same value they used when the
1854    /// session was created.
1855    #[serde(default)]
1856    pub system_prompt: Option<SystemPrompt>,
1857    /// **UNSTABLE**
1858    ///
1859    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1860    ///
1861    /// Initial values for the session's config options.
1862    ///
1863    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1864    /// this when the Agent advertises `session.options`.
1865    ///
1866    /// The Agent applies the entries in list order, as if the Client had called
1867    /// `session/set_config_option` for each entry after the session was set up. Malformed
1868    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1869    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1870    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1871    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries
1872    /// on the requesting connection. If the session is active on other connections, the
1873    /// Agent SHOULD send `config_option_update` on those connections.
1874    ///
1875    /// The Agent applies the entries before it replays history for `replayFrom` and before
1876    /// it responds.
1877    #[cfg(feature = "unstable_session_options")]
1878    #[serde_as(deserialize_as = "DefaultOnNull")]
1879    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1880    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1881    pub config_options: Vec<InitialSessionConfigOption>,
1882    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1883    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1884    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1885    ///
1886    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1887    #[serde_as(deserialize_as = "DefaultOnError")]
1888    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1889    #[serde(default)]
1890    #[serde(rename = "_meta")]
1891    pub meta: Option<Meta>,
1892}
1893
1894impl ResumeSessionRequest {
1895    /// Builds [`ResumeSessionRequest`] with the required request fields set. Optional fields start unset or empty.
1896    #[must_use]
1897    pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
1898        Self {
1899            session_id: session_id.into(),
1900            cwd: cwd.into(),
1901            additional_directories: vec![],
1902            mcp_servers: vec![],
1903            replay_from: None,
1904            system_prompt: None,
1905            #[cfg(feature = "unstable_session_options")]
1906            config_options: vec![],
1907            meta: None,
1908        }
1909    }
1910
1911    /// Additional workspace roots to activate for this session. Each path must be absolute.
1912    #[must_use]
1913    pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1914    where
1915        I: IntoIterator<Item = P>,
1916        P: Into<AbsolutePath>,
1917    {
1918        self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1919        self
1920    }
1921
1922    /// List of MCP servers to connect to for this session.
1923    #[must_use]
1924    pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1925        self.mcp_servers = mcp_servers;
1926        self
1927    }
1928
1929    /// Inclusive cursor describing where conversation replay should begin.
1930    ///
1931    /// Omitted and `null` are equivalent and mean the Agent should resume without replaying
1932    /// previous conversation history. Replay cursors are inclusive: replay
1933    /// includes the position identified by the cursor. Supplying
1934    /// `{ "type": "start" }` means the Agent should replay all retained
1935    /// conversation history before responding.
1936    #[must_use]
1937    pub fn replay_from(mut self, replay_from: impl IntoOption<ReplayFrom>) -> Self {
1938        self.replay_from = replay_from.into_option();
1939        self
1940    }
1941
1942    /// System-level instructions for the resumed session.
1943    #[must_use]
1944    pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1945        self.system_prompt = system_prompt.into_option();
1946        self
1947    }
1948
1949    /// **UNSTABLE**
1950    ///
1951    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1952    ///
1953    /// Initial values for the session's config options.
1954    ///
1955    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1956    /// this when the Agent advertises `session.options`.
1957    ///
1958    /// The Agent applies the entries in list order, as if the Client had called
1959    /// `session/set_config_option` for each entry after the session was set up. Malformed
1960    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1961    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1962    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1963    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries
1964    /// on the requesting connection. If the session is active on other connections, the
1965    /// Agent SHOULD send `config_option_update` on those connections.
1966    #[cfg(feature = "unstable_session_options")]
1967    #[must_use]
1968    pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1969        self.config_options = config_options;
1970        self
1971    }
1972
1973    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1974    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1975    /// do not recognize.
1976    ///
1977    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1978    #[must_use]
1979    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1980        self.meta = meta.into_option();
1981        self
1982    }
1983}
1984
1985/// Inclusive cursor describing where replayed session history should begin.
1986///
1987/// Replay includes the position identified by the cursor.
1988#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1989#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1990#[serde(tag = "type", rename_all = "snake_case")]
1991#[non_exhaustive]
1992pub enum ReplayFrom {
1993    /// Replay all retained conversation history from its first replayable entry.
1994    Start(ReplayFromStart),
1995    /// Custom or future replay cursor.
1996    ///
1997    /// Values beginning with `_` are reserved for implementation-specific
1998    /// extensions. Unknown values that do not begin with `_` are reserved for
1999    /// future ACP variants.
2000    ///
2001    /// Intermediaries SHOULD preserve the raw payload when storing, replaying,
2002    /// proxying, or forwarding requests. Agents that do not support this cursor
2003    /// MUST reject the request with `-32602` (Invalid params), rather than
2004    /// substituting another cursor or resuming without replay.
2005    #[serde(untagged)]
2006    Other(OtherReplayFrom),
2007}
2008
2009impl From<ReplayFromStart> for ReplayFrom {
2010    fn from(replay_from: ReplayFromStart) -> Self {
2011        Self::Start(replay_from)
2012    }
2013}
2014
2015/// Inclusive replay cursor requesting replay from the start of retained conversation history.
2016#[serde_as]
2017#[skip_serializing_none]
2018#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2019#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2020#[serde(rename_all = "camelCase")]
2021#[non_exhaustive]
2022pub struct ReplayFromStart {
2023    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2024    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2025    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2026    ///
2027    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2028    #[serde_as(deserialize_as = "DefaultOnError")]
2029    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2030    #[serde(default)]
2031    #[serde(rename = "_meta")]
2032    pub meta: Option<Meta>,
2033}
2034
2035impl ReplayFromStart {
2036    /// Builds [`ReplayFromStart`].
2037    #[must_use]
2038    pub fn new() -> Self {
2039        Self::default()
2040    }
2041
2042    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2043    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2044    /// do not recognize.
2045    ///
2046    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2047    #[must_use]
2048    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2049        self.meta = meta.into_option();
2050        self
2051    }
2052}
2053
2054/// Custom or future replay cursor payload.
2055#[serde_as]
2056#[skip_serializing_none]
2057#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2058#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
2059#[cfg_attr(feature = "schemars", schemars(inline))]
2060#[cfg_attr(feature = "schemars", schemars(transform = other_replay_from_schema))]
2061#[serde(rename_all = "camelCase")]
2062#[non_exhaustive]
2063pub struct OtherReplayFrom {
2064    /// Custom or future replay cursor type.
2065    ///
2066    /// Values beginning with `_` are reserved for implementation-specific
2067    /// extensions. Unknown values that do not begin with `_` are reserved for
2068    /// future ACP variants.
2069    #[serde(rename = "type")]
2070    pub type_: String,
2071    /// The remaining fields of the unknown replay cursor payload, preserved verbatim,
2072    /// including `_meta`.
2073    #[serde(flatten)]
2074    pub fields: BTreeMap<String, serde_json::Value>,
2075}
2076
2077impl OtherReplayFrom {
2078    /// Builds [`OtherReplayFrom`] from an unknown discriminator and preserves the remaining extension fields.
2079    #[must_use]
2080    pub fn new(type_: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
2081        fields.remove("type");
2082        Self {
2083            type_: type_.into(),
2084            fields,
2085        }
2086    }
2087}
2088
2089impl<'de> Deserialize<'de> for OtherReplayFrom {
2090    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2091    where
2092        D: serde::Deserializer<'de>,
2093    {
2094        let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
2095        let type_ = fields
2096            .remove("type")
2097            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
2098        let serde_json::Value::String(type_) = type_ else {
2099            return Err(serde::de::Error::custom("`type` must be a string"));
2100        };
2101
2102        if is_known_replay_from_type(&type_) {
2103            return Err(serde::de::Error::custom(format!(
2104                "known replay cursor `{type_}` did not match its schema"
2105            )));
2106        }
2107
2108        Ok(Self { type_, fields })
2109    }
2110}
2111
2112fn is_known_replay_from_type(type_: &str) -> bool {
2113    matches!(type_, "start")
2114}
2115
2116#[cfg(feature = "schemars")]
2117fn other_replay_from_schema(schema: &mut Schema) {
2118    super::schema_util::reject_known_string_discriminators(schema, "type", &["start"]);
2119}
2120
2121crate::serde_util::default_on_null! {
2122    /// Response from resuming an existing session.
2123    ///
2124    /// The agent MUST send a current `state_update` after any requested history
2125    /// replay and before this response, even without replay. The update reports
2126    /// foreground state after resuming. The response alone does not imply `idle`.
2127    ///
2128    /// See protocol docs: [Current-State Synchronization](https://agentclientprotocol.com/protocol/v2/session-setup#current-state-synchronization)
2129    #[serde_as]
2130    #[skip_serializing_none]
2131    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2132    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2133    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_RESUME_METHOD_NAME)))]
2134    #[serde(rename_all = "camelCase")]
2135    #[non_exhaustive]
2136    pub struct ResumeSessionResponse {
2137        /// Initial session configuration options.
2138        ///
2139        /// Optional. Omitted or empty means no config options are advertised.
2140        /// Senders MUST use an array, not `null`. Receivers treat `null` like omission.
2141        /// Later `config_option_update` notifications replace this list.
2142        #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2143        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2144        #[serde(default, skip_serializing_if = "Vec::is_empty")]
2145        pub config_options: Vec<SessionConfigOption>,
2146        /// Initial commands the agent can execute in this session.
2147        ///
2148        /// Optional. Omitted or empty means no initial commands are advertised.
2149        /// Senders MUST use an array, not `null`. Receivers treat `null` like omission.
2150        /// Later `available_commands_update` notifications replace this list.
2151        #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2152        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2153        #[serde(default, skip_serializing_if = "Vec::is_empty")]
2154        pub available_commands: Vec<AvailableCommand>,
2155        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2156        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2157        /// Implementations MUST NOT assign meaning to keys they do not recognize.
2158        ///
2159        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2160        #[serde_as(deserialize_as = "DefaultOnError")]
2161        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2162        #[serde(default)]
2163        #[serde(rename = "_meta")]
2164        pub meta: Option<Meta>,
2165    }
2166}
2167
2168impl ResumeSessionResponse {
2169    /// Builds [`ResumeSessionResponse`] with the required response fields set. Optional fields start unset or empty.
2170    #[must_use]
2171    pub fn new() -> Self {
2172        Self::default()
2173    }
2174
2175    /// Initial session configuration options.
2176    ///
2177    /// Optional. Omitted or empty means no config options are advertised.
2178    /// Senders MUST use an array, not `null`. Receivers treat `null` like omission.
2179    /// Later `config_option_update` notifications replace this list.
2180    #[must_use]
2181    pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
2182        self.config_options = config_options;
2183        self
2184    }
2185
2186    /// Initial commands the agent can execute in this session.
2187    #[must_use]
2188    pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
2189        self.available_commands = available_commands;
2190        self
2191    }
2192
2193    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2194    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2195    /// do not recognize.
2196    ///
2197    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2198    #[must_use]
2199    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2200        self.meta = meta.into_option();
2201        self
2202    }
2203}
2204
2205// Close session
2206
2207/// Request parameters for closing an active session.
2208///
2209/// The Agent MUST cancel any ongoing work related to the session as if `session/cancel`
2210/// was called, then free the resources associated with the session. Unlike `session/cancel`,
2211/// closing also stops the session's background work. After the close response, the Agent
2212/// sends no other messages for the session on that connection.
2213///
2214/// Closing a session that does not exist or is not active SHOULD succeed, and Clients SHOULD
2215/// treat a `-32002` response as a successful close.
2216///
2217/// When closing cancels active foreground work, the Agent MUST send the final
2218/// updates for that work and the idle `state_update` with `stopReason: "cancelled"`
2219/// before responding successfully to `session/close`. Closing an idle session
2220/// does not itself require another idle update.
2221///
2222/// Closing also cancels pending `session/prompt` requests whose messages have not
2223/// been inserted, including held prompts. If closing prevents a prompt's user message from being inserted, the
2224/// Agent MUST answer that request with `-32800` (Request Cancelled). If the message
2225/// has already been inserted, the Agent MUST respond successfully with its
2226/// `messageId`. Prompt responses need not precede the close response.
2227#[serde_as]
2228#[skip_serializing_none]
2229#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2230#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2231#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CLOSE_METHOD_NAME)))]
2232#[serde(rename_all = "camelCase")]
2233#[non_exhaustive]
2234pub struct CloseSessionRequest {
2235    /// The ID of the session to close.
2236    pub session_id: SessionId,
2237    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2238    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2239    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2240    ///
2241    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2242    #[serde_as(deserialize_as = "DefaultOnError")]
2243    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2244    #[serde(default)]
2245    #[serde(rename = "_meta")]
2246    pub meta: Option<Meta>,
2247}
2248
2249impl CloseSessionRequest {
2250    /// Builds [`CloseSessionRequest`] with the required request fields set. Optional fields start unset or empty.
2251    #[must_use]
2252    pub fn new(session_id: impl Into<SessionId>) -> Self {
2253        Self {
2254            session_id: session_id.into(),
2255            meta: None,
2256        }
2257    }
2258
2259    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2260    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2261    /// do not recognize.
2262    ///
2263    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2264    #[must_use]
2265    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2266        self.meta = meta.into_option();
2267        self
2268    }
2269}
2270
2271crate::serde_util::default_on_null! {
2272    /// Response from closing a session.
2273    #[serde_as]
2274    #[skip_serializing_none]
2275    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2276    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2277    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CLOSE_METHOD_NAME)))]
2278    #[serde(rename_all = "camelCase")]
2279    #[non_exhaustive]
2280    pub struct CloseSessionResponse {
2281        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2282        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2283        /// Implementations MUST NOT assign meaning to keys they do not recognize.
2284        ///
2285        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2286        #[serde_as(deserialize_as = "DefaultOnError")]
2287        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2288        #[serde(default)]
2289        #[serde(rename = "_meta")]
2290        pub meta: Option<Meta>,
2291    }
2292}
2293
2294impl CloseSessionResponse {
2295    /// Builds [`CloseSessionResponse`] with the required response fields set. Optional fields start unset or empty.
2296    #[must_use]
2297    pub fn new() -> Self {
2298        Self::default()
2299    }
2300
2301    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2302    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2303    /// do not recognize.
2304    ///
2305    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2306    #[must_use]
2307    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2308        self.meta = meta.into_option();
2309        self
2310    }
2311}
2312
2313// Session status
2314
2315/// **UNSTABLE**
2316///
2317/// This capability is not part of the spec yet, and may be removed or changed at any point.
2318///
2319/// Request parameters for checking the status of a session.
2320///
2321/// Only available if the Agent supports the `session.status` capability.
2322///
2323/// `session/status` MUST NOT have side effects. The Agent does not load, resume, create,
2324/// close, or change the session, and does not attach the requesting connection to it.
2325/// A session the Agent does not know gets `-32002` with the requested `sessionId` in `data`.
2326#[cfg(feature = "unstable_session_status")]
2327#[serde_as]
2328#[skip_serializing_none]
2329#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2330#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2331#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_STATUS_METHOD_NAME)))]
2332#[serde(rename_all = "camelCase")]
2333#[non_exhaustive]
2334pub struct SessionStatusRequest {
2335    /// The ID of the session to check.
2336    pub session_id: SessionId,
2337    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2338    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2339    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2340    ///
2341    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2342    #[serde_as(deserialize_as = "DefaultOnError")]
2343    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2344    #[serde(default)]
2345    #[serde(rename = "_meta")]
2346    pub meta: Option<Meta>,
2347}
2348
2349#[cfg(feature = "unstable_session_status")]
2350impl SessionStatusRequest {
2351    /// Builds [`SessionStatusRequest`] with the required request fields set. Optional fields start unset or empty.
2352    #[must_use]
2353    pub fn new(session_id: impl Into<SessionId>) -> Self {
2354        Self {
2355            session_id: session_id.into(),
2356            meta: None,
2357        }
2358    }
2359
2360    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2361    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2362    /// do not recognize.
2363    ///
2364    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2365    #[must_use]
2366    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2367        self.meta = meta.into_option();
2368        self
2369    }
2370}
2371
2372/// **UNSTABLE**
2373///
2374/// This capability is not part of the spec yet, and may be removed or changed at any point.
2375///
2376/// Response from checking the status of a session.
2377///
2378/// The result is a snapshot. A session reported `open` may be closed or evicted before
2379/// the Client's next request.
2380#[cfg(feature = "unstable_session_status")]
2381#[serde_as]
2382#[skip_serializing_none]
2383#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2384#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2385#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_STATUS_METHOD_NAME)))]
2386#[serde(rename_all = "camelCase")]
2387#[non_exhaustive]
2388pub struct SessionStatusResponse {
2389    /// Whether the Agent has the session in memory.
2390    ///
2391    /// Required. Clients MUST treat a value they do not recognize as `saved`.
2392    pub status: SessionStatus,
2393    /// The session's current foreground state, as the same snapshot the Agent sends in
2394    /// `state_update` notifications.
2395    ///
2396    /// Optional. Agents SHOULD include it when `status` is `open`. Omitted, `null`, and
2397    /// malformed values mean the Agent is not reporting foreground state, and Clients
2398    /// MUST NOT read that as `idle`. This is a snapshot, not a new transition. Clients
2399    /// MUST NOT count an `idle` snapshot as a new completion.
2400    #[serde_as(deserialize_as = "DefaultOnError")]
2401    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2402    #[serde(default)]
2403    pub state: Option<StateUpdate>,
2404    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2405    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2406    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2407    ///
2408    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2409    #[serde_as(deserialize_as = "DefaultOnError")]
2410    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2411    #[serde(default)]
2412    #[serde(rename = "_meta")]
2413    pub meta: Option<Meta>,
2414}
2415
2416#[cfg(feature = "unstable_session_status")]
2417impl SessionStatusResponse {
2418    /// Builds [`SessionStatusResponse`] with the required response fields set. Optional fields start unset or empty.
2419    #[must_use]
2420    pub fn new(status: SessionStatus) -> Self {
2421        Self {
2422            status,
2423            state: None,
2424            meta: None,
2425        }
2426    }
2427
2428    /// The session's current foreground state, as the same snapshot the Agent sends in
2429    /// `state_update` notifications.
2430    #[must_use]
2431    pub fn state(mut self, state: impl IntoOption<StateUpdate>) -> Self {
2432        self.state = state.into_option();
2433        self
2434    }
2435
2436    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2437    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2438    /// do not recognize.
2439    ///
2440    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2441    #[must_use]
2442    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2443        self.meta = meta.into_option();
2444        self
2445    }
2446}
2447
2448/// **UNSTABLE**
2449///
2450/// This capability is not part of the spec yet, and may be removed or changed at any point.
2451///
2452/// Whether the Agent has a session in memory, as reported by `session/status`.
2453#[cfg(feature = "unstable_session_status")]
2454#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2455#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2456#[serde(rename_all = "snake_case")]
2457#[non_exhaustive]
2458pub enum SessionStatus {
2459    /// The Agent has the session in memory, for any connection.
2460    ///
2461    /// This does not mean the requesting connection is attached to it. A Client that did
2462    /// not create or resume the session on its own connection MUST still call
2463    /// `session/resume` before sending `session/prompt` or expecting
2464    /// `session/update` notifications.
2465    Open,
2466    /// The Agent knows the session and can resume it, but does not have it in memory.
2467    ///
2468    /// The Client can call `session/resume` to start it.
2469    Saved,
2470    /// Custom or future session status.
2471    ///
2472    /// Values beginning with `_` are reserved for implementation-specific
2473    /// extensions. Unknown values that do not begin with `_` are reserved for
2474    /// future ACP variants. Clients MUST treat a value they do not recognize as
2475    /// `saved`.
2476    #[serde(untagged)]
2477    Other(String),
2478}
2479
2480/// **UNSTABLE**
2481///
2482/// This capability is not part of the spec yet, and may be removed or changed at any point.
2483///
2484/// Request parameters for `session/options`, which returns the config options a session
2485/// would start with, without creating or resuming a session.
2486///
2487/// Only available if the Agent supports the `session.options` capability.
2488///
2489/// `session/options` MUST NOT create or resume a session, send `session/update`
2490/// notifications, add an entry to `session/list`, or change an existing session. Agents
2491/// SHOULD NOT connect to MCP servers to answer it. Agents MAY start their runtime to resolve
2492/// the options. The rules above still hold for it.
2493#[cfg(feature = "unstable_session_options")]
2494#[serde_as]
2495#[skip_serializing_none]
2496#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2497#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2498#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_OPTIONS_METHOD_NAME)))]
2499#[serde(rename_all = "camelCase")]
2500#[non_exhaustive]
2501pub struct SessionOptionsRequest {
2502    /// The working directory to resolve options for. Must be an absolute path.
2503    pub cwd: AbsolutePath,
2504    /// Additional workspace roots to resolve options for. Each path must be absolute.
2505    ///
2506    /// Optional. Omitted and `null` are equivalent to an empty list.
2507    #[serde_as(deserialize_as = "DefaultOnNull")]
2508    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
2509    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2510    pub additional_directories: Vec<AbsolutePath>,
2511    /// The session to resolve options for.
2512    ///
2513    /// Optional. Omitted and `null` are equivalent and mean a new session. When present,
2514    /// the Agent returns what `session/resume` with the same `cwd` and
2515    /// `additionalDirectories` would return, with the same `cwd` rules. A session the
2516    /// Agent does not know gets `-32002`.
2517    #[serde(default)]
2518    pub session_id: Option<SessionId>,
2519    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2520    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2521    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2522    ///
2523    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2524    #[serde_as(deserialize_as = "DefaultOnError")]
2525    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2526    #[serde(default)]
2527    #[serde(rename = "_meta")]
2528    pub meta: Option<Meta>,
2529}
2530
2531#[cfg(feature = "unstable_session_options")]
2532impl SessionOptionsRequest {
2533    /// Builds [`SessionOptionsRequest`] with the required request fields set. Optional fields start unset or empty.
2534    #[must_use]
2535    pub fn new(cwd: impl Into<AbsolutePath>) -> Self {
2536        Self {
2537            cwd: cwd.into(),
2538            additional_directories: vec![],
2539            session_id: None,
2540            meta: None,
2541        }
2542    }
2543
2544    /// Additional workspace roots to resolve options for. Each path must be absolute.
2545    #[must_use]
2546    pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
2547    where
2548        I: IntoIterator<Item = P>,
2549        P: Into<AbsolutePath>,
2550    {
2551        self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
2552        self
2553    }
2554
2555    /// The session to resolve options for. Unset means a new session.
2556    #[must_use]
2557    pub fn session_id(mut self, session_id: impl IntoOption<SessionId>) -> Self {
2558        self.session_id = session_id.into_option();
2559        self
2560    }
2561
2562    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2563    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2564    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2565    ///
2566    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2567    #[must_use]
2568    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2569        self.meta = meta.into_option();
2570        self
2571    }
2572}
2573
2574#[cfg(feature = "unstable_session_options")]
2575crate::serde_util::default_on_null! {
2576    /// **UNSTABLE**
2577    ///
2578    /// This capability is not part of the spec yet, and may be removed or changed at any point.
2579    ///
2580    /// Response from `session/options`.
2581    ///
2582    /// The result is a snapshot. The options a session actually starts with are the ones in
2583    /// the session setup response.
2584    #[serde_as]
2585    #[skip_serializing_none]
2586    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2587    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2588    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_OPTIONS_METHOD_NAME)))]
2589    #[serde(rename_all = "camelCase")]
2590    #[non_exhaustive]
2591    pub struct SessionOptionsResponse {
2592        /// The config options the session would start with, with the same rules as on
2593        /// `NewSessionResponse`.
2594        ///
2595        /// Optional. Omitted or empty means no config options are advertised.
2596        /// Senders MUST use an array, not `null`. Receivers treat `null` like omission.
2597        #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2598        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2599        #[serde(default, skip_serializing_if = "Vec::is_empty")]
2600        pub config_options: Vec<SessionConfigOption>,
2601        /// Commands the Agent knows the session would have.
2602        ///
2603        /// Optional. Omitted or empty means no commands are advertised.
2604        /// Senders MUST use an array, not `null`. Receivers treat `null` like omission.
2605        ///
2606        /// Advisory. Agents MAY return a partial list. Clients MUST use the commands from the
2607        /// `session/new` or `session/resume` response and later `available_commands_update`
2608        /// notifications for the session itself.
2609        #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2610        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2611        #[serde(default, skip_serializing_if = "Vec::is_empty")]
2612        pub available_commands: Vec<AvailableCommand>,
2613        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2614        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2615        /// Implementations MUST NOT assign meaning to keys they do not recognize.
2616        ///
2617        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2618        #[serde_as(deserialize_as = "DefaultOnError")]
2619        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2620        #[serde(default)]
2621        #[serde(rename = "_meta")]
2622        pub meta: Option<Meta>,
2623    }
2624}
2625
2626#[cfg(feature = "unstable_session_options")]
2627impl SessionOptionsResponse {
2628    /// Builds [`SessionOptionsResponse`] with the required response fields set. Optional fields start unset or empty.
2629    #[must_use]
2630    pub fn new() -> Self {
2631        Self::default()
2632    }
2633
2634    /// The config options the session would start with.
2635    #[must_use]
2636    pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
2637        self.config_options = config_options;
2638        self
2639    }
2640
2641    /// Commands the Agent knows the session would have. Advisory.
2642    #[must_use]
2643    pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
2644        self.available_commands = available_commands;
2645        self
2646    }
2647
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    #[must_use]
2654    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2655        self.meta = meta.into_option();
2656        self
2657    }
2658}
2659
2660/// **UNSTABLE**
2661///
2662/// This capability is not part of the spec yet, and may be removed or changed at any point.
2663///
2664/// An initial value for a config option, sent on session setup requests.
2665///
2666/// Same shape as `session/set_config_option` without `sessionId`. Unlike
2667/// `session/set_config_option`, an unknown `configId`, a `type` that does not match the
2668/// option, or a value that is not allowed is ignored instead of rejected.
2669#[cfg(feature = "unstable_session_options")]
2670#[serde_as]
2671#[skip_serializing_none]
2672#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2673#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2674#[serde(rename_all = "camelCase")]
2675#[non_exhaustive]
2676pub struct InitialSessionConfigOption {
2677    /// The ID of the configuration option to set.
2678    pub config_id: SessionConfigId,
2679    /// The value to set, including a `type` discriminator and the raw `value`.
2680    ///
2681    /// Payloads must send `type: "id"` for id-based options. A value `type` the Agent
2682    /// does not support fails the request with `-32602`.
2683    #[serde(flatten)]
2684    pub value: SessionConfigOptionValue,
2685    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2686    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2687    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2688    ///
2689    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2690    #[serde_as(deserialize_as = "DefaultOnError")]
2691    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2692    #[serde(default)]
2693    #[serde(rename = "_meta")]
2694    pub meta: Option<Meta>,
2695}
2696
2697#[cfg(feature = "unstable_session_options")]
2698impl InitialSessionConfigOption {
2699    /// Builds [`InitialSessionConfigOption`] with the required fields set. Optional fields start unset or empty.
2700    #[must_use]
2701    pub fn new(
2702        config_id: impl Into<SessionConfigId>,
2703        value: impl Into<SessionConfigOptionValue>,
2704    ) -> Self {
2705        Self {
2706            config_id: config_id.into(),
2707            value: value.into(),
2708            meta: None,
2709        }
2710    }
2711
2712    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2713    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2714    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2715    ///
2716    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2717    #[must_use]
2718    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2719        self.meta = meta.into_option();
2720        self
2721    }
2722}
2723
2724// Cancel tool call
2725
2726/// Request parameters for cancelling one tool call.
2727///
2728/// Clients MUST NOT send it unless the tool call currently advertises `capabilities.cancel`.
2729///
2730/// The Agent responds once it has accepted the cancellation. The response does not mean
2731/// the work has stopped. The Agent confirms it with a `tool_call_update` to a final
2732/// status: normally `cancelled`, or `completed` or `failed` if the work finished first.
2733///
2734/// The Agent responds with `-32602` if the tool call is unknown, already final, or not
2735/// cancellable. Cancelling a tool call does not change the foreground state by itself.
2736///
2737/// See protocol docs: [Cancelling Tool Calls](https://agentclientprotocol.com/protocol/v2/tool-calls#cancelling-tool-calls)
2738#[serde_as]
2739#[skip_serializing_none]
2740#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2741#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2742#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TOOL_CALL_CANCEL_METHOD_NAME)))]
2743#[serde(rename_all = "camelCase")]
2744#[non_exhaustive]
2745pub struct CancelToolCallRequest {
2746    /// The ID of the session that owns the tool call.
2747    pub session_id: SessionId,
2748    /// The ID of the tool call to cancel.
2749    pub tool_call_id: ToolCallId,
2750    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2751    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2752    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2753    ///
2754    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2755    #[serde_as(deserialize_as = "DefaultOnError")]
2756    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2757    #[serde(default)]
2758    #[serde(rename = "_meta")]
2759    pub meta: Option<Meta>,
2760}
2761
2762impl CancelToolCallRequest {
2763    /// Builds [`CancelToolCallRequest`] with the required request fields set. Optional fields start unset or empty.
2764    #[must_use]
2765    pub fn new(session_id: impl Into<SessionId>, tool_call_id: impl Into<ToolCallId>) -> Self {
2766        Self {
2767            session_id: session_id.into(),
2768            tool_call_id: tool_call_id.into(),
2769            meta: None,
2770        }
2771    }
2772
2773    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2774    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2775    /// do not recognize.
2776    ///
2777    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2778    #[must_use]
2779    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2780        self.meta = meta.into_option();
2781        self
2782    }
2783}
2784
2785crate::serde_util::default_on_null! {
2786    /// Response from cancelling a tool call.
2787    #[serde_as]
2788    #[skip_serializing_none]
2789    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2790    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2791    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TOOL_CALL_CANCEL_METHOD_NAME)))]
2792    #[serde(rename_all = "camelCase")]
2793    #[non_exhaustive]
2794    pub struct CancelToolCallResponse {
2795        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2796        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2797        /// Implementations MUST NOT assign meaning to keys they do not recognize.
2798        ///
2799        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2800        #[serde_as(deserialize_as = "DefaultOnError")]
2801        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2802        #[serde(default)]
2803        #[serde(rename = "_meta")]
2804        pub meta: Option<Meta>,
2805    }
2806}
2807
2808impl CancelToolCallResponse {
2809    /// Builds [`CancelToolCallResponse`] with the required response fields set. Optional fields start unset or empty.
2810    #[must_use]
2811    pub fn new() -> Self {
2812        Self::default()
2813    }
2814
2815    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2816    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2817    /// do not recognize.
2818    ///
2819    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2820    #[must_use]
2821    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2822        self.meta = meta.into_option();
2823        self
2824    }
2825}
2826
2827// Cancel terminal
2828
2829/// Request parameters for cancelling one terminal.
2830///
2831/// Clients MUST NOT send it unless the terminal currently advertises `capabilities.cancel`.
2832///
2833/// The Agent responds once it has accepted the cancellation. The response does not mean
2834/// the work has stopped. The Agent confirms it with a `terminal_update` that sets
2835/// `exitStatus`. Cancelling stops the process but does not release the terminal, and does
2836/// not change the status of a tool call that references it.
2837///
2838/// The Agent responds with `-32602` if the terminal is unknown, has already exited, or is not
2839/// cancellable. Cancelling a terminal does not change the foreground state by itself.
2840///
2841/// See protocol docs: [Cancelling Terminals](https://agentclientprotocol.com/protocol/v2/tool-calls#cancelling-terminals)
2842#[serde_as]
2843#[skip_serializing_none]
2844#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2845#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2846#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TERMINAL_CANCEL_METHOD_NAME)))]
2847#[serde(rename_all = "camelCase")]
2848#[non_exhaustive]
2849pub struct CancelTerminalRequest {
2850    /// The ID of the session that owns the terminal.
2851    pub session_id: SessionId,
2852    /// The ID of the terminal to cancel.
2853    pub terminal_id: TerminalId,
2854    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2855    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2856    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2857    ///
2858    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2859    #[serde_as(deserialize_as = "DefaultOnError")]
2860    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2861    #[serde(default)]
2862    #[serde(rename = "_meta")]
2863    pub meta: Option<Meta>,
2864}
2865
2866impl CancelTerminalRequest {
2867    /// Builds [`CancelTerminalRequest`] with the required request fields set. Optional fields start unset or empty.
2868    #[must_use]
2869    pub fn new(session_id: impl Into<SessionId>, terminal_id: impl Into<TerminalId>) -> Self {
2870        Self {
2871            session_id: session_id.into(),
2872            terminal_id: terminal_id.into(),
2873            meta: None,
2874        }
2875    }
2876
2877    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2878    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2879    /// do not recognize.
2880    ///
2881    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2882    #[must_use]
2883    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2884        self.meta = meta.into_option();
2885        self
2886    }
2887}
2888
2889crate::serde_util::default_on_null! {
2890    /// Response from cancelling a terminal.
2891    #[serde_as]
2892    #[skip_serializing_none]
2893    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2894    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2895    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TERMINAL_CANCEL_METHOD_NAME)))]
2896    #[serde(rename_all = "camelCase")]
2897    #[non_exhaustive]
2898    pub struct CancelTerminalResponse {
2899        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2900        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2901        /// Implementations MUST NOT assign meaning to keys they do not recognize.
2902        ///
2903        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2904        #[serde_as(deserialize_as = "DefaultOnError")]
2905        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2906        #[serde(default)]
2907        #[serde(rename = "_meta")]
2908        pub meta: Option<Meta>,
2909    }
2910}
2911
2912impl CancelTerminalResponse {
2913    /// Builds [`CancelTerminalResponse`] with the required response fields set. Optional fields start unset or empty.
2914    #[must_use]
2915    pub fn new() -> Self {
2916        Self::default()
2917    }
2918
2919    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2920    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2921    /// do not recognize.
2922    ///
2923    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2924    #[must_use]
2925    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2926        self.meta = meta.into_option();
2927        self
2928    }
2929}
2930
2931// List sessions
2932
2933/// An opaque cursor used to paginate `session/list` results.
2934#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2935#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
2936#[serde(transparent)]
2937#[from(Arc<str>, String, &str, &mut str, Box<str>, Cow<'_, str>)]
2938#[non_exhaustive]
2939pub struct SessionListCursor(pub Arc<str>);
2940
2941impl SessionListCursor {
2942    /// Wraps a protocol string as a typed [`SessionListCursor`].
2943    #[must_use]
2944    pub fn new(cursor: impl Into<Self>) -> Self {
2945        cursor.into()
2946    }
2947}
2948
2949impl AsRef<str> for SessionListCursor {
2950    fn as_ref(&self) -> &str {
2951        &self.0
2952    }
2953}
2954
2955impl From<&String> for SessionListCursor {
2956    fn from(cursor: &String) -> Self {
2957        Self(cursor.as_str().into())
2958    }
2959}
2960
2961macro_rules! impl_session_list_cursor_option_conversion {
2962    ($source:ty) => {
2963        impl IntoOption<SessionListCursor> for $source {
2964            fn into_option(self) -> Option<SessionListCursor> {
2965                Some(self.into())
2966            }
2967        }
2968    };
2969}
2970
2971impl_session_list_cursor_option_conversion!(Arc<str>);
2972impl_session_list_cursor_option_conversion!(String);
2973impl_session_list_cursor_option_conversion!(&str);
2974impl_session_list_cursor_option_conversion!(&mut str);
2975impl_session_list_cursor_option_conversion!(&String);
2976impl_session_list_cursor_option_conversion!(Box<str>);
2977impl_session_list_cursor_option_conversion!(Cow<'_, str>);
2978
2979crate::serde_util::default_on_null! {
2980    /// Request parameters for listing existing sessions.
2981    #[serde_as]
2982    #[skip_serializing_none]
2983    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2984    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2985    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_LIST_METHOD_NAME)))]
2986    #[serde(rename_all = "camelCase")]
2987    #[non_exhaustive]
2988    pub struct ListSessionsRequest {
2989        /// Filter sessions by working directory. Must be an absolute path.
2990        ///
2991        /// Only sessions whose `cwd` is this same directory match. Subdirectories and
2992        /// `additionalDirectories` don't. Agents MAY normalize paths when comparing.
2993        ///
2994        /// Omitted and `null` are equivalent and mean sessions are not filtered by working directory.
2995        #[serde(default)]
2996        pub cwd: Option<AbsolutePath>,
2997        /// Opaque cursor token from a previous response's nextCursor field for cursor-based pagination
2998        ///
2999        /// Omitted and `null` are equivalent and mean the first page is requested.
3000        #[serde(default)]
3001        pub cursor: Option<SessionListCursor>,
3002        /// **UNSTABLE**
3003        ///
3004        /// This capability is not part of the spec yet, and may be removed or changed at any point.
3005        ///
3006        /// Filter sessions by archive state.
3007        ///
3008        /// Optional. Omitted and `null` are equivalent and mean `exclude`. Only send this when
3009        /// the Agent advertises the `session.archive` capability. The filter combines with `cwd` and
3010        /// applies before pagination. Clients keep the same value when following `nextCursor`.
3011        #[cfg(feature = "unstable_session_archive")]
3012        #[serde(default)]
3013        pub archived: Option<SessionArchiveFilter>,
3014        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3015        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3016        /// Implementations MUST NOT assign meaning to keys they do not recognize.
3017        ///
3018        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3019        #[serde_as(deserialize_as = "DefaultOnError")]
3020        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3021        #[serde(default)]
3022        #[serde(rename = "_meta")]
3023        pub meta: Option<Meta>,
3024    }
3025}
3026
3027impl ListSessionsRequest {
3028    /// Builds [`ListSessionsRequest`] with the required request fields set. Optional fields start unset or empty.
3029    #[must_use]
3030    pub fn new() -> Self {
3031        Self::default()
3032    }
3033
3034    /// Filter sessions by working directory. Must be an absolute path.
3035    #[must_use]
3036    pub fn cwd(mut self, cwd: impl IntoOption<AbsolutePath>) -> Self {
3037        self.cwd = cwd.into_option();
3038        self
3039    }
3040
3041    /// Opaque cursor token from a previous response's nextCursor field for cursor-based pagination
3042    #[must_use]
3043    pub fn cursor(mut self, cursor: impl IntoOption<SessionListCursor>) -> Self {
3044        self.cursor = cursor.into_option();
3045        self
3046    }
3047
3048    /// **UNSTABLE**
3049    ///
3050    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3051    ///
3052    /// Filter sessions by archive state.
3053    #[cfg(feature = "unstable_session_archive")]
3054    #[must_use]
3055    pub fn archived(mut self, archived: impl IntoOption<SessionArchiveFilter>) -> Self {
3056        self.archived = archived.into_option();
3057        self
3058    }
3059
3060    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3061    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3062    /// do not recognize.
3063    ///
3064    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3065    #[must_use]
3066    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3067        self.meta = meta.into_option();
3068        self
3069    }
3070}
3071
3072/// Response from listing sessions.
3073#[serde_as]
3074#[skip_serializing_none]
3075#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3076#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3077#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_LIST_METHOD_NAME)))]
3078#[serde(rename_all = "camelCase")]
3079#[non_exhaustive]
3080pub struct ListSessionsResponse {
3081    /// Array of session information objects.
3082    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
3083    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3084    pub sessions: Vec<SessionInfo>,
3085    /// Opaque cursor token. If present, pass this in the next request's cursor parameter
3086    /// to fetch the next page. Omitted and `null` are equivalent and mean there are no more
3087    /// results. An empty string is a valid cursor, not the end of results.
3088    #[serde(default)]
3089    pub next_cursor: Option<SessionListCursor>,
3090    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3091    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3092    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3093    ///
3094    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3095    #[serde_as(deserialize_as = "DefaultOnError")]
3096    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3097    #[serde(default)]
3098    #[serde(rename = "_meta")]
3099    pub meta: Option<Meta>,
3100}
3101
3102impl ListSessionsResponse {
3103    /// Builds [`ListSessionsResponse`] with the required response fields set. Optional fields start unset or empty.
3104    #[must_use]
3105    pub fn new(sessions: Vec<SessionInfo>) -> Self {
3106        Self {
3107            sessions,
3108            next_cursor: None,
3109            meta: None,
3110        }
3111    }
3112
3113    /// Sets or clears the optional `nextCursor` field.
3114    #[must_use]
3115    pub fn next_cursor(mut self, next_cursor: impl IntoOption<SessionListCursor>) -> Self {
3116        self.next_cursor = next_cursor.into_option();
3117        self
3118    }
3119
3120    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3121    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3122    /// do not recognize.
3123    ///
3124    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3125    #[must_use]
3126    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3127        self.meta = meta.into_option();
3128        self
3129    }
3130}
3131
3132// Delete session
3133
3134/// Request parameters for deleting an existing session from `session/list`.
3135///
3136/// Only available if the Agent supports the `session.delete` capability.
3137#[serde_as]
3138#[skip_serializing_none]
3139#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3140#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3141#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_DELETE_METHOD_NAME)))]
3142#[serde(rename_all = "camelCase")]
3143#[non_exhaustive]
3144pub struct DeleteSessionRequest {
3145    /// The ID of the session to delete.
3146    pub session_id: SessionId,
3147    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3148    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3149    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3150    ///
3151    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3152    #[serde_as(deserialize_as = "DefaultOnError")]
3153    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3154    #[serde(default)]
3155    #[serde(rename = "_meta")]
3156    pub meta: Option<Meta>,
3157}
3158
3159impl DeleteSessionRequest {
3160    /// Builds [`DeleteSessionRequest`] with the required request fields set. Optional fields start unset or empty.
3161    #[must_use]
3162    pub fn new(session_id: impl Into<SessionId>) -> Self {
3163        Self {
3164            session_id: session_id.into(),
3165            meta: None,
3166        }
3167    }
3168
3169    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3170    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3171    /// do not recognize.
3172    ///
3173    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3174    #[must_use]
3175    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3176        self.meta = meta.into_option();
3177        self
3178    }
3179}
3180
3181crate::serde_util::default_on_null! {
3182    /// Response from deleting a session.
3183    #[serde_as]
3184    #[skip_serializing_none]
3185    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3186    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3187    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_DELETE_METHOD_NAME)))]
3188    #[serde(rename_all = "camelCase")]
3189    #[non_exhaustive]
3190    pub struct DeleteSessionResponse {
3191        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3192        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3193        /// Implementations MUST NOT assign meaning to keys they do not recognize.
3194        ///
3195        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3196        #[serde_as(deserialize_as = "DefaultOnError")]
3197        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3198        #[serde(default)]
3199        #[serde(rename = "_meta")]
3200        pub meta: Option<Meta>,
3201    }
3202}
3203
3204impl DeleteSessionResponse {
3205    /// Builds [`DeleteSessionResponse`] with the required response fields set. Optional fields start unset or empty.
3206    #[must_use]
3207    pub fn new() -> Self {
3208        Self::default()
3209    }
3210
3211    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3212    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3213    /// do not recognize.
3214    ///
3215    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3216    #[must_use]
3217    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3218        self.meta = meta.into_option();
3219        self
3220    }
3221}
3222
3223// Archive session
3224
3225/// **UNSTABLE**
3226///
3227/// This capability is not part of the spec yet, and may be removed or changed at any point.
3228///
3229/// Request parameters for archiving a session.
3230///
3231/// Only available if the Agent supports the `session.archive` capability.
3232///
3233/// Archiving hides the session from default `session/list` results. It keeps the session ID
3234/// and saved history. If the session is active, the Agent MUST cancel any ongoing work and
3235/// free the session's resources as if `session/close` had been called, then archive it.
3236/// Archiving an archived session succeeds. A session that does not exist gets `-32002`.
3237///
3238#[cfg(feature = "unstable_session_archive")]
3239#[serde_as]
3240#[skip_serializing_none]
3241#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3242#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3243#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_ARCHIVE_METHOD_NAME)))]
3244#[serde(rename_all = "camelCase")]
3245#[non_exhaustive]
3246pub struct ArchiveSessionRequest {
3247    /// The ID of the session to archive.
3248    pub session_id: SessionId,
3249    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3250    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3251    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3252    ///
3253    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3254    #[serde_as(deserialize_as = "DefaultOnError")]
3255    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3256    #[serde(default)]
3257    #[serde(rename = "_meta")]
3258    pub meta: Option<Meta>,
3259}
3260
3261#[cfg(feature = "unstable_session_archive")]
3262impl ArchiveSessionRequest {
3263    /// Builds [`ArchiveSessionRequest`] with the required request fields set. Optional fields start unset or empty.
3264    #[must_use]
3265    pub fn new(session_id: impl Into<SessionId>) -> Self {
3266        Self {
3267            session_id: session_id.into(),
3268            meta: None,
3269        }
3270    }
3271
3272    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3273    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3274    /// do not recognize.
3275    ///
3276    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3277    #[must_use]
3278    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3279        self.meta = meta.into_option();
3280        self
3281    }
3282}
3283
3284#[cfg(feature = "unstable_session_archive")]
3285crate::serde_util::default_on_null! {
3286    /// **UNSTABLE**
3287    ///
3288    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3289    ///
3290    /// Response from archiving a session.
3291    #[serde_as]
3292    #[skip_serializing_none]
3293    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3294    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3295    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_ARCHIVE_METHOD_NAME)))]
3296    #[serde(rename_all = "camelCase")]
3297    #[non_exhaustive]
3298    pub struct ArchiveSessionResponse {
3299        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3300        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3301        /// Implementations MUST NOT assign meaning to keys they do not recognize.
3302        ///
3303        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3304        #[serde_as(deserialize_as = "DefaultOnError")]
3305        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3306        #[serde(default)]
3307        #[serde(rename = "_meta")]
3308        pub meta: Option<Meta>,
3309    }
3310}
3311
3312#[cfg(feature = "unstable_session_archive")]
3313impl ArchiveSessionResponse {
3314    /// Builds [`ArchiveSessionResponse`] with the required response fields set. Optional fields start unset or empty.
3315    #[must_use]
3316    pub fn new() -> Self {
3317        Self::default()
3318    }
3319
3320    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3321    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3322    /// do not recognize.
3323    ///
3324    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3325    #[must_use]
3326    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3327        self.meta = meta.into_option();
3328        self
3329    }
3330}
3331
3332/// **UNSTABLE**
3333///
3334/// This capability is not part of the spec yet, and may be removed or changed at any point.
3335///
3336/// Request parameters for unarchiving a session.
3337///
3338/// Only available if the Agent supports the `session.archive` capability.
3339///
3340/// Unarchiving returns the session to default `session/list` results with the same ID and
3341/// saved history. It never loads or resumes the session. Clients that want to continue an
3342/// archived session SHOULD unarchive it before calling `session/resume`.
3343/// Unarchiving a session that is not archived succeeds. A session that does not exist
3344/// gets `-32002`.
3345///
3346#[cfg(feature = "unstable_session_archive")]
3347#[serde_as]
3348#[skip_serializing_none]
3349#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3350#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3351#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_UNARCHIVE_METHOD_NAME)))]
3352#[serde(rename_all = "camelCase")]
3353#[non_exhaustive]
3354pub struct UnarchiveSessionRequest {
3355    /// The ID of the session to unarchive.
3356    pub session_id: SessionId,
3357    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3358    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3359    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3360    ///
3361    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3362    #[serde_as(deserialize_as = "DefaultOnError")]
3363    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3364    #[serde(default)]
3365    #[serde(rename = "_meta")]
3366    pub meta: Option<Meta>,
3367}
3368
3369#[cfg(feature = "unstable_session_archive")]
3370impl UnarchiveSessionRequest {
3371    /// Builds [`UnarchiveSessionRequest`] with the required request fields set. Optional fields start unset or empty.
3372    #[must_use]
3373    pub fn new(session_id: impl Into<SessionId>) -> Self {
3374        Self {
3375            session_id: session_id.into(),
3376            meta: None,
3377        }
3378    }
3379
3380    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3381    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3382    /// do not recognize.
3383    ///
3384    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3385    #[must_use]
3386    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3387        self.meta = meta.into_option();
3388        self
3389    }
3390}
3391
3392#[cfg(feature = "unstable_session_archive")]
3393crate::serde_util::default_on_null! {
3394    /// **UNSTABLE**
3395    ///
3396    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3397    ///
3398    /// Response from unarchiving a session.
3399    #[serde_as]
3400    #[skip_serializing_none]
3401    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3402    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3403    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_UNARCHIVE_METHOD_NAME)))]
3404    #[serde(rename_all = "camelCase")]
3405    #[non_exhaustive]
3406    pub struct UnarchiveSessionResponse {
3407        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3408        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3409        /// Implementations MUST NOT assign meaning to keys they do not recognize.
3410        ///
3411        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3412        #[serde_as(deserialize_as = "DefaultOnError")]
3413        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3414        #[serde(default)]
3415        #[serde(rename = "_meta")]
3416        pub meta: Option<Meta>,
3417    }
3418}
3419
3420#[cfg(feature = "unstable_session_archive")]
3421impl UnarchiveSessionResponse {
3422    /// Builds [`UnarchiveSessionResponse`] with the required response fields set. Optional fields start unset or empty.
3423    #[must_use]
3424    pub fn new() -> Self {
3425        Self::default()
3426    }
3427
3428    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3429    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3430    /// do not recognize.
3431    ///
3432    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3433    #[must_use]
3434    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3435        self.meta = meta.into_option();
3436        self
3437    }
3438}
3439
3440/// **UNSTABLE**
3441///
3442/// This capability is not part of the spec yet, and may be removed or changed at any point.
3443///
3444/// Which sessions `session/list` returns based on their archive state.
3445///
3446/// Unknown values are preserved so they can be stored, proxied, or forwarded. An Agent MUST
3447/// return `-32602` for a value it does not support rather than treating it as `exclude`.
3448#[cfg(feature = "unstable_session_archive")]
3449#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3450#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
3451#[serde(rename_all = "snake_case")]
3452#[non_exhaustive]
3453pub enum SessionArchiveFilter {
3454    /// Only sessions that are not archived. This is the default.
3455    #[default]
3456    Exclude,
3457    /// Both archived sessions and sessions that are not archived.
3458    Include,
3459    /// Only archived sessions.
3460    Only,
3461    /// Custom or future archive filter.
3462    ///
3463    /// Values beginning with `_` are reserved for implementation-specific
3464    /// extensions. Unknown values that do not begin with `_` are reserved for
3465    /// future ACP variants.
3466    #[serde(untagged)]
3467    Other(String),
3468}
3469
3470/// Information about a session returned by session/list
3471#[serde_as]
3472#[skip_serializing_none]
3473#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3474#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3475#[serde(rename_all = "camelCase")]
3476#[non_exhaustive]
3477pub struct SessionInfo {
3478    /// Unique identifier for the session
3479    pub session_id: SessionId,
3480    /// The working directory for this session. Must be an absolute path.
3481    pub cwd: AbsolutePath,
3482    /// Additional workspace roots reported for this session. Each path must be absolute.
3483    ///
3484    /// When present, this is the complete ordered additional-root list reported
3485    /// by the Agent. Omitted and empty values are equivalent: the response
3486    /// reports no additional roots.
3487    #[serde_as(deserialize_as = "DefaultOnNull")]
3488    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
3489    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3490    pub additional_directories: Vec<AbsolutePath>,
3491
3492    /// Human-readable title for the session
3493    ///
3494    /// Omitted and `null` are equivalent and mean no title is provided.
3495    #[serde_as(deserialize_as = "DefaultOnError")]
3496    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3497    #[serde(default)]
3498    pub title: Option<String>,
3499    /// RFC 3339 timestamp of last activity.
3500    ///
3501    /// Omitted and `null` are equivalent and mean the last activity time is not reported.
3502    #[serde_as(deserialize_as = "DefaultOnError")]
3503    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "format" = "date-time")))]
3504    #[serde(default)]
3505    pub updated_at: Option<String>,
3506    /// **UNSTABLE**
3507    ///
3508    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3509    ///
3510    /// Whether the session is archived.
3511    ///
3512    /// Optional. Omitted and `null` are equivalent and mean the archive state is not reported.
3513    /// Agents that advertise the `session.archive` capability MUST include it on every listed session.
3514    #[cfg(feature = "unstable_session_archive")]
3515    #[serde_as(deserialize_as = "DefaultOnError")]
3516    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3517    #[serde(default)]
3518    pub archived: Option<bool>,
3519    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3520    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3521    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3522    ///
3523    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3524    #[serde_as(deserialize_as = "DefaultOnError")]
3525    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3526    #[serde(default)]
3527    #[serde(rename = "_meta")]
3528    pub meta: Option<Meta>,
3529}
3530
3531impl SessionInfo {
3532    /// Builds [`SessionInfo`] with the required fields set. Optional fields start unset or empty.
3533    #[must_use]
3534    pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
3535        Self {
3536            session_id: session_id.into(),
3537            cwd: cwd.into(),
3538            additional_directories: vec![],
3539            title: None,
3540            updated_at: None,
3541            #[cfg(feature = "unstable_session_archive")]
3542            archived: None,
3543            meta: None,
3544        }
3545    }
3546
3547    /// Additional workspace roots reported for this session. Each path must be absolute.
3548    #[must_use]
3549    pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
3550    where
3551        I: IntoIterator<Item = P>,
3552        P: Into<AbsolutePath>,
3553    {
3554        self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
3555        self
3556    }
3557
3558    /// Human-readable title for the session
3559    #[must_use]
3560    pub fn title(mut self, title: impl IntoOption<String>) -> Self {
3561        self.title = title.into_option();
3562        self
3563    }
3564
3565    /// RFC 3339 timestamp of last activity.
3566    #[must_use]
3567    pub fn updated_at(mut self, updated_at: impl IntoOption<String>) -> Self {
3568        self.updated_at = updated_at.into_option();
3569        self
3570    }
3571
3572    /// **UNSTABLE**
3573    ///
3574    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3575    ///
3576    /// Whether the session is archived.
3577    #[cfg(feature = "unstable_session_archive")]
3578    #[must_use]
3579    pub fn archived(mut self, archived: impl IntoOption<bool>) -> Self {
3580        self.archived = archived.into_option();
3581        self
3582    }
3583
3584    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3585    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3586    /// do not recognize.
3587    ///
3588    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3589    #[must_use]
3590    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3591        self.meta = meta.into_option();
3592        self
3593    }
3594}
3595
3596// Set session title
3597
3598/// **UNSTABLE**
3599///
3600/// This capability is not part of the spec yet, and may be removed or changed at any point.
3601///
3602/// Request parameters for setting the title of a session.
3603///
3604/// Only available if the Agent supports the `session.title` capability.
3605///
3606/// The session does not need to be active on the connection. Any session the Agent would
3607/// return from `session/list` can be retitled. A session that does not exist gets `-32002`.
3608///
3609/// The Agent responds only after it has stored the title. After a successful response, the
3610/// Agent SHOULD NOT replace the title with one it generates automatically.
3611#[cfg(feature = "unstable_session_set_title")]
3612#[serde_as]
3613#[skip_serializing_none]
3614#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3615#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3616#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_TITLE_METHOD_NAME)))]
3617#[serde(rename_all = "camelCase")]
3618#[non_exhaustive]
3619pub struct SetSessionTitleRequest {
3620    /// The ID of the session to retitle.
3621    pub session_id: SessionId,
3622    /// The new title for the session.
3623    ///
3624    /// Required and non-null. Omission and explicit `null` are both invalid. The Agent MAY
3625    /// normalize the title before storing it, for example by trimming whitespace or
3626    /// truncating it. The Agent rejects a title that fails its validation, including one
3627    /// that is empty after normalization, with `-32602`.
3628    pub title: String,
3629    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3630    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3631    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3632    ///
3633    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3634    #[serde_as(deserialize_as = "DefaultOnError")]
3635    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3636    #[serde(default)]
3637    #[serde(rename = "_meta")]
3638    pub meta: Option<Meta>,
3639}
3640
3641#[cfg(feature = "unstable_session_set_title")]
3642impl SetSessionTitleRequest {
3643    /// Builds [`SetSessionTitleRequest`] with the required request fields set. Optional fields start unset or empty.
3644    #[must_use]
3645    pub fn new(session_id: impl Into<SessionId>, title: impl Into<String>) -> Self {
3646        Self {
3647            session_id: session_id.into(),
3648            title: title.into(),
3649            meta: None,
3650        }
3651    }
3652
3653    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3654    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3655    /// do not recognize.
3656    ///
3657    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3658    #[must_use]
3659    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3660        self.meta = meta.into_option();
3661        self
3662    }
3663}
3664
3665/// **UNSTABLE**
3666///
3667/// This capability is not part of the spec yet, and may be removed or changed at any point.
3668///
3669/// Response from setting the title of a session.
3670#[cfg(feature = "unstable_session_set_title")]
3671#[serde_as]
3672#[skip_serializing_none]
3673#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3674#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3675#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_TITLE_METHOD_NAME)))]
3676#[serde(rename_all = "camelCase")]
3677#[non_exhaustive]
3678pub struct SetSessionTitleResponse {
3679    /// The title the Agent stored.
3680    ///
3681    /// This differs from the requested title if the Agent normalized it. Clients SHOULD
3682    /// display this value rather than the one they sent.
3683    pub title: String,
3684    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3685    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3686    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3687    ///
3688    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3689    #[serde_as(deserialize_as = "DefaultOnError")]
3690    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3691    #[serde(default)]
3692    #[serde(rename = "_meta")]
3693    pub meta: Option<Meta>,
3694}
3695
3696#[cfg(feature = "unstable_session_set_title")]
3697impl SetSessionTitleResponse {
3698    /// Builds [`SetSessionTitleResponse`] with the required response fields set. Optional fields start unset or empty.
3699    #[must_use]
3700    pub fn new(title: impl Into<String>) -> Self {
3701        Self {
3702            title: title.into(),
3703            meta: None,
3704        }
3705    }
3706
3707    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3708    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3709    /// do not recognize.
3710    ///
3711    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3712    #[must_use]
3713    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3714        self.meta = meta.into_option();
3715        self
3716    }
3717}
3718
3719// Session config options
3720
3721/// Unique identifier for a session configuration option.
3722#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3723#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3724#[serde(transparent)]
3725#[from(forward)]
3726#[non_exhaustive]
3727pub struct SessionConfigId(pub Arc<str>);
3728
3729impl SessionConfigId {
3730    /// Wraps a protocol string as a typed [`SessionConfigId`].
3731    #[must_use]
3732    pub fn new(id: impl Into<Self>) -> Self {
3733        id.into()
3734    }
3735}
3736
3737/// Unique identifier for a session configuration option value.
3738#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3739#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3740#[serde(transparent)]
3741#[from(forward)]
3742#[non_exhaustive]
3743pub struct SessionConfigValueId(pub Arc<str>);
3744
3745impl SessionConfigValueId {
3746    /// Wraps a protocol string as a typed [`SessionConfigValueId`].
3747    #[must_use]
3748    pub fn new(id: impl Into<Self>) -> Self {
3749        id.into()
3750    }
3751}
3752
3753/// Unique identifier for a session configuration option value group.
3754#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3755#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3756#[serde(transparent)]
3757#[from(forward)]
3758#[non_exhaustive]
3759pub struct SessionConfigGroupId(pub Arc<str>);
3760
3761impl SessionConfigGroupId {
3762    /// Wraps a protocol string as a typed [`SessionConfigGroupId`].
3763    #[must_use]
3764    pub fn new(id: impl Into<Self>) -> Self {
3765        id.into()
3766    }
3767}
3768
3769/// A possible value for a session configuration option.
3770#[serde_as]
3771#[skip_serializing_none]
3772#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3773#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3774#[serde(rename_all = "camelCase")]
3775#[non_exhaustive]
3776pub struct SessionConfigSelectOption {
3777    /// Unique identifier for this option value.
3778    pub value: SessionConfigValueId,
3779    /// Human-readable label for this option value.
3780    pub name: String,
3781    /// Optional description for this option value.
3782    ///
3783    /// Omitted and `null` are equivalent and mean no description is provided.
3784    #[serde_as(deserialize_as = "DefaultOnError")]
3785    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3786    #[serde(default)]
3787    pub description: Option<String>,
3788    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3789    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3790    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3791    ///
3792    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3793    #[serde_as(deserialize_as = "DefaultOnError")]
3794    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3795    #[serde(default)]
3796    #[serde(rename = "_meta")]
3797    pub meta: Option<Meta>,
3798}
3799
3800impl SessionConfigSelectOption {
3801    /// Builds [`SessionConfigSelectOption`] with the required fields set. Optional fields start unset or empty.
3802    #[must_use]
3803    pub fn new(value: impl Into<SessionConfigValueId>, name: impl Into<String>) -> Self {
3804        Self {
3805            value: value.into(),
3806            name: name.into(),
3807            description: None,
3808            meta: None,
3809        }
3810    }
3811
3812    /// Sets or clears the optional `description` field.
3813    #[must_use]
3814    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
3815        self.description = description.into_option();
3816        self
3817    }
3818
3819    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3820    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3821    /// do not recognize.
3822    ///
3823    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3824    #[must_use]
3825    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3826        self.meta = meta.into_option();
3827        self
3828    }
3829}
3830
3831/// A group of possible values for a session configuration option.
3832#[serde_as]
3833#[skip_serializing_none]
3834#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3835#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3836#[serde(rename_all = "camelCase")]
3837#[non_exhaustive]
3838pub struct SessionConfigSelectGroup {
3839    /// Unique identifier for this group.
3840    pub group_id: SessionConfigGroupId,
3841    /// Human-readable label for this group.
3842    pub name: String,
3843    /// The set of option values in this group. MUST contain at least one value.
3844    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
3845    #[cfg_attr(feature = "schemars", schemars(length(min = 1), extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3846    pub options: Vec<SessionConfigSelectOption>,
3847    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3848    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3849    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3850    ///
3851    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3852    #[serde_as(deserialize_as = "DefaultOnError")]
3853    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3854    #[serde(default)]
3855    #[serde(rename = "_meta")]
3856    pub meta: Option<Meta>,
3857}
3858
3859impl SessionConfigSelectGroup {
3860    /// Builds [`SessionConfigSelectGroup`] with the required fields set. Optional fields start unset or empty.
3861    #[must_use]
3862    pub fn new(
3863        group_id: impl Into<SessionConfigGroupId>,
3864        name: impl Into<String>,
3865        options: Vec<SessionConfigSelectOption>,
3866    ) -> Self {
3867        Self {
3868            group_id: group_id.into(),
3869            name: name.into(),
3870            options,
3871            meta: None,
3872        }
3873    }
3874
3875    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3876    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3877    /// do not recognize.
3878    ///
3879    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3880    #[must_use]
3881    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3882        self.meta = meta.into_option();
3883        self
3884    }
3885}
3886
3887/// Possible values for a session configuration option.
3888#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3889#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3890#[serde(untagged)]
3891#[non_exhaustive]
3892pub enum SessionConfigSelectOptions {
3893    /// A flat list of options with no grouping.
3894    Ungrouped(
3895        #[cfg_attr(feature = "schemars", schemars(length(min = 1)))] Vec<SessionConfigSelectOption>,
3896    ),
3897    /// A list of options grouped under headers.
3898    Grouped(
3899        #[cfg_attr(feature = "schemars", schemars(length(min = 1)))] Vec<SessionConfigSelectGroup>,
3900    ),
3901}
3902
3903impl From<Vec<SessionConfigSelectOption>> for SessionConfigSelectOptions {
3904    fn from(options: Vec<SessionConfigSelectOption>) -> Self {
3905        SessionConfigSelectOptions::Ungrouped(options)
3906    }
3907}
3908
3909impl From<Vec<SessionConfigSelectGroup>> for SessionConfigSelectOptions {
3910    fn from(groups: Vec<SessionConfigSelectGroup>) -> Self {
3911        SessionConfigSelectOptions::Grouped(groups)
3912    }
3913}
3914
3915/// A single-value selector (dropdown) session configuration option payload.
3916#[skip_serializing_none]
3917#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3918#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3919#[serde(rename_all = "camelCase")]
3920#[non_exhaustive]
3921pub struct SessionConfigSelect {
3922    /// The currently selected value. MUST be one of the `value`s in `options`.
3923    pub current_value: SessionConfigValueId,
3924    /// The set of selectable options. MUST contain at least one value, and each `value` MUST be
3925    /// unique within the option, including across groups.
3926    pub options: SessionConfigSelectOptions,
3927}
3928
3929impl SessionConfigSelect {
3930    /// Builds [`SessionConfigSelect`] with the required fields set. Optional fields start unset or empty.
3931    #[must_use]
3932    pub fn new(
3933        current_value: impl Into<SessionConfigValueId>,
3934        options: impl Into<SessionConfigSelectOptions>,
3935    ) -> Self {
3936        Self {
3937            current_value: current_value.into(),
3938            options: options.into(),
3939        }
3940    }
3941}
3942
3943/// A boolean on/off toggle session configuration option payload.
3944#[skip_serializing_none]
3945#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3946#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3947#[serde(rename_all = "camelCase")]
3948#[non_exhaustive]
3949pub struct SessionConfigBoolean {
3950    /// The current value of the boolean option.
3951    pub current_value: bool,
3952}
3953
3954impl SessionConfigBoolean {
3955    /// Builds [`SessionConfigBoolean`] with the required fields set. Optional fields start unset or empty.
3956    #[must_use]
3957    pub fn new(current_value: bool) -> Self {
3958        Self { current_value }
3959    }
3960}
3961
3962/// Semantic category for a session configuration option.
3963///
3964/// This is intended to help Clients distinguish broadly common selectors (e.g. model selector vs
3965/// session mode selector vs thought/reasoning level) for UX purposes (keyboard shortcuts, icons,
3966/// placement). It MUST NOT be required for correctness. Clients MUST handle missing or unknown
3967/// categories gracefully.
3968///
3969/// Category names beginning with `_` are free for custom use, like other ACP extension methods.
3970/// Category names that do not begin with `_` are reserved for the ACP spec.
3971#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3972#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3973#[serde(rename_all = "snake_case")]
3974#[non_exhaustive]
3975pub enum SessionConfigOptionCategory {
3976    /// Session mode selector.
3977    Mode,
3978    /// Model selector.
3979    Model,
3980    /// Model-related configuration parameter.
3981    ModelConfig,
3982    /// **UNSTABLE**
3983    ///
3984    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3985    ///
3986    /// Response speed selector, such as a fast mode toggle.
3987    #[cfg(feature = "unstable_speed_config_category")]
3988    Speed,
3989    /// Thought/reasoning level selector.
3990    ThoughtLevel,
3991    /// Custom or future category.
3992    ///
3993    /// Values beginning with `_` are reserved for implementation-specific
3994    /// extensions. Unknown values that do not begin with `_` are reserved for
3995    /// future ACP variants.
3996    #[serde(untagged)]
3997    Other(String),
3998}
3999
4000/// Type-specific session configuration option payload.
4001#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4002#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4003#[serde(tag = "type", rename_all = "snake_case")]
4004#[non_exhaustive]
4005pub enum SessionConfigKind {
4006    /// Single-value selector (dropdown).
4007    Select(SessionConfigSelect),
4008    /// Boolean on/off toggle.
4009    Boolean(SessionConfigBoolean),
4010    /// Custom or future session configuration option payload.
4011    ///
4012    /// Values beginning with `_` are reserved for implementation-specific
4013    /// extensions. Unknown values that do not begin with `_` are reserved for
4014    /// future ACP variants.
4015    ///
4016    /// Clients that do not understand this option type should preserve the raw
4017    /// payload when storing, replaying, proxying, or forwarding configuration
4018    /// data, and otherwise ignore the option. The Agent keeps using its `currentValue`.
4019    #[serde(untagged)]
4020    Other(OtherSessionConfigKind),
4021}
4022
4023/// Custom or future session configuration option payload.
4024#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4025#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4026#[cfg_attr(feature = "schemars", schemars(inline))]
4027#[cfg_attr(feature = "schemars", schemars(transform = other_session_config_kind_schema))]
4028#[serde(rename_all = "camelCase")]
4029#[non_exhaustive]
4030pub struct OtherSessionConfigKind {
4031    /// Custom or future session configuration option type.
4032    ///
4033    /// Values beginning with `_` are reserved for implementation-specific
4034    /// extensions. Unknown values that do not begin with `_` are reserved for
4035    /// future ACP variants.
4036    #[serde(rename = "type")]
4037    pub type_: String,
4038    /// Additional fields from the unknown session configuration option payload.
4039    #[serde(flatten)]
4040    pub fields: BTreeMap<String, serde_json::Value>,
4041}
4042
4043impl OtherSessionConfigKind {
4044    /// Builds [`OtherSessionConfigKind`] from an unknown discriminator and preserves the remaining extension fields.
4045    #[must_use]
4046    pub fn new(type_: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
4047        fields.remove("type");
4048        fields.remove("_meta");
4049        Self {
4050            type_: type_.into(),
4051            fields,
4052        }
4053    }
4054}
4055
4056impl<'de> Deserialize<'de> for OtherSessionConfigKind {
4057    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4058    where
4059        D: serde::Deserializer<'de>,
4060    {
4061        let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
4062        let type_ = fields
4063            .remove("type")
4064            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4065        let serde_json::Value::String(type_) = type_ else {
4066            return Err(serde::de::Error::custom("`type` must be a string"));
4067        };
4068
4069        if is_known_session_config_kind_type(&type_) {
4070            return Err(serde::de::Error::custom(format!(
4071                "known session configuration option `{type_}` did not match its schema"
4072            )));
4073        }
4074
4075        Ok(Self { type_, fields })
4076    }
4077}
4078
4079fn is_known_session_config_kind_type(type_: &str) -> bool {
4080    matches!(type_, "select" | "boolean")
4081}
4082
4083#[cfg(feature = "schemars")]
4084fn other_session_config_kind_schema(schema: &mut Schema) {
4085    super::schema_util::reject_known_string_discriminators(schema, "type", &["select", "boolean"]);
4086}
4087
4088/// A session configuration option selector and its current state.
4089#[serde_as]
4090#[skip_serializing_none]
4091#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4092#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4093#[serde(rename_all = "camelCase")]
4094#[non_exhaustive]
4095pub struct SessionConfigOption {
4096    /// Unique identifier for the configuration option.
4097    pub config_id: SessionConfigId,
4098    /// Human-readable label for the option.
4099    pub name: String,
4100    /// Optional description for the Client to display to the user.
4101    ///
4102    /// Omitted and `null` are equivalent and mean no description is provided.
4103    #[serde_as(deserialize_as = "DefaultOnError")]
4104    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4105    #[serde(default)]
4106    pub description: Option<String>,
4107    /// Optional semantic category for this option (UX only).
4108    ///
4109    /// Omitted and `null` are equivalent and mean no category is provided.
4110    #[serde_as(deserialize_as = "DefaultOnError")]
4111    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4112    #[serde(default)]
4113    pub category: Option<SessionConfigOptionCategory>,
4114    /// Type-specific fields for this configuration option.
4115    #[serde(flatten)]
4116    pub kind: SessionConfigKind,
4117    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4118    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4119    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4120    ///
4121    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4122    #[serde_as(deserialize_as = "DefaultOnError")]
4123    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4124    #[serde(default)]
4125    #[serde(rename = "_meta")]
4126    pub meta: Option<Meta>,
4127}
4128
4129impl SessionConfigOption {
4130    /// Builds [`SessionConfigOption`] with the required fields set. Optional fields start unset or empty.
4131    #[must_use]
4132    pub fn new(
4133        config_id: impl Into<SessionConfigId>,
4134        name: impl Into<String>,
4135        kind: SessionConfigKind,
4136    ) -> Self {
4137        Self {
4138            config_id: config_id.into(),
4139            name: name.into(),
4140            description: None,
4141            category: None,
4142            kind,
4143            meta: None,
4144        }
4145    }
4146
4147    /// Builds a select-style session configuration option with its current value and choices.
4148    #[must_use]
4149    pub fn select(
4150        config_id: impl Into<SessionConfigId>,
4151        name: impl Into<String>,
4152        current_value: impl Into<SessionConfigValueId>,
4153        options: impl Into<SessionConfigSelectOptions>,
4154    ) -> Self {
4155        Self::new(
4156            config_id,
4157            name,
4158            SessionConfigKind::Select(SessionConfigSelect::new(current_value, options)),
4159        )
4160    }
4161
4162    /// Builds a boolean-style session configuration option with its current value.
4163    #[must_use]
4164    pub fn boolean(
4165        config_id: impl Into<SessionConfigId>,
4166        name: impl Into<String>,
4167        current_value: bool,
4168    ) -> Self {
4169        Self::new(
4170            config_id,
4171            name,
4172            SessionConfigKind::Boolean(SessionConfigBoolean::new(current_value)),
4173        )
4174    }
4175
4176    /// Sets or clears the optional `description` field.
4177    #[must_use]
4178    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
4179        self.description = description.into_option();
4180        self
4181    }
4182
4183    /// Sets or clears the optional `category` field.
4184    #[must_use]
4185    pub fn category(mut self, category: impl IntoOption<SessionConfigOptionCategory>) -> Self {
4186        self.category = category.into_option();
4187        self
4188    }
4189
4190    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4191    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4192    /// do not recognize.
4193    ///
4194    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4195    #[must_use]
4196    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4197        self.meta = meta.into_option();
4198        self
4199    }
4200}
4201
4202/// The value to set for a session configuration option.
4203///
4204/// The `type` field acts as the discriminator in the serialized JSON form.
4205///
4206/// The `type` discriminator describes the *shape* of the value, not the option
4207/// kind. For example every option kind that picks from a list of ids
4208/// (`select`, `radio`, …) would use [`Id`](Self::Id), while a future freeform
4209/// text option would get its own variant.
4210#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4211#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4212#[serde(tag = "type", rename_all = "snake_case")]
4213#[non_exhaustive]
4214pub enum SessionConfigOptionValue {
4215    /// A `SessionConfigValueId` string value (`type: "id"`).
4216    Id {
4217        /// The value ID.
4218        value: SessionConfigValueId,
4219    },
4220    /// A boolean value (`type: "boolean"`).
4221    Boolean {
4222        /// The boolean value.
4223        value: bool,
4224    },
4225    /// Custom or future session configuration option value payload.
4226    ///
4227    /// Values beginning with `_` are reserved for implementation-specific
4228    /// extensions. Unknown values that do not begin with `_` are reserved for
4229    /// future ACP variants.
4230    ///
4231    /// Agents MUST reject a `session/set_config_option` request with a value type
4232    /// they do not support with `-32602`.
4233    #[serde(untagged)]
4234    Other(OtherSessionConfigOptionValue),
4235}
4236
4237/// Custom or future session configuration option value payload.
4238#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4239#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4240#[cfg_attr(feature = "schemars", schemars(inline))]
4241#[cfg_attr(feature = "schemars", schemars(transform = other_session_config_option_value_schema))]
4242#[serde(rename_all = "camelCase")]
4243#[non_exhaustive]
4244pub struct OtherSessionConfigOptionValue {
4245    /// Custom or future session configuration option value type.
4246    ///
4247    /// Values beginning with `_` are reserved for implementation-specific
4248    /// extensions. Unknown values that do not begin with `_` are reserved for
4249    /// future ACP variants.
4250    #[serde(rename = "type")]
4251    pub type_: String,
4252    /// Raw value payload for the custom or future value type.
4253    pub value: serde_json::Value,
4254    /// Additional fields from the unknown session configuration option value payload.
4255    #[serde(flatten)]
4256    pub fields: BTreeMap<String, serde_json::Value>,
4257}
4258
4259impl OtherSessionConfigOptionValue {
4260    /// Builds [`OtherSessionConfigOptionValue`] from an unknown discriminator and preserves the remaining extension fields.
4261    #[must_use]
4262    pub fn new(
4263        type_: impl Into<String>,
4264        value: serde_json::Value,
4265        mut fields: BTreeMap<String, serde_json::Value>,
4266    ) -> Self {
4267        fields.remove("type");
4268        fields.remove("value");
4269        fields.remove("_meta");
4270        Self {
4271            type_: type_.into(),
4272            value,
4273            fields,
4274        }
4275    }
4276}
4277
4278impl<'de> Deserialize<'de> for OtherSessionConfigOptionValue {
4279    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4280    where
4281        D: serde::Deserializer<'de>,
4282    {
4283        let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
4284        let type_ = fields
4285            .remove("type")
4286            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4287        let serde_json::Value::String(type_) = type_ else {
4288            return Err(serde::de::Error::custom("`type` must be a string"));
4289        };
4290
4291        if is_known_session_config_option_value_type(&type_) {
4292            return Err(serde::de::Error::custom(format!(
4293                "known session configuration option value `{type_}` did not match its schema"
4294            )));
4295        }
4296
4297        let value = fields
4298            .remove("value")
4299            .ok_or_else(|| serde::de::Error::missing_field("value"))?;
4300
4301        Ok(Self {
4302            type_,
4303            value,
4304            fields,
4305        })
4306    }
4307}
4308
4309impl<'de> Deserialize<'de> for SessionConfigOptionValue {
4310    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4311    where
4312        D: serde::Deserializer<'de>,
4313    {
4314        let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
4315        let type_ = fields.remove("type");
4316        let value = fields
4317            .remove("value")
4318            .ok_or_else(|| serde::de::Error::missing_field("value"))?;
4319
4320        let type_ = type_.ok_or_else(|| serde::de::Error::missing_field("type"))?;
4321
4322        let serde_json::Value::String(type_) = type_ else {
4323            return Err(serde::de::Error::custom("`type` must be a string"));
4324        };
4325
4326        match type_.as_str() {
4327            "id" => {
4328                let value = serde_json::from_value(value).map_err(|error| {
4329                    serde::de::Error::custom(format!(
4330                        "`value` must be a string for `type: id`: {error}"
4331                    ))
4332                })?;
4333                Ok(Self::Id { value })
4334            }
4335            "boolean" => {
4336                let value = serde_json::from_value(value).map_err(|error| {
4337                    serde::de::Error::custom(format!(
4338                        "`value` must be a boolean for `type: boolean`: {error}"
4339                    ))
4340                })?;
4341                Ok(Self::Boolean { value })
4342            }
4343            _ => Ok(Self::Other(OtherSessionConfigOptionValue {
4344                type_,
4345                value,
4346                fields,
4347            })),
4348        }
4349    }
4350}
4351
4352fn is_known_session_config_option_value_type(type_: &str) -> bool {
4353    matches!(type_, "id" | "boolean")
4354}
4355
4356#[cfg(feature = "schemars")]
4357fn other_session_config_option_value_schema(schema: &mut Schema) {
4358    super::schema_util::reject_known_string_discriminators(schema, "type", &["id", "boolean"]);
4359}
4360
4361impl SessionConfigOptionValue {
4362    /// Create an id option value (used by `select` and other id-based option types).
4363    #[must_use]
4364    pub fn id(id: impl Into<SessionConfigValueId>) -> Self {
4365        Self::Id { value: id.into() }
4366    }
4367
4368    /// Create a boolean option value.
4369    #[must_use]
4370    pub fn boolean(val: bool) -> Self {
4371        Self::Boolean { value: val }
4372    }
4373
4374    /// Return the inner [`SessionConfigValueId`] if this is a
4375    /// [`Id`](Self::Id) value.
4376    #[must_use]
4377    pub fn as_id(&self) -> Option<&SessionConfigValueId> {
4378        match self {
4379            Self::Id { value } => Some(value),
4380            _ => None,
4381        }
4382    }
4383
4384    /// Return the inner [`bool`] if this is a [`Boolean`](Self::Boolean) value.
4385    #[must_use]
4386    pub fn as_bool(&self) -> Option<bool> {
4387        match self {
4388            Self::Boolean { value } => Some(*value),
4389            _ => None,
4390        }
4391    }
4392}
4393
4394impl From<SessionConfigValueId> for SessionConfigOptionValue {
4395    fn from(value: SessionConfigValueId) -> Self {
4396        Self::Id { value }
4397    }
4398}
4399
4400impl From<bool> for SessionConfigOptionValue {
4401    fn from(value: bool) -> Self {
4402        Self::Boolean { value }
4403    }
4404}
4405
4406impl From<&str> for SessionConfigOptionValue {
4407    fn from(value: &str) -> Self {
4408        Self::Id {
4409            value: SessionConfigValueId::new(value),
4410        }
4411    }
4412}
4413
4414/// Request parameters for setting a session configuration option.
4415///
4416/// Agents MUST support this method for any session where they advertise config options.
4417/// Agents MUST reject an unknown `configId` or invalid value with `-32602` and leave the
4418/// configuration unchanged.
4419///
4420/// See protocol docs: [Session Config Options](https://agentclientprotocol.com/protocol/v2/session-config-options#setting-a-config-option)
4421#[serde_as]
4422#[skip_serializing_none]
4423#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4424#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4425#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_CONFIG_OPTION_METHOD_NAME)))]
4426#[serde(rename_all = "camelCase")]
4427#[non_exhaustive]
4428pub struct SetSessionConfigOptionRequest {
4429    /// The ID of the session to set the configuration option for.
4430    pub session_id: SessionId,
4431    /// The ID of the configuration option to set.
4432    pub config_id: SessionConfigId,
4433    /// The value to set, including a `type` discriminator and the raw `value`.
4434    ///
4435    /// Payloads must send `type: "id"` for id-based options.
4436    #[serde(flatten)]
4437    pub value: SessionConfigOptionValue,
4438    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4439    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4440    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4441    ///
4442    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4443    #[serde_as(deserialize_as = "DefaultOnError")]
4444    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4445    #[serde(default)]
4446    #[serde(rename = "_meta")]
4447    pub meta: Option<Meta>,
4448}
4449
4450impl SetSessionConfigOptionRequest {
4451    /// Builds [`SetSessionConfigOptionRequest`] with the required request fields set. Optional fields start unset or empty.
4452    #[must_use]
4453    pub fn new(
4454        session_id: impl Into<SessionId>,
4455        config_id: impl Into<SessionConfigId>,
4456        value: impl Into<SessionConfigOptionValue>,
4457    ) -> Self {
4458        Self {
4459            session_id: session_id.into(),
4460            config_id: config_id.into(),
4461            value: value.into(),
4462            meta: None,
4463        }
4464    }
4465
4466    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4467    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4468    /// do not recognize.
4469    ///
4470    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4471    #[must_use]
4472    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4473        self.meta = meta.into_option();
4474        self
4475    }
4476}
4477
4478/// Response to `session/set_config_option` method.
4479#[serde_as]
4480#[skip_serializing_none]
4481#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4482#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4483#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_CONFIG_OPTION_METHOD_NAME)))]
4484#[serde(rename_all = "camelCase")]
4485#[non_exhaustive]
4486pub struct SetSessionConfigOptionResponse {
4487    /// The full set of configuration options and their current values.
4488    #[serde_as(deserialize_as = "VecSkipError<_>")]
4489    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-skip-invalid-items" = true)))]
4490    pub config_options: Vec<SessionConfigOption>,
4491    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4492    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4493    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4494    ///
4495    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4496    #[serde_as(deserialize_as = "DefaultOnError")]
4497    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4498    #[serde(default)]
4499    #[serde(rename = "_meta")]
4500    pub meta: Option<Meta>,
4501}
4502
4503impl SetSessionConfigOptionResponse {
4504    /// Builds [`SetSessionConfigOptionResponse`] with the required response fields set. Optional fields start unset or empty.
4505    #[must_use]
4506    pub fn new(config_options: Vec<SessionConfigOption>) -> Self {
4507        Self {
4508            config_options,
4509            meta: None,
4510        }
4511    }
4512
4513    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4514    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4515    /// do not recognize.
4516    ///
4517    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4518    #[must_use]
4519    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4520        self.meta = meta.into_option();
4521        self
4522    }
4523}
4524
4525// MCP
4526
4527/// Configuration for connecting to an MCP (Model Context Protocol) server.
4528///
4529/// MCP servers provide tools and context that the agent can use when
4530/// processing prompts.
4531///
4532/// See protocol docs: [MCP Servers](https://agentclientprotocol.com/protocol/v2/session-setup#mcp-servers)
4533#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4534#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4535#[serde(tag = "type", rename_all = "snake_case")]
4536#[non_exhaustive]
4537pub enum McpServer {
4538    /// HTTP transport configuration
4539    ///
4540    /// Only available when the Agent capabilities include `session.mcp.http`.
4541    Http(McpServerHttp),
4542    /// **UNSTABLE**
4543    ///
4544    /// This capability is not part of the spec yet, and may be removed or changed at any point.
4545    ///
4546    /// ACP transport configuration
4547    ///
4548    /// Only available when the Agent capabilities include `session.mcp.acp`.
4549    /// The MCP server is provided by an ACP component and communicates over the ACP channel.
4550    #[cfg(feature = "unstable_mcp_over_acp")]
4551    Acp(McpServerAcp),
4552    /// Stdio transport configuration
4553    ///
4554    /// Only available when the Agent capabilities include `session.mcp.stdio`.
4555    Stdio(McpServerStdio),
4556    /// Custom or future MCP server transport configuration.
4557    ///
4558    /// Values beginning with `_` are reserved for implementation-specific
4559    /// extensions. Unknown values that do not begin with `_` are reserved for
4560    /// future ACP variants.
4561    ///
4562    /// Receivers that do not understand this transport should preserve the raw
4563    /// payload when storing, replaying, proxying, or forwarding session setup
4564    /// data. Agents MUST reject a request with a transport they do not support
4565    /// with `-32602`.
4566    #[serde(untagged)]
4567    Other(OtherMcpServer),
4568}
4569
4570/// Custom or future MCP server transport payload.
4571#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4572#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4573#[cfg_attr(feature = "schemars", schemars(inline))]
4574#[cfg_attr(feature = "schemars", schemars(transform = other_mcp_server_schema))]
4575#[serde(rename_all = "camelCase")]
4576#[non_exhaustive]
4577pub struct OtherMcpServer {
4578    /// Custom or future MCP server transport type.
4579    ///
4580    /// Values beginning with `_` are reserved for implementation-specific
4581    /// extensions. Unknown values that do not begin with `_` are reserved for
4582    /// future ACP variants.
4583    #[serde(rename = "type")]
4584    pub type_: String,
4585    /// Additional fields from the unknown MCP server transport payload.
4586    #[serde(flatten)]
4587    pub fields: BTreeMap<String, serde_json::Value>,
4588}
4589
4590impl OtherMcpServer {
4591    /// Builds [`OtherMcpServer`] from an unknown discriminator and preserves the remaining extension fields.
4592    #[must_use]
4593    pub fn new(type_: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
4594        fields.remove("type");
4595        Self {
4596            type_: type_.into(),
4597            fields,
4598        }
4599    }
4600}
4601
4602impl<'de> Deserialize<'de> for OtherMcpServer {
4603    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4604    where
4605        D: serde::Deserializer<'de>,
4606    {
4607        let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
4608        let type_ = fields
4609            .remove("type")
4610            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4611        let serde_json::Value::String(type_) = type_ else {
4612            return Err(serde::de::Error::custom("`type` must be a string"));
4613        };
4614
4615        if is_known_mcp_server_type(&type_) {
4616            return Err(serde::de::Error::custom(format!(
4617                "known MCP server transport `{type_}` did not match its schema"
4618            )));
4619        }
4620
4621        Ok(Self { type_, fields })
4622    }
4623}
4624
4625fn is_known_mcp_server_type(type_: &str) -> bool {
4626    match type_ {
4627        "http" | "stdio" => true,
4628        #[cfg(feature = "unstable_mcp_over_acp")]
4629        "acp" => true,
4630        _ => false,
4631    }
4632}
4633
4634#[cfg(feature = "schemars")]
4635fn other_mcp_server_schema(schema: &mut Schema) {
4636    super::schema_util::reject_known_string_discriminators(
4637        schema,
4638        "type",
4639        &[
4640            "http",
4641            "stdio",
4642            #[cfg(feature = "unstable_mcp_over_acp")]
4643            "acp",
4644        ],
4645    );
4646}
4647
4648/// HTTP transport configuration for MCP.
4649#[serde_as]
4650#[skip_serializing_none]
4651#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4652#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4653#[serde(rename_all = "camelCase")]
4654#[non_exhaustive]
4655pub struct McpServerHttp {
4656    /// Human-readable name identifying this MCP server.
4657    pub name: String,
4658    /// URL to the MCP server.
4659    #[cfg_attr(feature = "schemars", schemars(url))]
4660    pub url: String,
4661    /// HTTP headers to set when making requests to the MCP server. Headers the MCP transport
4662    /// defines are owned by the transport, and Agents use the transport's values for them.
4663    #[serde_as(deserialize_as = "DefaultOnNull")]
4664    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4665    #[serde(default, skip_serializing_if = "Vec::is_empty")]
4666    pub headers: Vec<HttpHeader>,
4667    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4668    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4669    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4670    ///
4671    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4672    #[serde_as(deserialize_as = "DefaultOnError")]
4673    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4674    #[serde(default)]
4675    #[serde(rename = "_meta")]
4676    pub meta: Option<Meta>,
4677}
4678
4679impl McpServerHttp {
4680    /// Builds [`McpServerHttp`] with the required fields set. Optional fields start unset or empty.
4681    #[must_use]
4682    pub fn new(name: impl Into<String>, url: impl Into<String>) -> Self {
4683        Self {
4684            name: name.into(),
4685            url: url.into(),
4686            headers: Vec::new(),
4687            meta: None,
4688        }
4689    }
4690
4691    /// HTTP headers to set when making requests to the MCP server. Headers the MCP transport
4692    /// defines are owned by the transport, and Agents use the transport's values for them.
4693    #[must_use]
4694    pub fn headers(mut self, headers: Vec<HttpHeader>) -> Self {
4695        self.headers = headers;
4696        self
4697    }
4698
4699    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4700    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4701    /// do not recognize.
4702    ///
4703    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4704    #[must_use]
4705    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4706        self.meta = meta.into_option();
4707        self
4708    }
4709}
4710
4711/// **UNSTABLE**
4712///
4713/// This capability is not part of the spec yet, and may be removed or changed at any point.
4714///
4715/// Unique identifier for an MCP server using the ACP transport.
4716///
4717/// The value is opaque and generated by the ACP component providing the MCP server. It is
4718/// used by `mcp/message` to route requests to the component that declared the server.
4719#[cfg(feature = "unstable_mcp_over_acp")]
4720#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4721#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
4722#[serde(transparent)]
4723#[from(forward)]
4724#[non_exhaustive]
4725pub struct McpServerAcpId(pub Arc<str>);
4726
4727#[cfg(feature = "unstable_mcp_over_acp")]
4728impl McpServerAcpId {
4729    /// Wraps a protocol string as a typed [`McpServerAcpId`].
4730    #[must_use]
4731    pub fn new(id: impl Into<Self>) -> Self {
4732        id.into()
4733    }
4734}
4735
4736/// **UNSTABLE**
4737///
4738/// This capability is not part of the spec yet, and may be removed or changed at any point.
4739///
4740/// ACP transport configuration for MCP.
4741///
4742/// The MCP server is provided by an ACP component and communicates over the ACP channel
4743/// using `mcp/message`.
4744#[serde_as]
4745#[skip_serializing_none]
4746#[cfg(feature = "unstable_mcp_over_acp")]
4747#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4748#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4749#[serde(rename_all = "camelCase")]
4750#[non_exhaustive]
4751pub struct McpServerAcp {
4752    /// Human-readable name identifying this MCP server.
4753    pub name: String,
4754    /// Unique identifier for this MCP server, generated by the component providing it.
4755    ///
4756    /// Providers MUST NOT reuse an ID for multiple ACP-transport MCP servers that are visible
4757    /// on the same ACP connection.
4758    pub server_id: McpServerAcpId,
4759    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4760    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4761    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4762    ///
4763    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4764    #[serde_as(deserialize_as = "DefaultOnError")]
4765    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4766    #[serde(default)]
4767    #[serde(rename = "_meta")]
4768    pub meta: Option<Meta>,
4769}
4770
4771#[cfg(feature = "unstable_mcp_over_acp")]
4772impl McpServerAcp {
4773    /// Builds [`McpServerAcp`] with the required fields set. Optional fields start unset or empty.
4774    #[must_use]
4775    pub fn new(name: impl Into<String>, server_id: impl Into<McpServerAcpId>) -> Self {
4776        Self {
4777            name: name.into(),
4778            server_id: server_id.into(),
4779            meta: None,
4780        }
4781    }
4782
4783    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4784    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4785    /// do not recognize.
4786    ///
4787    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4788    #[must_use]
4789    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4790        self.meta = meta.into_option();
4791        self
4792    }
4793}
4794
4795/// Stdio transport configuration for MCP.
4796#[serde_as]
4797#[skip_serializing_none]
4798#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4799#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4800#[serde(rename_all = "camelCase")]
4801#[non_exhaustive]
4802pub struct McpServerStdio {
4803    /// Human-readable name identifying this MCP server.
4804    pub name: String,
4805    /// Absolute path to the MCP server executable.
4806    pub command: AbsolutePath,
4807    /// Command-line arguments to pass to the MCP server.
4808    #[serde_as(deserialize_as = "DefaultOnNull")]
4809    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4810    #[serde(default, skip_serializing_if = "Vec::is_empty")]
4811    pub args: Vec<String>,
4812    /// Environment variables to set when launching the MCP server. Names SHOULD be unique.
4813    /// Agents MAY reject duplicates with `-32602`, and otherwise the last entry wins.
4814    #[serde_as(deserialize_as = "DefaultOnNull")]
4815    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4816    #[serde(default, skip_serializing_if = "Vec::is_empty")]
4817    pub env: Vec<EnvVariable>,
4818    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4819    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4820    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4821    ///
4822    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4823    #[serde_as(deserialize_as = "DefaultOnError")]
4824    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4825    #[serde(default)]
4826    #[serde(rename = "_meta")]
4827    pub meta: Option<Meta>,
4828}
4829
4830impl McpServerStdio {
4831    /// Builds [`McpServerStdio`] with the required fields set. Optional fields start unset or empty.
4832    #[must_use]
4833    pub fn new(name: impl Into<String>, command: impl Into<AbsolutePath>) -> Self {
4834        Self {
4835            name: name.into(),
4836            command: command.into(),
4837            args: Vec::new(),
4838            env: Vec::new(),
4839            meta: None,
4840        }
4841    }
4842
4843    /// Command-line arguments to pass to the MCP server.
4844    #[must_use]
4845    pub fn args(mut self, args: Vec<String>) -> Self {
4846        self.args = args;
4847        self
4848    }
4849
4850    /// Environment variables to set when launching the MCP server. Names SHOULD be unique.
4851    /// Agents MAY reject duplicates with `-32602`, and otherwise the last entry wins.
4852    #[must_use]
4853    pub fn env(mut self, env: Vec<EnvVariable>) -> Self {
4854        self.env = env;
4855        self
4856    }
4857
4858    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4859    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4860    /// do not recognize.
4861    ///
4862    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4863    #[must_use]
4864    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4865        self.meta = meta.into_option();
4866        self
4867    }
4868}
4869
4870/// An environment variable to set when launching a process.
4871#[serde_as]
4872#[skip_serializing_none]
4873#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4874#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4875#[serde(rename_all = "camelCase")]
4876#[non_exhaustive]
4877pub struct EnvVariable {
4878    /// The name of the environment variable.
4879    pub name: String,
4880    /// The value to set for the environment variable.
4881    pub value: String,
4882    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4883    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4884    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4885    ///
4886    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4887    #[serde_as(deserialize_as = "DefaultOnError")]
4888    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4889    #[serde(default)]
4890    #[serde(rename = "_meta")]
4891    pub meta: Option<Meta>,
4892}
4893
4894impl EnvVariable {
4895    /// Builds [`EnvVariable`] with the required fields set. Optional fields start unset or empty.
4896    #[must_use]
4897    pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
4898        Self {
4899            name: name.into(),
4900            value: value.into(),
4901            meta: None,
4902        }
4903    }
4904
4905    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4906    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4907    /// do not recognize.
4908    ///
4909    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4910    #[must_use]
4911    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4912        self.meta = meta.into_option();
4913        self
4914    }
4915}
4916
4917/// An HTTP header to set when making requests to the MCP server.
4918#[serde_as]
4919#[skip_serializing_none]
4920#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4921#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4922#[serde(rename_all = "camelCase")]
4923#[non_exhaustive]
4924pub struct HttpHeader {
4925    /// The name of the HTTP header.
4926    pub name: String,
4927    /// The value to set for the HTTP header.
4928    pub value: String,
4929    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4930    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4931    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4932    ///
4933    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4934    #[serde_as(deserialize_as = "DefaultOnError")]
4935    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4936    #[serde(default)]
4937    #[serde(rename = "_meta")]
4938    pub meta: Option<Meta>,
4939}
4940
4941impl HttpHeader {
4942    /// Builds [`HttpHeader`] with the required fields set. Optional fields start unset or empty.
4943    #[must_use]
4944    pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
4945        Self {
4946            name: name.into(),
4947            value: value.into(),
4948            meta: None,
4949        }
4950    }
4951
4952    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4953    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4954    /// do not recognize.
4955    ///
4956    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4957    #[must_use]
4958    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4959        self.meta = meta.into_option();
4960        self
4961    }
4962}
4963
4964// System prompt
4965
4966/// Client-provided system-level instructions for a session.
4967///
4968/// Clients MUST only send this when the Agent advertises
4969/// `session.systemPrompt`. Agents that cannot apply it, for example because of
4970/// an unadvertised mode or an unsupported content block type, MUST return an
4971/// error instead of creating or resuming the session.
4972#[serde_as]
4973#[skip_serializing_none]
4974#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4975#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4976#[serde(rename_all = "camelCase")]
4977#[non_exhaustive]
4978pub struct SystemPrompt {
4979    /// How the Agent combines `content` with its own instructions.
4980    ///
4981    /// Required. Agents MUST return an error for a mode they do not support rather than
4982    /// treating it as `append` or `override`.
4983    pub mode: SystemPromptMode,
4984    /// The system prompt content.
4985    ///
4986    /// Agents advertising the capability MUST accept `text` content blocks.
4987    /// Clients MUST NOT send other content block types until a future
4988    /// capability allows them, and Agents MUST return an error for content
4989    /// blocks they do not support, including unknown types.
4990    ///
4991    /// Clients MUST NOT send an empty array. Agents MAY reject one with
4992    /// `-32602` without creating or resuming the session.
4993    pub content: Vec<ContentBlock>,
4994    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4995    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4996    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4997    ///
4998    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4999    #[serde_as(deserialize_as = "DefaultOnError")]
5000    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5001    #[serde(default)]
5002    #[serde(rename = "_meta")]
5003    pub meta: Option<Meta>,
5004}
5005
5006impl SystemPrompt {
5007    /// Builds [`SystemPrompt`] with the required fields set. Optional fields start unset or empty.
5008    ///
5009    /// `mode` starts as [`SystemPromptMode::Append`]. Use [`SystemPrompt::mode`]
5010    /// to request another mode.
5011    #[must_use]
5012    pub fn new(content: Vec<ContentBlock>) -> Self {
5013        Self {
5014            mode: SystemPromptMode::default(),
5015            content,
5016            meta: None,
5017        }
5018    }
5019
5020    /// How the Agent combines `content` with its own instructions.
5021    #[must_use]
5022    pub fn mode(mut self, mode: SystemPromptMode) -> Self {
5023        self.mode = mode;
5024        self
5025    }
5026
5027    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5028    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5029    /// do not recognize.
5030    ///
5031    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5032    #[must_use]
5033    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5034        self.meta = meta.into_option();
5035        self
5036    }
5037}
5038
5039/// How the Agent combines a client-provided system prompt with its own instructions.
5040///
5041/// Unknown modes are preserved so they can be stored,
5042/// proxied, or forwarded. An Agent MUST return an error for a mode it does not
5043/// support rather than treating it as `append` or `override`.
5044#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5045#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
5046#[serde(rename_all = "snake_case")]
5047#[non_exhaustive]
5048pub enum SystemPromptMode {
5049    /// Add the content to the Agent's own instructions rather than replacing them.
5050    ///
5051    /// Every Agent that advertises `session.systemPrompt` supports this mode.
5052    /// Agents SHOULD give the content system-level precedence, for example in the
5053    /// model's system prompt or developer instructions rather than in user-turn
5054    /// content. Where it is placed and how it is formatted is implementation-defined.
5055    #[default]
5056    Append,
5057    /// Replace the Agent's built-in default instructions with the content.
5058    ///
5059    /// This does not change tool availability, MCP servers, permissions, or session
5060    /// configuration. Context the Agent supplies from the workspace or environment
5061    /// MAY still be included. Clients that use this mode take responsibility for any
5062    /// tool guidance or safety instructions the Agent's default instructions
5063    /// provided, and MUST only use it when the Agent advertises
5064    /// `session.systemPrompt.mode.override`.
5065    Override,
5066    /// Custom or future system prompt mode.
5067    ///
5068    /// Values beginning with `_` are reserved for implementation-specific
5069    /// extensions. Unknown values that do not begin with `_` are reserved for
5070    /// future ACP variants.
5071    #[serde(untagged)]
5072    Other(String),
5073}
5074
5075// Prompt
5076
5077/// A key the Client generates to identify one `session/prompt` submission across attempts.
5078///
5079/// The key is an opaque, case-sensitive string of 1 to 255 characters. It is scoped to the
5080/// session named by the request's `sessionId`.
5081///
5082/// See protocol docs: [Retrying a prompt](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#retrying-a-prompt)
5083#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5084#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash, Display)]
5085#[serde(transparent)]
5086pub struct IdempotencyKey(
5087    #[cfg_attr(feature = "schemars", schemars(length(min = 1, max = 255)))] Arc<str>,
5088);
5089
5090impl IdempotencyKey {
5091    /// The maximum length of a key, in characters.
5092    pub const MAX_LENGTH: usize = 255;
5093
5094    /// Wraps a string as a typed [`IdempotencyKey`].
5095    ///
5096    /// # Errors
5097    ///
5098    /// Returns [`InvalidIdempotencyKey`] if the key is empty or longer than
5099    /// [`Self::MAX_LENGTH`] characters.
5100    pub fn new(key: impl Into<Arc<str>>) -> Result<Self, InvalidIdempotencyKey> {
5101        let key = key.into();
5102        if key.is_empty() {
5103            return Err(InvalidIdempotencyKey::Empty);
5104        }
5105        // The limit counts characters, as JSON Schema `maxLength` does, not bytes.
5106        if key.chars().nth(Self::MAX_LENGTH).is_some() {
5107            return Err(InvalidIdempotencyKey::TooLong);
5108        }
5109        Ok(Self(key))
5110    }
5111
5112    /// Generates a key from a random version 4 UUID ([RFC 9562]).
5113    ///
5114    /// Generate one key per submission, when the user submits the input, and store it
5115    /// with the pending input. Every attempt for that submission sends the same key.
5116    ///
5117    /// [RFC 9562]: https://www.rfc-editor.org/rfc/rfc9562
5118    #[cfg(feature = "uuid")]
5119    #[must_use]
5120    pub fn generate() -> Self {
5121        uuid::Uuid::new_v4().into()
5122    }
5123
5124    /// Returns the key as a string slice.
5125    #[must_use]
5126    pub fn as_str(&self) -> &str {
5127        &self.0
5128    }
5129}
5130
5131impl AsRef<str> for IdempotencyKey {
5132    fn as_ref(&self) -> &str {
5133        &self.0
5134    }
5135}
5136
5137#[cfg(feature = "uuid")]
5138impl From<uuid::Uuid> for IdempotencyKey {
5139    /// Uses the UUID's hyphenated lowercase form. It is 36 characters, so it is always a
5140    /// valid key.
5141    fn from(uuid: uuid::Uuid) -> Self {
5142        Self(uuid.to_string().into())
5143    }
5144}
5145
5146impl TryFrom<String> for IdempotencyKey {
5147    type Error = InvalidIdempotencyKey;
5148
5149    fn try_from(key: String) -> Result<Self, Self::Error> {
5150        Self::new(key)
5151    }
5152}
5153
5154impl TryFrom<&str> for IdempotencyKey {
5155    type Error = InvalidIdempotencyKey;
5156
5157    fn try_from(key: &str) -> Result<Self, Self::Error> {
5158        Self::new(key)
5159    }
5160}
5161
5162impl std::str::FromStr for IdempotencyKey {
5163    type Err = InvalidIdempotencyKey;
5164
5165    fn from_str(key: &str) -> Result<Self, Self::Err> {
5166        Self::new(key)
5167    }
5168}
5169
5170// Deserialization validates the key, so a malformed value fails the request
5171// instead of being treated as omitted.
5172impl<'de> Deserialize<'de> for IdempotencyKey {
5173    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
5174    where
5175        D: serde::Deserializer<'de>,
5176    {
5177        let key = Arc::<str>::deserialize(deserializer)?;
5178        Self::new(key).map_err(serde::de::Error::custom)
5179    }
5180}
5181
5182/// Error returned when a string is not a valid [`IdempotencyKey`].
5183#[derive(Debug, Clone, Copy, PartialEq, Eq, Display)]
5184#[non_exhaustive]
5185pub enum InvalidIdempotencyKey {
5186    /// The key is an empty string.
5187    #[display("idempotency key must not be empty")]
5188    Empty,
5189    /// The key is longer than [`IdempotencyKey::MAX_LENGTH`] characters.
5190    #[display(
5191        "idempotency key must be at most {} characters",
5192        IdempotencyKey::MAX_LENGTH
5193    )]
5194    TooLong,
5195}
5196
5197impl std::error::Error for InvalidIdempotencyKey {}
5198
5199/// Request parameters for sending a user prompt to the agent.
5200///
5201/// Contains the user's message and any additional context.
5202///
5203/// See protocol docs: [User Message](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#1-user-message)
5204#[serde_as]
5205#[skip_serializing_none]
5206#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5207#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5208#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_PROMPT_METHOD_NAME)))]
5209#[serde(rename_all = "camelCase")]
5210#[non_exhaustive]
5211pub struct PromptRequest {
5212    /// The ID of the session to send this user message to
5213    pub session_id: SessionId,
5214    /// The blocks of content that compose the user's message.
5215    ///
5216    /// As a baseline, the Agent MUST support `text` and `resource_link` content blocks,
5217    /// while other variants are optionally enabled via `PromptCapabilities`.
5218    ///
5219    /// The Client MUST adapt its interface according to `PromptCapabilities`.
5220    ///
5221    /// The client MAY include referenced pieces of context as either
5222    /// `resource` or `resource_link` content blocks.
5223    ///
5224    /// When available, `resource` is preferred
5225    /// as it avoids extra round-trips and allows the message to include
5226    /// pieces of context from sources the agent may not have access to.
5227    ///
5228    /// Clients MUST NOT send an empty array. Agents MAY reject one with `-32602` without
5229    /// inserting it.
5230    #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
5231    pub prompt: Vec<ContentBlock>,
5232    /// Identifies this submission, so the Client can send the request again without the
5233    /// user message being inserted twice.
5234    ///
5235    /// Optional. Omitted and `null` are equivalent and mean no key. The Agent then handles
5236    /// the prompt without duplicate detection.
5237    ///
5238    /// The Client generates the key and sends the same key on every attempt for the same
5239    /// submission. The Agent inserts at most one user message for a key in a session, and
5240    /// answers a retry with the `messageId` of the message it already inserted. Agents that
5241    /// advertise `capabilities.session` MUST support the key.
5242    ///
5243    /// When present, the value is an opaque, case-sensitive string of 1 to 255 characters.
5244    /// Agents MUST reject any other value with `-32602` (Invalid params) and MUST NOT treat
5245    /// it as omitted.
5246    ///
5247    /// See protocol docs: [Retrying a prompt](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#retrying-a-prompt)
5248    #[serde(default)]
5249    pub idempotency_key: Option<IdempotencyKey>,
5250    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5251    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5252    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5253    ///
5254    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5255    #[serde_as(deserialize_as = "DefaultOnError")]
5256    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5257    #[serde(default)]
5258    #[serde(rename = "_meta")]
5259    pub meta: Option<Meta>,
5260}
5261
5262impl PromptRequest {
5263    /// Builds [`PromptRequest`] with the required request fields set. Optional fields start unset or empty.
5264    #[must_use]
5265    pub fn new(session_id: impl Into<SessionId>, prompt: Vec<ContentBlock>) -> Self {
5266        Self {
5267            session_id: session_id.into(),
5268            prompt,
5269            idempotency_key: None,
5270            meta: None,
5271        }
5272    }
5273
5274    /// Identifies this submission, so the Client can send the request again without the
5275    /// user message being inserted twice.
5276    ///
5277    /// The Client generates the key and sends the same key on every attempt for the same
5278    /// submission. `None` means no key.
5279    ///
5280    /// See protocol docs: [Retrying a prompt](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#retrying-a-prompt)
5281    #[must_use]
5282    pub fn idempotency_key(mut self, idempotency_key: impl IntoOption<IdempotencyKey>) -> Self {
5283        self.idempotency_key = idempotency_key.into_option();
5284        self
5285    }
5286
5287    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5288    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5289    /// do not recognize.
5290    ///
5291    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5292    #[must_use]
5293    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5294        self.meta = meta.into_option();
5295        self
5296    }
5297}
5298
5299/// Response acknowledging that a user prompt was inserted into the ACP conversation.
5300///
5301/// This response does not indicate that the prompt was merely received or held, nor that the
5302/// agent has finished processing it.
5303/// Processing and completion are reported through `state_update` session updates.
5304///
5305/// Insertion is the logical addition of a user message with a message ID and a position
5306/// relative to other messages in the ACP conversation.
5307///
5308/// See protocol docs: [Prompt Accepted](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#2-prompt-accepted)
5309#[serde_as]
5310#[skip_serializing_none]
5311#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5312#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5313#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_PROMPT_METHOD_NAME)))]
5314#[serde(rename_all = "camelCase")]
5315#[non_exhaustive]
5316pub struct PromptResponse {
5317    /// Identifies the user message inserted into the ACP conversation.
5318    ///
5319    /// Required and non-null. Omission and explicit `null` are both invalid.
5320    ///
5321    /// The corresponding user-message session update carries this same identifier and may arrive
5322    /// before or after this response. Agents must echo the message during the live session, but are
5323    /// not required to retain it. If retained and replayed, the message keeps this identifier.
5324    pub message_id: MessageId,
5325    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5326    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5327    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5328    ///
5329    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5330    #[serde_as(deserialize_as = "DefaultOnError")]
5331    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5332    #[serde(default)]
5333    #[serde(rename = "_meta")]
5334    pub meta: Option<Meta>,
5335}
5336
5337impl PromptResponse {
5338    /// Builds [`PromptResponse`] with the required response fields set. Optional fields start unset or empty.
5339    #[must_use]
5340    pub fn new(message_id: impl Into<MessageId>) -> Self {
5341        Self {
5342            message_id: message_id.into(),
5343            meta: None,
5344        }
5345    }
5346
5347    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5348    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5349    /// do not recognize.
5350    ///
5351    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5352    #[must_use]
5353    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5354        self.meta = meta.into_option();
5355        self
5356    }
5357}
5358
5359/// Reasons why an agent stops active session work.
5360///
5361/// See protocol docs: [Stop Reasons](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#stop-reasons)
5362#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5363#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
5364#[serde(tag = "stopReason", rename_all = "snake_case")]
5365#[non_exhaustive]
5366pub enum StopReason {
5367    /// The active work ended successfully.
5368    /// Includes locally handled commands that required no model call.
5369    EndTurn,
5370    /// The active work ended because the agent reached the maximum number of tokens.
5371    MaxTokens,
5372    /// The active work ended because the agent reached the maximum number of
5373    /// model requests for the foreground work.
5374    MaxTurnRequests,
5375    /// The active work ended because the agent refused to continue.
5376    Refusal,
5377    /// The user or client chose to stop the work: via `session/cancel`, by
5378    /// closing the session, or through an interaction the agent offers, such
5379    /// as a permission option that tells the agent to stop. Work the agent
5380    /// stops for its own reasons uses another reason, such as `error` for an
5381    /// internal timeout.
5382    ///
5383    /// Agents MUST report this stop reason on an idle `state_update` when
5384    /// cancellation ends active foreground work, even if aborting causes
5385    /// exceptions. Agents MUST catch these errors and report `cancelled`, not
5386    /// `error`.
5387    Cancelled,
5388    /// The active work ended because something failed.
5389    ///
5390    /// This includes pre-insertion foreground work. A prompt failure before
5391    /// insertion also requires an error response to `session/prompt`. After
5392    /// insertion, the prompt's response remains successful.
5393    Error(ErrorStopReason),
5394    /// Custom or future stop reason.
5395    ///
5396    /// Values beginning with `_` are reserved for implementation-specific
5397    /// extensions. Unknown values that do not begin with `_` are reserved for
5398    /// future ACP variants.
5399    #[serde(untagged)]
5400    Other(OtherStopReason),
5401}
5402
5403impl From<ErrorStopReason> for StopReason {
5404    fn from(value: ErrorStopReason) -> Self {
5405        Self::Error(value)
5406    }
5407}
5408
5409/// Details of a failure that ended active work.
5410#[serde_as]
5411#[skip_serializing_none]
5412#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5413#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
5414#[serde(rename_all = "camelCase")]
5415#[non_exhaustive]
5416pub struct ErrorStopReason {
5417    /// The failure, as a JSON-RPC error object.
5418    ///
5419    /// Optional. Omitted and `null` are equivalent and mean the agent is not reporting failure details.
5420    /// Agents SHOULD include it.
5421    #[serde_as(deserialize_as = "DefaultOnError")]
5422    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5423    #[serde(default)]
5424    pub error: Option<Box<Error>>,
5425}
5426
5427impl ErrorStopReason {
5428    /// Builds [`ErrorStopReason`] with the required fields set. Optional fields start unset or empty.
5429    #[must_use]
5430    pub fn new() -> Self {
5431        Self::default()
5432    }
5433
5434    /// The failure, as a JSON-RPC error object.
5435    #[must_use]
5436    pub fn error(mut self, error: impl IntoOption<Error>) -> Self {
5437        self.error = error.into_option().map(Box::new);
5438        self
5439    }
5440}
5441
5442/// Custom or future stop reason payload.
5443#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5444#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
5445#[cfg_attr(feature = "schemars", schemars(inline))]
5446#[cfg_attr(feature = "schemars", schemars(transform = other_stop_reason_schema))]
5447#[serde(rename_all = "camelCase")]
5448#[non_exhaustive]
5449pub struct OtherStopReason {
5450    /// Custom or future stop reason.
5451    ///
5452    /// Values beginning with `_` are reserved for implementation-specific
5453    /// extensions. Unknown values that do not begin with `_` are reserved for
5454    /// future ACP variants.
5455    pub stop_reason: String,
5456    /// Additional fields from the unknown stop reason payload.
5457    #[serde(flatten)]
5458    pub fields: BTreeMap<String, serde_json::Value>,
5459}
5460
5461impl OtherStopReason {
5462    /// Builds [`OtherStopReason`] from an unknown discriminator and preserves the remaining extension fields.
5463    #[must_use]
5464    pub fn new(
5465        stop_reason: impl Into<String>,
5466        mut fields: BTreeMap<String, serde_json::Value>,
5467    ) -> Self {
5468        remove_idle_state_update_fields(&mut fields);
5469        Self {
5470            stop_reason: stop_reason.into(),
5471            fields,
5472        }
5473    }
5474}
5475
5476impl<'de> Deserialize<'de> for OtherStopReason {
5477    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
5478    where
5479        D: serde::Deserializer<'de>,
5480    {
5481        let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
5482        let stop_reason = fields
5483            .remove("stopReason")
5484            .ok_or_else(|| serde::de::Error::missing_field("stopReason"))?;
5485        let serde_json::Value::String(stop_reason) = stop_reason else {
5486            return Err(serde::de::Error::custom("`stopReason` must be a string"));
5487        };
5488
5489        if KNOWN_STOP_REASONS.contains(&stop_reason.as_str()) {
5490            return Err(serde::de::Error::custom(format!(
5491                "known stop reason `{stop_reason}` did not match its schema"
5492            )));
5493        }
5494        remove_idle_state_update_fields(&mut fields);
5495
5496        Ok(Self {
5497            stop_reason,
5498            fields,
5499        })
5500    }
5501}
5502
5503const KNOWN_STOP_REASONS: &[&str] = &[
5504    "end_turn",
5505    "max_tokens",
5506    "max_turn_requests",
5507    "refusal",
5508    "cancelled",
5509    "error",
5510];
5511
5512/// Keeps the idle update's own fields out of an unknown stop reason's payload.
5513fn remove_idle_state_update_fields(fields: &mut BTreeMap<String, serde_json::Value>) {
5514    fields.remove("stopReason");
5515    fields.remove("usage");
5516    fields.remove("_meta");
5517}
5518
5519#[cfg(feature = "schemars")]
5520fn other_stop_reason_schema(schema: &mut Schema) {
5521    super::schema_util::reject_known_string_discriminators(
5522        schema,
5523        "stopReason",
5524        KNOWN_STOP_REASONS,
5525    );
5526}
5527
5528/// **UNSTABLE**
5529///
5530/// This capability is not part of the spec yet, and may be removed or changed at any point.
5531///
5532/// Token usage for the foreground work that just completed, not cumulative for the session.
5533#[cfg(feature = "unstable_end_turn_token_usage")]
5534#[serde_as]
5535#[skip_serializing_none]
5536#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5537#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5538#[serde(rename_all = "camelCase")]
5539#[non_exhaustive]
5540pub struct Usage {
5541    /// Sum of all token types for the completed work.
5542    pub total_tokens: u64,
5543    /// Input tokens for the completed work.
5544    pub input_tokens: u64,
5545    /// Output tokens for the completed work.
5546    pub output_tokens: u64,
5547    /// Thought/reasoning tokens for the completed work.
5548    ///
5549    /// Omitted and `null` are equivalent and mean the count is not reported.
5550    #[serde_as(deserialize_as = "DefaultOnError")]
5551    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5552    #[serde(default)]
5553    pub thought_tokens: Option<u64>,
5554    /// Cache read tokens for the completed work.
5555    ///
5556    /// Omitted and `null` are equivalent and mean the count is not reported.
5557    #[serde_as(deserialize_as = "DefaultOnError")]
5558    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5559    #[serde(default)]
5560    pub cached_read_tokens: Option<u64>,
5561    /// Cache write tokens for the completed work.
5562    ///
5563    /// Omitted and `null` are equivalent and mean the count is not reported.
5564    #[serde_as(deserialize_as = "DefaultOnError")]
5565    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5566    #[serde(default)]
5567    pub cached_write_tokens: Option<u64>,
5568    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5569    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5570    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5571    ///
5572    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5573    #[serde_as(deserialize_as = "DefaultOnError")]
5574    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5575    #[serde(default)]
5576    #[serde(rename = "_meta")]
5577    pub meta: Option<Meta>,
5578}
5579
5580#[cfg(feature = "unstable_end_turn_token_usage")]
5581impl Usage {
5582    /// Builds [`Usage`] with the required fields set. Optional fields start unset or empty.
5583    #[must_use]
5584    pub fn new(total_tokens: u64, input_tokens: u64, output_tokens: u64) -> Self {
5585        Self {
5586            total_tokens,
5587            input_tokens,
5588            output_tokens,
5589            thought_tokens: None,
5590            cached_read_tokens: None,
5591            cached_write_tokens: None,
5592            meta: None,
5593        }
5594    }
5595
5596    /// Thought/reasoning tokens for the completed work.
5597    #[must_use]
5598    pub fn thought_tokens(mut self, thought_tokens: impl IntoOption<u64>) -> Self {
5599        self.thought_tokens = thought_tokens.into_option();
5600        self
5601    }
5602
5603    /// Cache read tokens for the completed work.
5604    #[must_use]
5605    pub fn cached_read_tokens(mut self, cached_read_tokens: impl IntoOption<u64>) -> Self {
5606        self.cached_read_tokens = cached_read_tokens.into_option();
5607        self
5608    }
5609
5610    /// Cache write tokens for the completed work.
5611    #[must_use]
5612    pub fn cached_write_tokens(mut self, cached_write_tokens: impl IntoOption<u64>) -> Self {
5613        self.cached_write_tokens = cached_write_tokens.into_option();
5614        self
5615    }
5616
5617    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5618    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5619    /// do not recognize.
5620    ///
5621    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5622    #[must_use]
5623    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5624        self.meta = meta.into_option();
5625        self
5626    }
5627}
5628
5629// Providers
5630
5631/// **UNSTABLE**
5632///
5633/// This capability is not part of the spec yet, and may be removed or changed at any point.
5634///
5635/// Well-known API protocol identifiers for LLM providers.
5636///
5637/// Agents and clients MUST handle unknown protocol identifiers gracefully.
5638///
5639/// Protocol names beginning with `_` are free for custom use, like other ACP extension methods.
5640/// Protocol names that do not begin with `_` are reserved for the ACP spec.
5641#[cfg(feature = "unstable_llm_providers")]
5642#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5643#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5644#[serde(rename_all = "snake_case")]
5645#[non_exhaustive]
5646#[expect(clippy::doc_markdown)]
5647pub enum LlmProtocol {
5648    /// Anthropic API protocol.
5649    Anthropic,
5650    /// OpenAI API protocol.
5651    #[serde(rename = "openai")]
5652    OpenAi,
5653    /// Azure OpenAI API protocol.
5654    Azure,
5655    /// Google Vertex AI API protocol.
5656    Vertex,
5657    /// AWS Bedrock API protocol.
5658    Bedrock,
5659    /// Custom or future protocol.
5660    ///
5661    /// Values beginning with `_` are reserved for implementation-specific
5662    /// extensions. Unknown values that do not begin with `_` are reserved for
5663    /// future ACP variants.
5664    #[serde(untagged)]
5665    Other(String),
5666}
5667
5668/// **UNSTABLE**
5669///
5670/// This capability is not part of the spec yet, and may be removed or changed at any point.
5671///
5672/// Current effective non-secret routing configuration for a provider.
5673#[cfg(feature = "unstable_llm_providers")]
5674#[serde_as]
5675#[skip_serializing_none]
5676#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5677#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5678#[serde(rename_all = "camelCase")]
5679#[non_exhaustive]
5680pub struct ProviderCurrentConfig {
5681    /// Protocol currently used by this provider.
5682    pub api_type: LlmProtocol,
5683    /// Base URL currently used by this provider.
5684    #[cfg_attr(feature = "schemars", schemars(url))]
5685    pub base_url: String,
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 ProviderCurrentConfig {
5700    /// Builds [`ProviderCurrentConfig`] with the required fields set. Optional fields start unset or empty.
5701    #[must_use]
5702    pub fn new(api_type: LlmProtocol, base_url: impl Into<String>) -> Self {
5703        Self {
5704            api_type,
5705            base_url: base_url.into(),
5706            meta: None,
5707        }
5708    }
5709
5710    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5711    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5712    /// do not recognize.
5713    ///
5714    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5715    #[must_use]
5716    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5717        self.meta = meta.into_option();
5718        self
5719    }
5720}
5721
5722/// **UNSTABLE**
5723///
5724/// This capability is not part of the spec yet, and may be removed or changed at any point.
5725///
5726/// Unique identifier for a configurable LLM provider.
5727#[cfg(feature = "unstable_llm_providers")]
5728#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5729#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
5730#[serde(transparent)]
5731#[from(forward)]
5732#[non_exhaustive]
5733pub struct ProviderId(pub Arc<str>);
5734
5735#[cfg(feature = "unstable_llm_providers")]
5736impl ProviderId {
5737    /// Wraps a protocol string as a typed [`ProviderId`].
5738    #[must_use]
5739    pub fn new(id: impl Into<Self>) -> Self {
5740        id.into()
5741    }
5742}
5743
5744/// **UNSTABLE**
5745///
5746/// This capability is not part of the spec yet, and may be removed or changed at any point.
5747///
5748/// Information about a configurable LLM provider.
5749#[cfg(feature = "unstable_llm_providers")]
5750#[serde_as]
5751#[skip_serializing_none]
5752#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5753#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5754#[serde(rename_all = "camelCase")]
5755#[non_exhaustive]
5756pub struct ProviderInfo {
5757    /// Provider identifier, for example "main" or "openai".
5758    pub provider_id: ProviderId,
5759    /// Supported protocol types for this provider.
5760    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
5761    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
5762    pub supported: Vec<LlmProtocol>,
5763    /// Whether this provider is mandatory and cannot be disabled via `providers/disable`.
5764    /// If true, clients must not call `providers/disable` for this provider ID.
5765    pub required: bool,
5766    /// Current effective non-secret routing config.
5767    /// Null or omitted means provider is disabled.
5768    #[serde(default)]
5769    pub current: Option<ProviderCurrentConfig>,
5770    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5771    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5772    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5773    ///
5774    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5775    #[serde_as(deserialize_as = "DefaultOnError")]
5776    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5777    #[serde(default)]
5778    #[serde(rename = "_meta")]
5779    pub meta: Option<Meta>,
5780}
5781
5782#[cfg(feature = "unstable_llm_providers")]
5783impl ProviderInfo {
5784    /// Builds [`ProviderInfo`] with the required fields set. Optional fields start unset or empty.
5785    #[must_use]
5786    pub fn new(
5787        provider_id: impl Into<ProviderId>,
5788        supported: Vec<LlmProtocol>,
5789        required: bool,
5790        current: impl IntoOption<ProviderCurrentConfig>,
5791    ) -> Self {
5792        Self {
5793            provider_id: provider_id.into(),
5794            supported,
5795            required,
5796            current: current.into_option(),
5797            meta: None,
5798        }
5799    }
5800
5801    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5802    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5803    /// do not recognize.
5804    ///
5805    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5806    #[must_use]
5807    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5808        self.meta = meta.into_option();
5809        self
5810    }
5811}
5812
5813#[cfg(feature = "unstable_llm_providers")]
5814crate::serde_util::default_on_null! {
5815    /// **UNSTABLE**
5816    ///
5817    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5818    ///
5819    /// Request parameters for `providers/list`.
5820    #[serde_as]
5821    #[skip_serializing_none]
5822    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5823    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
5824    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_LIST_METHOD_NAME)))]
5825    #[serde(rename_all = "camelCase")]
5826    #[non_exhaustive]
5827    pub struct ListProvidersRequest {
5828        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5829        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5830        /// Implementations MUST NOT assign meaning to keys they do not recognize.
5831        ///
5832        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5833        #[serde_as(deserialize_as = "DefaultOnError")]
5834        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5835        #[serde(default)]
5836        #[serde(rename = "_meta")]
5837        pub meta: Option<Meta>,
5838    }
5839}
5840
5841#[cfg(feature = "unstable_llm_providers")]
5842impl ListProvidersRequest {
5843    /// Builds [`ListProvidersRequest`] with the required request fields set. Optional fields start unset or empty.
5844    #[must_use]
5845    pub fn new() -> Self {
5846        Self::default()
5847    }
5848
5849    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5850    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5851    /// do not recognize.
5852    ///
5853    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5854    #[must_use]
5855    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5856        self.meta = meta.into_option();
5857        self
5858    }
5859}
5860
5861/// **UNSTABLE**
5862///
5863/// This capability is not part of the spec yet, and may be removed or changed at any point.
5864///
5865/// Response to `providers/list`.
5866#[cfg(feature = "unstable_llm_providers")]
5867#[serde_as]
5868#[skip_serializing_none]
5869#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5870#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5871#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_LIST_METHOD_NAME)))]
5872#[serde(rename_all = "camelCase")]
5873#[non_exhaustive]
5874pub struct ListProvidersResponse {
5875    /// Configurable providers with current routing info suitable for UI display.
5876    pub providers: Vec<ProviderInfo>,
5877    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5878    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5879    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5880    ///
5881    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5882    #[serde_as(deserialize_as = "DefaultOnError")]
5883    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5884    #[serde(default)]
5885    #[serde(rename = "_meta")]
5886    pub meta: Option<Meta>,
5887}
5888
5889#[cfg(feature = "unstable_llm_providers")]
5890impl ListProvidersResponse {
5891    /// Builds [`ListProvidersResponse`] with the required response fields set. Optional fields start unset or empty.
5892    #[must_use]
5893    pub fn new(providers: Vec<ProviderInfo>) -> Self {
5894        Self {
5895            providers,
5896            meta: None,
5897        }
5898    }
5899
5900    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5901    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5902    /// do not recognize.
5903    ///
5904    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5905    #[must_use]
5906    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5907        self.meta = meta.into_option();
5908        self
5909    }
5910}
5911
5912/// **UNSTABLE**
5913///
5914/// This capability is not part of the spec yet, and may be removed or changed at any point.
5915///
5916/// Request parameters for `providers/set`.
5917///
5918/// Replaces the full configuration for one provider ID.
5919#[cfg(feature = "unstable_llm_providers")]
5920#[serde_as]
5921#[skip_serializing_none]
5922#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5923#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
5924#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_SET_METHOD_NAME)))]
5925#[serde(rename_all = "camelCase")]
5926#[non_exhaustive]
5927pub struct SetProviderRequest {
5928    /// Provider ID to configure.
5929    pub provider_id: ProviderId,
5930    /// Protocol type for this provider.
5931    pub api_type: LlmProtocol,
5932    /// Base URL for requests sent through this provider.
5933    #[cfg_attr(feature = "schemars", schemars(url))]
5934    pub base_url: String,
5935    /// Full headers map for this provider.
5936    /// May include authorization, routing, or other integration-specific headers.
5937    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
5938    pub headers: HashMap<String, String>,
5939    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5940    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5941    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5942    ///
5943    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5944    #[serde_as(deserialize_as = "DefaultOnError")]
5945    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5946    #[serde(default)]
5947    #[serde(rename = "_meta")]
5948    pub meta: Option<Meta>,
5949}
5950
5951#[cfg(feature = "unstable_llm_providers")]
5952impl SetProviderRequest {
5953    /// Builds [`SetProviderRequest`] with the required request fields set. Optional fields start unset or empty.
5954    #[must_use]
5955    pub fn new(
5956        provider_id: impl Into<ProviderId>,
5957        api_type: LlmProtocol,
5958        base_url: impl Into<String>,
5959    ) -> Self {
5960        Self {
5961            provider_id: provider_id.into(),
5962            api_type,
5963            base_url: base_url.into(),
5964            headers: HashMap::new(),
5965            meta: None,
5966        }
5967    }
5968
5969    /// Full headers map for this provider.
5970    /// May include authorization, routing, or other integration-specific headers.
5971    #[must_use]
5972    pub fn headers(mut self, headers: HashMap<String, String>) -> Self {
5973        self.headers = headers;
5974        self
5975    }
5976
5977    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5978    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5979    /// do not recognize.
5980    ///
5981    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5982    #[must_use]
5983    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5984        self.meta = meta.into_option();
5985        self
5986    }
5987}
5988
5989#[cfg(feature = "unstable_llm_providers")]
5990crate::serde_util::default_on_null! {
5991    /// **UNSTABLE**
5992    ///
5993    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5994    ///
5995    /// Response to `providers/set`.
5996    #[serde_as]
5997    #[skip_serializing_none]
5998    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5999    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
6000    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_SET_METHOD_NAME)))]
6001    #[serde(rename_all = "camelCase")]
6002    #[non_exhaustive]
6003    pub struct SetProviderResponse {
6004        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6005        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6006        /// Implementations MUST NOT assign meaning to keys they do not recognize.
6007        ///
6008        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6009        #[serde_as(deserialize_as = "DefaultOnError")]
6010        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6011        #[serde(default)]
6012        #[serde(rename = "_meta")]
6013        pub meta: Option<Meta>,
6014    }
6015}
6016
6017#[cfg(feature = "unstable_llm_providers")]
6018impl SetProviderResponse {
6019    /// Builds [`SetProviderResponse`] with the required response fields set. Optional fields start unset or empty.
6020    #[must_use]
6021    pub fn new() -> Self {
6022        Self::default()
6023    }
6024
6025    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6026    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6027    /// do not recognize.
6028    ///
6029    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6030    #[must_use]
6031    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6032        self.meta = meta.into_option();
6033        self
6034    }
6035}
6036
6037/// **UNSTABLE**
6038///
6039/// This capability is not part of the spec yet, and may be removed or changed at any point.
6040///
6041/// Request parameters for `providers/disable`.
6042#[cfg(feature = "unstable_llm_providers")]
6043#[serde_as]
6044#[skip_serializing_none]
6045#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6046#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6047#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_DISABLE_METHOD_NAME)))]
6048#[serde(rename_all = "camelCase")]
6049#[non_exhaustive]
6050pub struct DisableProviderRequest {
6051    /// Provider ID to disable.
6052    pub provider_id: ProviderId,
6053    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6054    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6055    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6056    ///
6057    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6058    #[serde_as(deserialize_as = "DefaultOnError")]
6059    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6060    #[serde(default)]
6061    #[serde(rename = "_meta")]
6062    pub meta: Option<Meta>,
6063}
6064
6065#[cfg(feature = "unstable_llm_providers")]
6066impl DisableProviderRequest {
6067    /// Builds [`DisableProviderRequest`] with the required request fields set. Optional fields start unset or empty.
6068    #[must_use]
6069    pub fn new(provider_id: impl Into<ProviderId>) -> Self {
6070        Self {
6071            provider_id: provider_id.into(),
6072            meta: None,
6073        }
6074    }
6075
6076    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6077    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6078    /// do not recognize.
6079    ///
6080    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6081    #[must_use]
6082    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6083        self.meta = meta.into_option();
6084        self
6085    }
6086}
6087
6088#[cfg(feature = "unstable_llm_providers")]
6089crate::serde_util::default_on_null! {
6090    /// **UNSTABLE**
6091    ///
6092    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6093    ///
6094    /// Response to `providers/disable`.
6095    #[serde_as]
6096    #[skip_serializing_none]
6097    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6098    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
6099    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_DISABLE_METHOD_NAME)))]
6100    #[serde(rename_all = "camelCase")]
6101    #[non_exhaustive]
6102    pub struct DisableProviderResponse {
6103        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6104        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6105        /// Implementations MUST NOT assign meaning to keys they do not recognize.
6106        ///
6107        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6108        #[serde_as(deserialize_as = "DefaultOnError")]
6109        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6110        #[serde(default)]
6111        #[serde(rename = "_meta")]
6112        pub meta: Option<Meta>,
6113    }
6114}
6115
6116#[cfg(feature = "unstable_llm_providers")]
6117impl DisableProviderResponse {
6118    /// Builds [`DisableProviderResponse`] with the required response fields set. Optional fields start unset or empty.
6119    #[must_use]
6120    pub fn new() -> Self {
6121        Self::default()
6122    }
6123
6124    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6125    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6126    /// do not recognize.
6127    ///
6128    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6129    #[must_use]
6130    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6131        self.meta = meta.into_option();
6132        self
6133    }
6134}
6135
6136// Capabilities
6137
6138/// Capabilities supported by the agent.
6139///
6140/// Advertised during initialization to inform the client about
6141/// available features and content types.
6142///
6143/// See protocol docs: [Agent Capabilities](https://agentclientprotocol.com/protocol/v2/initialization#agent-capabilities)
6144#[serde_as]
6145#[skip_serializing_none]
6146#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6147#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6148#[serde(rename_all = "camelCase")]
6149#[non_exhaustive]
6150pub struct AgentCapabilities {
6151    /// Session capabilities supported by the agent.
6152    ///
6153    /// Optional. Omitted and `null` are equivalent and mean the agent does not support the
6154    /// `session/*` methods. Supplying `{}` means the agent supports the
6155    /// baseline session methods: `session/new`, `session/list`,
6156    /// `session/resume`, `session/close`, `session/prompt`, `session/cancel`,
6157    /// and `session/update`.
6158    #[serde_as(deserialize_as = "DefaultOnError")]
6159    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6160    #[serde(default)]
6161    pub session: Option<SessionCapabilities>,
6162    /// Authentication-related extension capabilities supported by the agent.
6163    ///
6164    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise any
6165    /// authentication-related extensions. This field does not advertise support
6166    /// for `auth/login` or `auth/logout`. Those methods are advertised by a
6167    /// non-empty `authMethods` list in the `initialize` response.
6168    #[serde_as(deserialize_as = "DefaultOnError")]
6169    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6170    #[serde(default)]
6171    pub auth: Option<AgentAuthCapabilities>,
6172    /// **UNSTABLE**
6173    ///
6174    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6175    ///
6176    /// Provider configuration capabilities supported by the agent.
6177    ///
6178    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
6179    /// Supplying `{}` means the agent supports provider configuration methods.
6180    #[cfg(feature = "unstable_llm_providers")]
6181    #[serde_as(deserialize_as = "DefaultOnError")]
6182    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6183    #[serde(default)]
6184    pub providers: Option<ProvidersCapabilities>,
6185    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6186    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6187    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6188    ///
6189    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6190    #[serde_as(deserialize_as = "DefaultOnError")]
6191    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6192    #[serde(default)]
6193    #[serde(rename = "_meta")]
6194    pub meta: Option<Meta>,
6195}
6196
6197impl AgentCapabilities {
6198    /// Builds an empty [`AgentCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6199    #[must_use]
6200    pub fn new() -> Self {
6201        Self::default()
6202    }
6203
6204    /// Session capabilities supported by the agent.
6205    ///
6206    /// Omitted and `null` are equivalent and mean the agent does not support the `session/*`
6207    /// methods. Supplying `{}` means the agent supports the baseline
6208    /// session methods: `session/new`, `session/list`, `session/resume`,
6209    /// `session/close`, `session/prompt`, `session/cancel`, and
6210    /// `session/update`.
6211    #[must_use]
6212    pub fn session(mut self, session: impl IntoOption<SessionCapabilities>) -> Self {
6213        self.session = session.into_option();
6214        self
6215    }
6216
6217    /// Authentication-related extension capabilities supported by the agent.
6218    ///
6219    /// This field does not advertise support for `auth/login` or `auth/logout`.
6220    #[must_use]
6221    pub fn auth(mut self, auth: impl IntoOption<AgentAuthCapabilities>) -> Self {
6222        self.auth = auth.into_option();
6223        self
6224    }
6225
6226    /// **UNSTABLE**
6227    ///
6228    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6229    ///
6230    /// Provider configuration capabilities supported by the agent.
6231    #[cfg(feature = "unstable_llm_providers")]
6232    #[must_use]
6233    pub fn providers(mut self, providers: impl IntoOption<ProvidersCapabilities>) -> Self {
6234        self.providers = providers.into_option();
6235        self
6236    }
6237
6238    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6239    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6240    /// do not recognize.
6241    ///
6242    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6243    #[must_use]
6244    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6245        self.meta = meta.into_option();
6246        self
6247    }
6248}
6249
6250/// **UNSTABLE**
6251///
6252/// This capability is not part of the spec yet, and may be removed or changed at any point.
6253///
6254/// Provider configuration capabilities supported by the agent.
6255///
6256/// Supplying `{}` means the agent supports provider configuration methods.
6257#[cfg(feature = "unstable_llm_providers")]
6258#[serde_as]
6259#[skip_serializing_none]
6260#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6261#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6262#[non_exhaustive]
6263pub struct ProvidersCapabilities {
6264    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6265    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6266    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6267    ///
6268    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6269    #[serde_as(deserialize_as = "DefaultOnError")]
6270    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6271    #[serde(default)]
6272    #[serde(rename = "_meta")]
6273    pub meta: Option<Meta>,
6274}
6275
6276#[cfg(feature = "unstable_llm_providers")]
6277impl ProvidersCapabilities {
6278    /// Builds an empty [`ProvidersCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6279    #[must_use]
6280    pub fn new() -> Self {
6281        Self::default()
6282    }
6283
6284    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6285    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6286    /// do not recognize.
6287    ///
6288    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6289    #[must_use]
6290    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6291        self.meta = meta.into_option();
6292        self
6293    }
6294}
6295
6296/// Session capabilities supported by the agent.
6297///
6298/// Supplying `{}` means the agent supports the baseline session methods:
6299/// `session/new`, `session/list`, `session/resume`, `session/close`,
6300/// `session/prompt`, `session/cancel`, and `session/update`.
6301///
6302/// Agents that support sessions **MAY** support additional session methods,
6303/// prompt content types, and MCP transports by specifying additional
6304/// capabilities.
6305///
6306/// See protocol docs: [Session Capabilities](https://agentclientprotocol.com/protocol/v2/initialization#session-capabilities)
6307#[serde_as]
6308#[skip_serializing_none]
6309#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6310#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6311#[serde(rename_all = "camelCase")]
6312#[non_exhaustive]
6313pub struct SessionCapabilities {
6314    /// Prompt capabilities supported by the agent in `session/prompt` requests.
6315    ///
6316    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise any
6317    /// prompt extensions beyond the baseline text and resource-link content
6318    /// required by `session/prompt`.
6319    #[serde_as(deserialize_as = "DefaultOnError")]
6320    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6321    #[serde(default)]
6322    pub prompt: Option<PromptCapabilities>,
6323    /// MCP capabilities supported by the agent for session lifecycle requests.
6324    ///
6325    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise MCP
6326    /// server transport support for sessions.
6327    #[serde_as(deserialize_as = "DefaultOnError")]
6328    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6329    #[serde(default)]
6330    pub mcp: Option<McpCapabilities>,
6331    /// Whether the agent supports `session/delete`.
6332    ///
6333    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
6334    /// Supplying `{}` means the agent supports deleting sessions from `session/list`.
6335    #[serde_as(deserialize_as = "DefaultOnError")]
6336    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6337    #[serde(default)]
6338    pub delete: Option<SessionDeleteCapabilities>,
6339    /// Whether the agent supports `additionalDirectories` on supported session lifecycle requests.
6340    ///
6341    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
6342    /// Supplying `{}` means the agent supports `additionalDirectories` on
6343    /// supported session lifecycle requests.
6344    ///
6345    /// Agents may return `SessionInfo.additionalDirectories` to report the
6346    /// complete ordered additional-root list associated with a listed session.
6347    #[serde_as(deserialize_as = "DefaultOnError")]
6348    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6349    #[serde(default)]
6350    pub additional_directories: Option<SessionAdditionalDirectoriesCapabilities>,
6351    /// Whether the agent supports `systemPrompt` on session lifecycle requests.
6352    ///
6353    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
6354    /// Supplying `{}` means the agent supports `systemPrompt` in `append` mode.
6355    #[serde_as(deserialize_as = "DefaultOnError")]
6356    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6357    #[serde(default)]
6358    pub system_prompt: Option<SessionSystemPromptCapabilities>,
6359    /// **UNSTABLE**
6360    ///
6361    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6362    ///
6363    /// Whether the agent supports `session/fork`.
6364    ///
6365    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
6366    /// Supplying `{}` means the agent supports forking sessions.
6367    #[cfg(feature = "unstable_session_fork")]
6368    #[serde_as(deserialize_as = "DefaultOnError")]
6369    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6370    #[serde(default)]
6371    pub fork: Option<SessionForkCapabilities>,
6372    /// **UNSTABLE**
6373    ///
6374    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6375    ///
6376    /// Whether the agent supports `session/archive` and `session/unarchive`.
6377    ///
6378    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
6379    /// Supplying `{}` means the agent supports both methods, the `archived` filter on
6380    /// `session/list`, and `SessionInfo.archived`.
6381    #[cfg(feature = "unstable_session_archive")]
6382    #[serde_as(deserialize_as = "DefaultOnError")]
6383    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6384    #[serde(default)]
6385    pub archive: Option<SessionArchiveCapabilities>,
6386    /// **UNSTABLE**
6387    ///
6388    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6389    ///
6390    /// Whether the agent supports `session/status`.
6391    ///
6392    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
6393    /// Supplying `{}` means the agent supports checking session status.
6394    #[cfg(feature = "unstable_session_status")]
6395    #[serde_as(deserialize_as = "DefaultOnError")]
6396    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6397    #[serde(default)]
6398    pub status: Option<SessionStatusCapabilities>,
6399    /// **UNSTABLE**
6400    ///
6401    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6402    ///
6403    /// Whether the agent supports `session/options`.
6404    ///
6405    /// Optional. Omitted or `null` both mean the agent does not advertise support.
6406    /// Supplying `{}` means the agent supports `session/options` and accepts initial
6407    /// config option values on session setup requests.
6408    #[cfg(feature = "unstable_session_options")]
6409    #[serde_as(deserialize_as = "DefaultOnError")]
6410    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6411    #[serde(default)]
6412    pub options: Option<SessionOptionsCapabilities>,
6413    /// **UNSTABLE**
6414    ///
6415    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6416    ///
6417    /// Whether the agent supports `session/set_title`.
6418    ///
6419    /// Agents report titles through `session/list` and `session_info_update` without this
6420    /// capability. It only advertises that Clients can set titles.
6421    ///
6422    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
6423    /// Supplying `{}` means the agent supports setting session titles.
6424    #[cfg(feature = "unstable_session_set_title")]
6425    #[serde_as(deserialize_as = "DefaultOnError")]
6426    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6427    #[serde(default)]
6428    pub title: Option<SessionTitleCapabilities>,
6429    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6430    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6431    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6432    ///
6433    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6434    #[serde_as(deserialize_as = "DefaultOnError")]
6435    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6436    #[serde(default)]
6437    #[serde(rename = "_meta")]
6438    pub meta: Option<Meta>,
6439}
6440
6441impl SessionCapabilities {
6442    /// Builds an empty [`SessionCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6443    #[must_use]
6444    pub fn new() -> Self {
6445        Self::default()
6446    }
6447
6448    /// Prompt capabilities supported by the agent in `session/prompt` requests.
6449    ///
6450    /// Omitted and `null` are equivalent and mean the agent does not advertise any prompt
6451    /// extensions beyond the baseline text and resource-link content required by
6452    /// `session/prompt`.
6453    #[must_use]
6454    pub fn prompt(mut self, prompt: impl IntoOption<PromptCapabilities>) -> Self {
6455        self.prompt = prompt.into_option();
6456        self
6457    }
6458
6459    /// MCP capabilities supported by the agent for session lifecycle requests.
6460    ///
6461    /// Omitted and `null` are equivalent and mean the agent does not advertise MCP server
6462    /// transport support for sessions.
6463    #[must_use]
6464    pub fn mcp(mut self, mcp: impl IntoOption<McpCapabilities>) -> Self {
6465        self.mcp = mcp.into_option();
6466        self
6467    }
6468
6469    /// Whether the agent supports `session/delete`.
6470    ///
6471    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
6472    /// Supplying `{}` means the agent supports deleting sessions from `session/list`.
6473    #[must_use]
6474    pub fn delete(mut self, delete: impl IntoOption<SessionDeleteCapabilities>) -> Self {
6475        self.delete = delete.into_option();
6476        self
6477    }
6478
6479    /// Whether the agent supports `additionalDirectories` on supported session lifecycle requests.
6480    ///
6481    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
6482    /// Supplying `{}` means the agent supports `additionalDirectories` on
6483    /// supported session lifecycle requests.
6484    ///
6485    /// Agents may return `SessionInfo.additionalDirectories` to report the
6486    /// complete ordered additional-root list associated with a listed session.
6487    #[must_use]
6488    pub fn additional_directories(
6489        mut self,
6490        additional_directories: impl IntoOption<SessionAdditionalDirectoriesCapabilities>,
6491    ) -> Self {
6492        self.additional_directories = additional_directories.into_option();
6493        self
6494    }
6495
6496    /// Whether the agent supports `systemPrompt` on session lifecycle requests.
6497    ///
6498    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
6499    /// Supplying `{}` means the agent supports `systemPrompt` in `append` mode.
6500    #[must_use]
6501    pub fn system_prompt(
6502        mut self,
6503        system_prompt: impl IntoOption<SessionSystemPromptCapabilities>,
6504    ) -> Self {
6505        self.system_prompt = system_prompt.into_option();
6506        self
6507    }
6508
6509    #[cfg(feature = "unstable_session_fork")]
6510    /// Whether the agent supports `session/fork`.
6511    ///
6512    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
6513    /// Supplying `{}` means the agent supports forking sessions.
6514    #[must_use]
6515    pub fn fork(mut self, fork: impl IntoOption<SessionForkCapabilities>) -> Self {
6516        self.fork = fork.into_option();
6517        self
6518    }
6519
6520    /// **UNSTABLE**
6521    ///
6522    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6523    ///
6524    /// Whether the agent supports `session/archive` and `session/unarchive`.
6525    ///
6526    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
6527    /// Supplying `{}` means the agent supports both methods, the `archived` filter on
6528    /// `session/list`, and `SessionInfo.archived`.
6529    #[cfg(feature = "unstable_session_archive")]
6530    #[must_use]
6531    pub fn archive(mut self, archive: impl IntoOption<SessionArchiveCapabilities>) -> Self {
6532        self.archive = archive.into_option();
6533        self
6534    }
6535
6536    /// **UNSTABLE**
6537    ///
6538    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6539    ///
6540    /// Whether the agent supports `session/status`.
6541    ///
6542    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
6543    /// Supplying `{}` means the agent supports checking session status.
6544    #[cfg(feature = "unstable_session_status")]
6545    #[must_use]
6546    pub fn status(mut self, status: impl IntoOption<SessionStatusCapabilities>) -> Self {
6547        self.status = status.into_option();
6548        self
6549    }
6550
6551    /// **UNSTABLE**
6552    ///
6553    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6554    ///
6555    /// Whether the agent supports `session/options`.
6556    ///
6557    /// Omitted or `null` both mean the agent does not advertise support.
6558    /// Supplying `{}` means the agent supports `session/options` and accepts initial
6559    /// config option values on session setup requests.
6560    #[cfg(feature = "unstable_session_options")]
6561    #[must_use]
6562    pub fn options(mut self, options: impl IntoOption<SessionOptionsCapabilities>) -> Self {
6563        self.options = options.into_option();
6564        self
6565    }
6566
6567    /// **UNSTABLE**
6568    ///
6569    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6570    ///
6571    /// Whether the agent supports `session/set_title`.
6572    ///
6573    /// Agents report titles through `session/list` and `session_info_update` without this
6574    /// capability. It only advertises that Clients can set titles.
6575    ///
6576    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
6577    /// Supplying `{}` means the agent supports setting session titles.
6578    #[cfg(feature = "unstable_session_set_title")]
6579    #[must_use]
6580    pub fn title(mut self, title: impl IntoOption<SessionTitleCapabilities>) -> Self {
6581        self.title = title.into_option();
6582        self
6583    }
6584
6585    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6586    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6587    /// do not recognize.
6588    ///
6589    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6590    #[must_use]
6591    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6592        self.meta = meta.into_option();
6593        self
6594    }
6595}
6596
6597/// Capabilities for the `session/delete` method.
6598///
6599/// Supplying `{}` means the agent supports deleting sessions from `session/list`.
6600#[serde_as]
6601#[skip_serializing_none]
6602#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6603#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6604#[non_exhaustive]
6605pub struct SessionDeleteCapabilities {
6606    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6607    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6608    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6609    ///
6610    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6611    #[serde_as(deserialize_as = "DefaultOnError")]
6612    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6613    #[serde(default)]
6614    #[serde(rename = "_meta")]
6615    pub meta: Option<Meta>,
6616}
6617
6618impl SessionDeleteCapabilities {
6619    /// Builds an empty [`SessionDeleteCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6620    #[must_use]
6621    pub fn new() -> Self {
6622        Self::default()
6623    }
6624
6625    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6626    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6627    /// do not recognize.
6628    ///
6629    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6630    #[must_use]
6631    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6632        self.meta = meta.into_option();
6633        self
6634    }
6635}
6636
6637/// Capabilities for additional session directories support.
6638///
6639/// Supplying `{}` means the agent supports the `additionalDirectories` field on
6640/// supported session lifecycle requests. Agents may return
6641/// `SessionInfo.additionalDirectories` in `session/list` to report the
6642/// complete ordered additional-root list associated with a listed session.
6643#[serde_as]
6644#[skip_serializing_none]
6645#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6646#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6647#[non_exhaustive]
6648pub struct SessionAdditionalDirectoriesCapabilities {
6649    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6650    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6651    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6652    ///
6653    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6654    #[serde_as(deserialize_as = "DefaultOnError")]
6655    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6656    #[serde(default)]
6657    #[serde(rename = "_meta")]
6658    pub meta: Option<Meta>,
6659}
6660
6661impl SessionAdditionalDirectoriesCapabilities {
6662    /// Builds an empty [`SessionAdditionalDirectoriesCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6663    #[must_use]
6664    pub fn new() -> Self {
6665        Self::default()
6666    }
6667
6668    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6669    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6670    /// do not recognize.
6671    ///
6672    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6673    #[must_use]
6674    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6675        self.meta = meta.into_option();
6676        self
6677    }
6678}
6679
6680/// Capabilities for client-provided system prompts.
6681///
6682/// Supplying `{}` means the agent supports `systemPrompt` on session lifecycle
6683/// requests in `append` mode.
6684#[serde_as]
6685#[skip_serializing_none]
6686#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6687#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6688#[serde(rename_all = "camelCase")]
6689#[non_exhaustive]
6690pub struct SessionSystemPromptCapabilities {
6691    /// Delivery modes the agent supports in addition to `append`.
6692    ///
6693    /// Optional. Omitted and `null` are equivalent and mean the agent supports only `append`.
6694    #[serde_as(deserialize_as = "DefaultOnError")]
6695    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6696    #[serde(default)]
6697    pub mode: Option<SessionSystemPromptModeCapabilities>,
6698    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6699    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6700    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6701    ///
6702    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6703    #[serde_as(deserialize_as = "DefaultOnError")]
6704    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6705    #[serde(default)]
6706    #[serde(rename = "_meta")]
6707    pub meta: Option<Meta>,
6708}
6709
6710impl SessionSystemPromptCapabilities {
6711    /// Builds an empty [`SessionSystemPromptCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6712    #[must_use]
6713    pub fn new() -> Self {
6714        Self::default()
6715    }
6716
6717    /// Delivery modes the agent supports in addition to `append`.
6718    ///
6719    /// Omitted and `null` are equivalent and mean the agent supports only `append`.
6720    #[must_use]
6721    pub fn mode(mut self, mode: impl IntoOption<SessionSystemPromptModeCapabilities>) -> Self {
6722        self.mode = mode.into_option();
6723        self
6724    }
6725
6726    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6727    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6728    /// do not recognize.
6729    ///
6730    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6731    #[must_use]
6732    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6733        self.meta = meta.into_option();
6734        self
6735    }
6736}
6737
6738/// System prompt delivery modes the agent supports in addition to `append`.
6739///
6740/// `append` has no entry because every agent advertising `session.systemPrompt`
6741/// supports it.
6742#[serde_as]
6743#[skip_serializing_none]
6744#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6745#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6746#[serde(rename_all = "camelCase")]
6747#[non_exhaustive]
6748pub struct SessionSystemPromptModeCapabilities {
6749    /// Whether the agent supports `override` mode.
6750    ///
6751    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
6752    /// Supplying `{}` means the agent supports replacing its built-in default
6753    /// instructions with the client-provided system prompt.
6754    #[serde_as(deserialize_as = "DefaultOnError")]
6755    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6756    #[serde(default, rename = "override")]
6757    pub override_: Option<SessionSystemPromptOverrideCapabilities>,
6758    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6759    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6760    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6761    ///
6762    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6763    #[serde_as(deserialize_as = "DefaultOnError")]
6764    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6765    #[serde(default)]
6766    #[serde(rename = "_meta")]
6767    pub meta: Option<Meta>,
6768}
6769
6770impl SessionSystemPromptModeCapabilities {
6771    /// Builds an empty [`SessionSystemPromptModeCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6772    #[must_use]
6773    pub fn new() -> Self {
6774        Self::default()
6775    }
6776
6777    /// Whether the agent supports `override` mode.
6778    ///
6779    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
6780    /// Supplying `{}` means the agent supports replacing its built-in default
6781    /// instructions with the client-provided system prompt.
6782    #[must_use]
6783    pub fn override_(
6784        mut self,
6785        override_: impl IntoOption<SessionSystemPromptOverrideCapabilities>,
6786    ) -> Self {
6787        self.override_ = override_.into_option();
6788        self
6789    }
6790
6791    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6792    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6793    /// do not recognize.
6794    ///
6795    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6796    #[must_use]
6797    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6798        self.meta = meta.into_option();
6799        self
6800    }
6801}
6802
6803/// Capabilities for the `override` system prompt mode.
6804///
6805/// Supplying `{}` means the agent supports replacing its built-in default
6806/// instructions with the client-provided system prompt.
6807#[serde_as]
6808#[skip_serializing_none]
6809#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6810#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6811#[non_exhaustive]
6812pub struct SessionSystemPromptOverrideCapabilities {
6813    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6814    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6815    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6816    ///
6817    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6818    #[serde_as(deserialize_as = "DefaultOnError")]
6819    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6820    #[serde(default)]
6821    #[serde(rename = "_meta")]
6822    pub meta: Option<Meta>,
6823}
6824
6825impl SessionSystemPromptOverrideCapabilities {
6826    /// Builds an empty [`SessionSystemPromptOverrideCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6827    #[must_use]
6828    pub fn new() -> Self {
6829        Self::default()
6830    }
6831
6832    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6833    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6834    /// do not recognize.
6835    ///
6836    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6837    #[must_use]
6838    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6839        self.meta = meta.into_option();
6840        self
6841    }
6842}
6843
6844/// **UNSTABLE**
6845///
6846/// This capability is not part of the spec yet, and may be removed or changed at any point.
6847///
6848/// Capabilities for the `session/fork` method.
6849///
6850/// Supplying `{}` means the agent supports forking sessions.
6851#[cfg(feature = "unstable_session_fork")]
6852#[serde_as]
6853#[skip_serializing_none]
6854#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6855#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6856#[non_exhaustive]
6857pub struct SessionForkCapabilities {
6858    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6859    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6860    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6861    ///
6862    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6863    #[serde_as(deserialize_as = "DefaultOnError")]
6864    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6865    #[serde(default)]
6866    #[serde(rename = "_meta")]
6867    pub meta: Option<Meta>,
6868}
6869
6870#[cfg(feature = "unstable_session_fork")]
6871impl SessionForkCapabilities {
6872    /// Builds an empty [`SessionForkCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6873    #[must_use]
6874    pub fn new() -> Self {
6875        Self::default()
6876    }
6877
6878    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6879    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6880    /// do not recognize.
6881    ///
6882    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6883    #[must_use]
6884    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6885        self.meta = meta.into_option();
6886        self
6887    }
6888}
6889
6890/// **UNSTABLE**
6891///
6892/// This capability is not part of the spec yet, and may be removed or changed at any point.
6893///
6894/// Capabilities for `session/archive` and `session/unarchive`.
6895///
6896/// Supplying `{}` means the agent supports both methods, the `archived` filter on
6897/// `session/list`, and `SessionInfo.archived`.
6898#[cfg(feature = "unstable_session_archive")]
6899#[serde_as]
6900#[skip_serializing_none]
6901#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6902#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6903#[non_exhaustive]
6904pub struct SessionArchiveCapabilities {
6905    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6906    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6907    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6908    ///
6909    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6910    #[serde_as(deserialize_as = "DefaultOnError")]
6911    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6912    #[serde(default)]
6913    #[serde(rename = "_meta")]
6914    pub meta: Option<Meta>,
6915}
6916
6917#[cfg(feature = "unstable_session_archive")]
6918impl SessionArchiveCapabilities {
6919    /// Builds an empty [`SessionArchiveCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6920    #[must_use]
6921    pub fn new() -> Self {
6922        Self::default()
6923    }
6924
6925    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6926    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6927    /// do not recognize.
6928    ///
6929    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6930    #[must_use]
6931    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6932        self.meta = meta.into_option();
6933        self
6934    }
6935}
6936
6937/// **UNSTABLE**
6938///
6939/// This capability is not part of the spec yet, and may be removed or changed at any point.
6940///
6941/// Capabilities for the `session/status` method.
6942///
6943/// Supplying `{}` means the agent supports checking session status.
6944#[cfg(feature = "unstable_session_status")]
6945#[serde_as]
6946#[skip_serializing_none]
6947#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6948#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6949#[non_exhaustive]
6950pub struct SessionStatusCapabilities {
6951    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6952    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6953    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6954    ///
6955    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6956    #[serde_as(deserialize_as = "DefaultOnError")]
6957    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6958    #[serde(default)]
6959    #[serde(rename = "_meta")]
6960    pub meta: Option<Meta>,
6961}
6962
6963#[cfg(feature = "unstable_session_status")]
6964impl SessionStatusCapabilities {
6965    /// Builds an empty [`SessionStatusCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6966    #[must_use]
6967    pub fn new() -> Self {
6968        Self::default()
6969    }
6970
6971    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6972    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6973    /// do not recognize.
6974    ///
6975    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6976    #[must_use]
6977    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6978        self.meta = meta.into_option();
6979        self
6980    }
6981}
6982
6983/// **UNSTABLE**
6984///
6985/// This capability is not part of the spec yet, and may be removed or changed at any point.
6986///
6987/// Capabilities for the `session/options` method.
6988///
6989/// Supplying `{}` means the agent supports `session/options` and accepts initial config
6990/// option values on session setup requests.
6991#[cfg(feature = "unstable_session_options")]
6992#[serde_as]
6993#[skip_serializing_none]
6994#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6995#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6996#[non_exhaustive]
6997pub struct SessionOptionsCapabilities {
6998    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6999    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7000    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7001    ///
7002    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7003    #[serde_as(deserialize_as = "DefaultOnError")]
7004    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7005    #[serde(default)]
7006    #[serde(rename = "_meta")]
7007    pub meta: Option<Meta>,
7008}
7009
7010#[cfg(feature = "unstable_session_options")]
7011impl SessionOptionsCapabilities {
7012    /// Builds an empty [`SessionOptionsCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7013    #[must_use]
7014    pub fn new() -> Self {
7015        Self::default()
7016    }
7017
7018    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7019    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7020    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7021    ///
7022    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7023    #[must_use]
7024    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7025        self.meta = meta.into_option();
7026        self
7027    }
7028}
7029
7030/// **UNSTABLE**
7031///
7032/// This capability is not part of the spec yet, and may be removed or changed at any point.
7033///
7034/// Capabilities for Client-set session titles.
7035///
7036/// Supplying `{}` means the agent supports `session/set_title`. Agents report titles
7037/// through `session/list` and `session_info_update` without this capability.
7038#[cfg(feature = "unstable_session_set_title")]
7039#[serde_as]
7040#[skip_serializing_none]
7041#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7042#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7043#[non_exhaustive]
7044pub struct SessionTitleCapabilities {
7045    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7046    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7047    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7048    ///
7049    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7050    #[serde_as(deserialize_as = "DefaultOnError")]
7051    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7052    #[serde(default)]
7053    #[serde(rename = "_meta")]
7054    pub meta: Option<Meta>,
7055}
7056
7057#[cfg(feature = "unstable_session_set_title")]
7058impl SessionTitleCapabilities {
7059    /// Builds an empty [`SessionTitleCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7060    #[must_use]
7061    pub fn new() -> Self {
7062        Self::default()
7063    }
7064
7065    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7066    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7067    /// do not recognize.
7068    ///
7069    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7070    #[must_use]
7071    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7072        self.meta = meta.into_option();
7073        self
7074    }
7075}
7076
7077/// Prompt capabilities supported by the agent in `session/prompt` requests.
7078///
7079/// Baseline agent functionality requires support for `text`
7080/// and `resource_link` content blocks in prompt requests.
7081///
7082/// Other variants must be explicitly opted in to.
7083/// Capabilities for different types of content in prompt requests.
7084///
7085/// Indicates which content types beyond the baseline (text and resource links)
7086/// the agent can process.
7087///
7088/// See protocol docs: [Session Prompt Capabilities](https://agentclientprotocol.com/protocol/v2/initialization#session-prompt-capabilities)
7089#[serde_as]
7090#[skip_serializing_none]
7091#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7092#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7093#[serde(rename_all = "camelCase")]
7094#[non_exhaustive]
7095pub struct PromptCapabilities {
7096    /// Agent supports `image` content blocks.
7097    ///
7098    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
7099    /// Supplying `{}` means the agent supports image content in prompts.
7100    #[serde_as(deserialize_as = "DefaultOnError")]
7101    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7102    #[serde(default)]
7103    pub image: Option<PromptImageCapabilities>,
7104    /// Agent supports `audio` content blocks.
7105    ///
7106    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
7107    /// Supplying `{}` means the agent supports audio content in prompts.
7108    #[serde_as(deserialize_as = "DefaultOnError")]
7109    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7110    #[serde(default)]
7111    pub audio: Option<PromptAudioCapabilities>,
7112    /// Agent supports embedded context in `session/prompt` requests.
7113    ///
7114    /// When enabled, the Client is allowed to include `resource` content blocks
7115    /// in prompt requests for pieces of context that are referenced in the message.
7116    ///
7117    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
7118    /// Supplying `{}` means the agent supports embedded context in prompts.
7119    #[serde_as(deserialize_as = "DefaultOnError")]
7120    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7121    #[serde(default)]
7122    pub embedded_context: Option<PromptEmbeddedContextCapabilities>,
7123    /// **UNSTABLE**
7124    ///
7125    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7126    ///
7127    /// Agent supports `skill` content blocks.
7128    ///
7129    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
7130    /// Supplying `{}` means a prompt may contain one `skill` content block, as its first block.
7131    /// An agent that sends `skill` entries in `availableCommands` MUST advertise this capability.
7132    #[cfg(feature = "unstable_agent_skills")]
7133    #[serde_as(deserialize_as = "DefaultOnError")]
7134    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7135    #[serde(default)]
7136    pub skill: Option<PromptSkillCapabilities>,
7137    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7138    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7139    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7140    ///
7141    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7142    #[serde_as(deserialize_as = "DefaultOnError")]
7143    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7144    #[serde(default)]
7145    #[serde(rename = "_meta")]
7146    pub meta: Option<Meta>,
7147}
7148
7149impl PromptCapabilities {
7150    /// Builds an empty [`PromptCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7151    #[must_use]
7152    pub fn new() -> Self {
7153        Self::default()
7154    }
7155
7156    /// Agent supports `image` content blocks.
7157    ///
7158    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
7159    /// Supplying `{}` means the agent supports image content in prompts.
7160    #[must_use]
7161    pub fn image(mut self, image: impl IntoOption<PromptImageCapabilities>) -> Self {
7162        self.image = image.into_option();
7163        self
7164    }
7165
7166    /// Agent supports `audio` content blocks.
7167    ///
7168    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
7169    /// Supplying `{}` means the agent supports audio content in prompts.
7170    #[must_use]
7171    pub fn audio(mut self, audio: impl IntoOption<PromptAudioCapabilities>) -> Self {
7172        self.audio = audio.into_option();
7173        self
7174    }
7175
7176    /// Agent supports embedded context in `session/prompt` requests.
7177    ///
7178    /// When enabled, the Client is allowed to include `resource` content blocks
7179    /// in prompt requests for pieces of context that are referenced in the message.
7180    ///
7181    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
7182    /// Supplying `{}` means the agent supports embedded context in prompts.
7183    #[must_use]
7184    pub fn embedded_context(
7185        mut self,
7186        embedded_context: impl IntoOption<PromptEmbeddedContextCapabilities>,
7187    ) -> Self {
7188        self.embedded_context = embedded_context.into_option();
7189        self
7190    }
7191
7192    /// **UNSTABLE**
7193    ///
7194    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7195    ///
7196    /// Agent supports `skill` content blocks.
7197    ///
7198    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
7199    /// Supplying `{}` means a prompt may contain one `skill` content block, as its first block.
7200    #[cfg(feature = "unstable_agent_skills")]
7201    #[must_use]
7202    pub fn skill(mut self, skill: impl IntoOption<PromptSkillCapabilities>) -> Self {
7203        self.skill = skill.into_option();
7204        self
7205    }
7206
7207    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7208    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7209    /// do not recognize.
7210    ///
7211    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7212    #[must_use]
7213    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7214        self.meta = meta.into_option();
7215        self
7216    }
7217}
7218
7219/// Capabilities for image content in prompt requests.
7220///
7221/// Supplying `{}` means the agent supports image content in prompts.
7222#[serde_as]
7223#[skip_serializing_none]
7224#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7225#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7226#[non_exhaustive]
7227pub struct PromptImageCapabilities {
7228    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7229    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7230    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7231    ///
7232    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7233    #[serde_as(deserialize_as = "DefaultOnError")]
7234    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7235    #[serde(default)]
7236    #[serde(rename = "_meta")]
7237    pub meta: Option<Meta>,
7238}
7239
7240impl PromptImageCapabilities {
7241    /// Builds an empty [`PromptImageCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7242    #[must_use]
7243    pub fn new() -> Self {
7244        Self::default()
7245    }
7246
7247    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7248    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7249    /// do not recognize.
7250    ///
7251    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7252    #[must_use]
7253    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7254        self.meta = meta.into_option();
7255        self
7256    }
7257}
7258
7259/// Capabilities for audio content in prompt requests.
7260///
7261/// Supplying `{}` means the agent supports audio content in prompts.
7262#[serde_as]
7263#[skip_serializing_none]
7264#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7265#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7266#[non_exhaustive]
7267pub struct PromptAudioCapabilities {
7268    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7269    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7270    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7271    ///
7272    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7273    #[serde_as(deserialize_as = "DefaultOnError")]
7274    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7275    #[serde(default)]
7276    #[serde(rename = "_meta")]
7277    pub meta: Option<Meta>,
7278}
7279
7280impl PromptAudioCapabilities {
7281    /// Builds an empty [`PromptAudioCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7282    #[must_use]
7283    pub fn new() -> Self {
7284        Self::default()
7285    }
7286
7287    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7288    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7289    /// do not recognize.
7290    ///
7291    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7292    #[must_use]
7293    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7294        self.meta = meta.into_option();
7295        self
7296    }
7297}
7298
7299/// Capabilities for embedded context in prompt requests.
7300///
7301/// Supplying `{}` means the agent supports embedded context in prompts.
7302#[serde_as]
7303#[skip_serializing_none]
7304#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7305#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7306#[non_exhaustive]
7307pub struct PromptEmbeddedContextCapabilities {
7308    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7309    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7310    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7311    ///
7312    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7313    #[serde_as(deserialize_as = "DefaultOnError")]
7314    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7315    #[serde(default)]
7316    #[serde(rename = "_meta")]
7317    pub meta: Option<Meta>,
7318}
7319
7320impl PromptEmbeddedContextCapabilities {
7321    /// Builds an empty [`PromptEmbeddedContextCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7322    #[must_use]
7323    pub fn new() -> Self {
7324        Self::default()
7325    }
7326
7327    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7328    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7329    /// do not recognize.
7330    ///
7331    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7332    #[must_use]
7333    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7334        self.meta = meta.into_option();
7335        self
7336    }
7337}
7338
7339/// **UNSTABLE**
7340///
7341/// This capability is not part of the spec yet, and may be removed or changed at any point.
7342///
7343/// Capabilities for `skill` content blocks in prompt requests.
7344///
7345/// Supplying `{}` means a prompt may contain one `skill` content block, as
7346/// its first block. The agent opts in to more with the `inline` field.
7347#[cfg(feature = "unstable_agent_skills")]
7348#[serde_as]
7349#[skip_serializing_none]
7350#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7351#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7352#[serde(rename_all = "camelCase")]
7353#[non_exhaustive]
7354pub struct PromptSkillCapabilities {
7355    /// Agent supports `skill` content blocks at any position in a prompt.
7356    ///
7357    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
7358    /// Supplying `{}` means a prompt may contain any number of `skill` content blocks, at any
7359    /// position.
7360    #[serde_as(deserialize_as = "DefaultOnError")]
7361    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7362    #[serde(default)]
7363    pub inline: Option<PromptSkillInlineCapabilities>,
7364    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7365    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7366    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7367    ///
7368    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7369    #[serde_as(deserialize_as = "DefaultOnError")]
7370    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7371    #[serde(default)]
7372    #[serde(rename = "_meta")]
7373    pub meta: Option<Meta>,
7374}
7375
7376#[cfg(feature = "unstable_agent_skills")]
7377impl PromptSkillCapabilities {
7378    /// Builds an empty [`PromptSkillCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7379    #[must_use]
7380    pub fn new() -> Self {
7381        Self::default()
7382    }
7383
7384    /// Agent supports `skill` content blocks at any position in a prompt.
7385    ///
7386    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
7387    /// Supplying `{}` means a prompt may contain any number of `skill` content blocks, at any
7388    /// position.
7389    #[must_use]
7390    pub fn inline(mut self, inline: impl IntoOption<PromptSkillInlineCapabilities>) -> Self {
7391        self.inline = inline.into_option();
7392        self
7393    }
7394
7395    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7396    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7397    /// do not recognize.
7398    ///
7399    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7400    #[must_use]
7401    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7402        self.meta = meta.into_option();
7403        self
7404    }
7405}
7406
7407/// **UNSTABLE**
7408///
7409/// This capability is not part of the spec yet, and may be removed or changed at any point.
7410///
7411/// Capabilities for `skill` content blocks at any position in a prompt.
7412///
7413/// Supplying `{}` means a prompt may contain any number of `skill` content
7414/// blocks, at any position.
7415#[cfg(feature = "unstable_agent_skills")]
7416#[serde_as]
7417#[skip_serializing_none]
7418#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7419#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7420#[non_exhaustive]
7421pub struct PromptSkillInlineCapabilities {
7422    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7423    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7424    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7425    ///
7426    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7427    #[serde_as(deserialize_as = "DefaultOnError")]
7428    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7429    #[serde(default)]
7430    #[serde(rename = "_meta")]
7431    pub meta: Option<Meta>,
7432}
7433
7434#[cfg(feature = "unstable_agent_skills")]
7435impl PromptSkillInlineCapabilities {
7436    /// Builds an empty [`PromptSkillInlineCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7437    #[must_use]
7438    pub fn new() -> Self {
7439        Self::default()
7440    }
7441
7442    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7443    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7444    /// do not recognize.
7445    ///
7446    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7447    #[must_use]
7448    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7449        self.meta = meta.into_option();
7450        self
7451    }
7452}
7453
7454/// MCP capabilities supported by the agent for session lifecycle requests.
7455#[serde_as]
7456#[skip_serializing_none]
7457#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7458#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7459#[serde(rename_all = "camelCase")]
7460#[non_exhaustive]
7461pub struct McpCapabilities {
7462    /// Agent supports `stdio` MCP servers.
7463    ///
7464    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
7465    /// Supplying `{}` means the agent supports stdio MCP server transports.
7466    #[serde_as(deserialize_as = "DefaultOnError")]
7467    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7468    #[serde(default)]
7469    pub stdio: Option<McpStdioCapabilities>,
7470    /// Agent supports `http` MCP servers.
7471    ///
7472    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
7473    /// Supplying `{}` means the agent supports HTTP MCP server transports.
7474    #[serde_as(deserialize_as = "DefaultOnError")]
7475    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7476    #[serde(default)]
7477    pub http: Option<McpHttpCapabilities>,
7478    /// **UNSTABLE**
7479    ///
7480    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7481    ///
7482    /// Agent supports `acp` MCP servers.
7483    ///
7484    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
7485    /// Supplying `{}` means the agent supports ACP MCP server transports.
7486    #[cfg(feature = "unstable_mcp_over_acp")]
7487    #[serde_as(deserialize_as = "DefaultOnError")]
7488    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7489    #[serde(default)]
7490    pub acp: Option<McpAcpCapabilities>,
7491    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7492    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7493    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7494    ///
7495    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7496    #[serde_as(deserialize_as = "DefaultOnError")]
7497    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7498    #[serde(default)]
7499    #[serde(rename = "_meta")]
7500    pub meta: Option<Meta>,
7501}
7502
7503impl McpCapabilities {
7504    /// Builds an empty [`McpCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7505    #[must_use]
7506    pub fn new() -> Self {
7507        Self::default()
7508    }
7509
7510    /// Agent supports `stdio` MCP servers.
7511    ///
7512    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
7513    /// Supplying `{}` means the agent supports stdio MCP server transports.
7514    #[must_use]
7515    pub fn stdio(mut self, stdio: impl IntoOption<McpStdioCapabilities>) -> Self {
7516        self.stdio = stdio.into_option();
7517        self
7518    }
7519
7520    /// Agent supports `http` MCP servers.
7521    ///
7522    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
7523    /// Supplying `{}` means the agent supports HTTP MCP server transports.
7524    #[must_use]
7525    pub fn http(mut self, http: impl IntoOption<McpHttpCapabilities>) -> Self {
7526        self.http = http.into_option();
7527        self
7528    }
7529
7530    /// **UNSTABLE**
7531    ///
7532    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7533    ///
7534    /// Agent supports `acp` MCP servers.
7535    #[cfg(feature = "unstable_mcp_over_acp")]
7536    ///
7537    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
7538    /// Supplying `{}` means the agent supports ACP MCP server transports.
7539    #[must_use]
7540    pub fn acp(mut self, acp: impl IntoOption<McpAcpCapabilities>) -> Self {
7541        self.acp = acp.into_option();
7542        self
7543    }
7544
7545    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7546    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7547    /// do not recognize.
7548    ///
7549    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7550    #[must_use]
7551    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7552        self.meta = meta.into_option();
7553        self
7554    }
7555}
7556
7557/// Capabilities for stdio MCP server transports.
7558///
7559/// Supplying `{}` means the agent supports stdio MCP server transports.
7560#[serde_as]
7561#[skip_serializing_none]
7562#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7563#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7564#[non_exhaustive]
7565pub struct McpStdioCapabilities {
7566    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7567    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7568    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7569    ///
7570    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7571    #[serde_as(deserialize_as = "DefaultOnError")]
7572    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7573    #[serde(default)]
7574    #[serde(rename = "_meta")]
7575    pub meta: Option<Meta>,
7576}
7577
7578impl McpStdioCapabilities {
7579    /// Builds an empty [`McpStdioCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7580    #[must_use]
7581    pub fn new() -> Self {
7582        Self::default()
7583    }
7584
7585    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7586    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7587    /// do not recognize.
7588    ///
7589    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7590    #[must_use]
7591    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7592        self.meta = meta.into_option();
7593        self
7594    }
7595}
7596
7597/// Capabilities for HTTP MCP server transports.
7598///
7599/// Supplying `{}` means the agent supports HTTP MCP server transports.
7600#[serde_as]
7601#[skip_serializing_none]
7602#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7603#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7604#[non_exhaustive]
7605pub struct McpHttpCapabilities {
7606    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7607    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7608    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7609    ///
7610    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7611    #[serde_as(deserialize_as = "DefaultOnError")]
7612    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7613    #[serde(default)]
7614    #[serde(rename = "_meta")]
7615    pub meta: Option<Meta>,
7616}
7617
7618impl McpHttpCapabilities {
7619    /// Builds an empty [`McpHttpCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7620    #[must_use]
7621    pub fn new() -> Self {
7622        Self::default()
7623    }
7624
7625    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7626    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7627    /// do not recognize.
7628    ///
7629    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7630    #[must_use]
7631    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7632        self.meta = meta.into_option();
7633        self
7634    }
7635}
7636
7637/// **UNSTABLE**
7638///
7639/// This capability is not part of the spec yet, and may be removed or changed at any point.
7640///
7641/// Capabilities for ACP MCP server transports.
7642///
7643/// Supplying `{}` means the agent supports ACP MCP server transports.
7644#[cfg(feature = "unstable_mcp_over_acp")]
7645#[serde_as]
7646#[skip_serializing_none]
7647#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7648#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7649#[non_exhaustive]
7650pub struct McpAcpCapabilities {
7651    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7652    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7653    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7654    ///
7655    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7656    #[serde_as(deserialize_as = "DefaultOnError")]
7657    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7658    #[serde(default)]
7659    #[serde(rename = "_meta")]
7660    pub meta: Option<Meta>,
7661}
7662
7663#[cfg(feature = "unstable_mcp_over_acp")]
7664impl McpAcpCapabilities {
7665    /// Builds an empty [`McpAcpCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7666    #[must_use]
7667    pub fn new() -> Self {
7668        Self::default()
7669    }
7670
7671    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7672    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7673    /// do not recognize.
7674    ///
7675    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7676    #[must_use]
7677    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7678        self.meta = meta.into_option();
7679        self
7680    }
7681}
7682
7683/// Notification to cancel a session's foreground work and its prompts not yet inserted.
7684///
7685/// See protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#cancellation)
7686#[serde_as]
7687#[skip_serializing_none]
7688#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7689#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7690#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CANCEL_METHOD_NAME)))]
7691#[serde(rename_all = "camelCase")]
7692#[non_exhaustive]
7693pub struct CancelSessionNotification {
7694    /// The ID of the session whose foreground work to cancel.
7695    pub session_id: SessionId,
7696    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7697    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7698    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7699    ///
7700    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7701    #[serde_as(deserialize_as = "DefaultOnError")]
7702    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7703    #[serde(default)]
7704    #[serde(rename = "_meta")]
7705    pub meta: Option<Meta>,
7706}
7707
7708impl CancelSessionNotification {
7709    /// Builds [`CancelSessionNotification`] with the required notification fields set. Optional fields start unset or empty.
7710    #[must_use]
7711    pub fn new(session_id: impl Into<SessionId>) -> Self {
7712        Self {
7713            session_id: session_id.into(),
7714            meta: None,
7715        }
7716    }
7717
7718    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7719    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7720    /// do not recognize.
7721    ///
7722    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7723    #[must_use]
7724    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7725        self.meta = meta.into_option();
7726        self
7727    }
7728}
7729
7730// Method schema
7731
7732/// Names of all methods that agents handle.
7733///
7734/// Provides a centralized definition of method names used in the protocol.
7735#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7736#[non_exhaustive]
7737pub struct AgentMethodNames {
7738    /// Method for initializing the connection.
7739    pub initialize: &'static str,
7740    /// Method for authenticating with the agent.
7741    pub auth_login: &'static str,
7742    /// Method for listing configurable providers.
7743    #[cfg(feature = "unstable_llm_providers")]
7744    pub providers_list: &'static str,
7745    /// Method for setting provider configuration.
7746    #[cfg(feature = "unstable_llm_providers")]
7747    pub providers_set: &'static str,
7748    /// Method for disabling a provider.
7749    #[cfg(feature = "unstable_llm_providers")]
7750    pub providers_disable: &'static str,
7751    /// Method for creating a new session.
7752    pub session_new: &'static str,
7753    /// Method for setting a configuration option for a session.
7754    pub session_set_config_option: &'static str,
7755    /// Method for sending a prompt to the agent.
7756    pub session_prompt: &'static str,
7757    /// Notification for cancelling operations.
7758    pub session_cancel: &'static str,
7759    /// Method for exchanging MCP-over-ACP messages.
7760    #[cfg(feature = "unstable_mcp_over_acp")]
7761    pub mcp_message: &'static str,
7762    /// Method for listing existing sessions.
7763    pub session_list: &'static str,
7764    /// Method for deleting an existing session.
7765    pub session_delete: &'static str,
7766    /// Method for forking an existing session.
7767    #[cfg(feature = "unstable_session_fork")]
7768    pub session_fork: &'static str,
7769    /// Method for archiving a session.
7770    #[cfg(feature = "unstable_session_archive")]
7771    pub session_archive: &'static str,
7772    /// Method for unarchiving a session.
7773    #[cfg(feature = "unstable_session_archive")]
7774    pub session_unarchive: &'static str,
7775    /// Method for checking the status of a session.
7776    #[cfg(feature = "unstable_session_status")]
7777    pub session_status: &'static str,
7778    /// Method for querying the config options a session would start with.
7779    #[cfg(feature = "unstable_session_options")]
7780    pub session_options: &'static str,
7781    /// Method for setting the title of a session.
7782    #[cfg(feature = "unstable_session_set_title")]
7783    pub session_set_title: &'static str,
7784    /// Method for resuming an existing session.
7785    pub session_resume: &'static str,
7786    /// Method for closing an active session.
7787    pub session_close: &'static str,
7788    /// Method for cancelling one tool call.
7789    pub tool_call_cancel: &'static str,
7790    /// Method for cancelling one terminal's process.
7791    pub terminal_cancel: &'static str,
7792    /// Method for logging out of an authenticated session.
7793    pub auth_logout: &'static str,
7794    /// Method for querying the agent's authentication state.
7795    #[cfg(feature = "unstable_auth_status")]
7796    pub auth_status: &'static str,
7797}
7798
7799/// Constant containing all agent method names.
7800pub const AGENT_METHOD_NAMES: AgentMethodNames = AgentMethodNames {
7801    initialize: INITIALIZE_METHOD_NAME,
7802    auth_login: AUTH_LOGIN_METHOD_NAME,
7803    #[cfg(feature = "unstable_llm_providers")]
7804    providers_list: PROVIDERS_LIST_METHOD_NAME,
7805    #[cfg(feature = "unstable_llm_providers")]
7806    providers_set: PROVIDERS_SET_METHOD_NAME,
7807    #[cfg(feature = "unstable_llm_providers")]
7808    providers_disable: PROVIDERS_DISABLE_METHOD_NAME,
7809    session_new: SESSION_NEW_METHOD_NAME,
7810    session_set_config_option: SESSION_SET_CONFIG_OPTION_METHOD_NAME,
7811    session_prompt: SESSION_PROMPT_METHOD_NAME,
7812    session_cancel: SESSION_CANCEL_METHOD_NAME,
7813    #[cfg(feature = "unstable_mcp_over_acp")]
7814    mcp_message: MCP_MESSAGE_METHOD_NAME,
7815    session_list: SESSION_LIST_METHOD_NAME,
7816    session_delete: SESSION_DELETE_METHOD_NAME,
7817    #[cfg(feature = "unstable_session_fork")]
7818    session_fork: SESSION_FORK_METHOD_NAME,
7819    #[cfg(feature = "unstable_session_archive")]
7820    session_archive: SESSION_ARCHIVE_METHOD_NAME,
7821    #[cfg(feature = "unstable_session_archive")]
7822    session_unarchive: SESSION_UNARCHIVE_METHOD_NAME,
7823    #[cfg(feature = "unstable_session_status")]
7824    session_status: SESSION_STATUS_METHOD_NAME,
7825    #[cfg(feature = "unstable_session_options")]
7826    session_options: SESSION_OPTIONS_METHOD_NAME,
7827    #[cfg(feature = "unstable_session_set_title")]
7828    session_set_title: SESSION_SET_TITLE_METHOD_NAME,
7829    session_resume: SESSION_RESUME_METHOD_NAME,
7830    session_close: SESSION_CLOSE_METHOD_NAME,
7831    tool_call_cancel: TOOL_CALL_CANCEL_METHOD_NAME,
7832    terminal_cancel: TERMINAL_CANCEL_METHOD_NAME,
7833    auth_logout: AUTH_LOGOUT_METHOD_NAME,
7834    #[cfg(feature = "unstable_auth_status")]
7835    auth_status: AUTH_STATUS_METHOD_NAME,
7836};
7837
7838/// Method name for the initialize request.
7839pub(crate) const INITIALIZE_METHOD_NAME: &str = "initialize";
7840/// Method name for the `auth/login` request.
7841pub(crate) const AUTH_LOGIN_METHOD_NAME: &str = "auth/login";
7842/// Method name for listing configurable providers.
7843#[cfg(feature = "unstable_llm_providers")]
7844pub(crate) const PROVIDERS_LIST_METHOD_NAME: &str = "providers/list";
7845/// Method name for setting provider configuration.
7846#[cfg(feature = "unstable_llm_providers")]
7847pub(crate) const PROVIDERS_SET_METHOD_NAME: &str = "providers/set";
7848/// Method name for disabling a provider.
7849#[cfg(feature = "unstable_llm_providers")]
7850pub(crate) const PROVIDERS_DISABLE_METHOD_NAME: &str = "providers/disable";
7851/// Method name for creating a new session.
7852pub(crate) const SESSION_NEW_METHOD_NAME: &str = "session/new";
7853/// Method name for setting a configuration option for a session.
7854pub(crate) const SESSION_SET_CONFIG_OPTION_METHOD_NAME: &str = "session/set_config_option";
7855/// Method name for sending a prompt.
7856pub(crate) const SESSION_PROMPT_METHOD_NAME: &str = "session/prompt";
7857/// Method name for the cancel notification.
7858pub(crate) const SESSION_CANCEL_METHOD_NAME: &str = "session/cancel";
7859/// Method name for listing existing sessions.
7860pub(crate) const SESSION_LIST_METHOD_NAME: &str = "session/list";
7861/// Method name for deleting an existing session.
7862pub(crate) const SESSION_DELETE_METHOD_NAME: &str = "session/delete";
7863/// Method name for forking an existing session.
7864#[cfg(feature = "unstable_session_fork")]
7865pub(crate) const SESSION_FORK_METHOD_NAME: &str = "session/fork";
7866/// Method name for archiving a session.
7867#[cfg(feature = "unstable_session_archive")]
7868pub(crate) const SESSION_ARCHIVE_METHOD_NAME: &str = "session/archive";
7869/// Method name for unarchiving a session.
7870#[cfg(feature = "unstable_session_archive")]
7871pub(crate) const SESSION_UNARCHIVE_METHOD_NAME: &str = "session/unarchive";
7872/// Method name for checking the status of a session.
7873#[cfg(feature = "unstable_session_status")]
7874pub(crate) const SESSION_STATUS_METHOD_NAME: &str = "session/status";
7875/// Method name for querying the config options a session would start with.
7876#[cfg(feature = "unstable_session_options")]
7877pub(crate) const SESSION_OPTIONS_METHOD_NAME: &str = "session/options";
7878/// Method name for setting the title of a session.
7879#[cfg(feature = "unstable_session_set_title")]
7880pub(crate) const SESSION_SET_TITLE_METHOD_NAME: &str = "session/set_title";
7881/// Method name for resuming an existing session.
7882pub(crate) const SESSION_RESUME_METHOD_NAME: &str = "session/resume";
7883/// Method name for closing an active session.
7884pub(crate) const SESSION_CLOSE_METHOD_NAME: &str = "session/close";
7885/// Method name for cancelling one tool call.
7886pub(crate) const TOOL_CALL_CANCEL_METHOD_NAME: &str = "tool_call/cancel";
7887/// Method name for cancelling one terminal's process.
7888pub(crate) const TERMINAL_CANCEL_METHOD_NAME: &str = "terminal/cancel";
7889/// Method name for the `auth/logout` request.
7890pub(crate) const AUTH_LOGOUT_METHOD_NAME: &str = "auth/logout";
7891/// Method name for the `auth/status` request.
7892#[cfg(feature = "unstable_auth_status")]
7893pub(crate) const AUTH_STATUS_METHOD_NAME: &str = "auth/status";
7894
7895/// All possible requests that a client can send to an agent.
7896///
7897/// This enum is used internally for routing RPC requests. You typically won't need
7898/// to use this directly.
7899///
7900/// This enum encompasses all method calls from client to agent.
7901#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7902#[derive(Clone, Debug, Serialize, Deserialize)]
7903#[serde(untagged)]
7904#[cfg_attr(feature = "schemars", schemars(inline))]
7905#[non_exhaustive]
7906pub enum ClientRequest {
7907    /// Establishes the connection with a client and negotiates protocol capabilities.
7908    ///
7909    /// This method is called at the beginning of the connection, before any other request, to:
7910    /// - Negotiate the protocol version to use
7911    /// - Exchange capability information between client and agent
7912    /// - Determine available authentication methods
7913    ///
7914    /// The Client may repeat it before its first other request. The latest successful
7915    /// `initialize` is authoritative.
7916    ///
7917    /// The agent should respond with its supported protocol version and capabilities.
7918    ///
7919    /// See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/v2/initialization)
7920    InitializeRequest(Box<InitializeRequest>),
7921    /// Authenticates the client using the specified authentication method.
7922    ///
7923    /// Agents MUST support this method when their `initialize` response included
7924    /// a non-empty `authMethods` list. Clients MUST call this method only
7925    /// with a method whose type defines a protocol-driven login flow, and MUST NOT
7926    /// call it when `authMethods` was omitted or empty.
7927    ///
7928    /// Called when the agent requires authentication before allowing session creation.
7929    /// The client provides the authentication method ID that was advertised during initialization.
7930    ///
7931    /// After successful authentication, the client can proceed to create sessions with
7932    /// `session/new` without receiving an `auth_required` (`-32000`) error.
7933    ///
7934    /// See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/v2/initialization)
7935    LoginAuthRequest(Box<LoginAuthRequest>),
7936    /// **UNSTABLE**
7937    ///
7938    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7939    ///
7940    /// Lists providers that can be configured by the client.
7941    #[cfg(feature = "unstable_llm_providers")]
7942    ListProvidersRequest(Box<ListProvidersRequest>),
7943    /// **UNSTABLE**
7944    ///
7945    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7946    ///
7947    /// Replaces the configuration for a provider.
7948    #[cfg(feature = "unstable_llm_providers")]
7949    SetProviderRequest(Box<SetProviderRequest>),
7950    /// **UNSTABLE**
7951    ///
7952    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7953    ///
7954    /// Disables a provider.
7955    #[cfg(feature = "unstable_llm_providers")]
7956    DisableProviderRequest(Box<DisableProviderRequest>),
7957    /// Logs out of the current authenticated state.
7958    ///
7959    /// Agents MUST support this method when their `initialize` response included
7960    /// a non-empty `authMethods` list. Clients MUST NOT call this method
7961    /// when `authMethods` was omitted or empty.
7962    ///
7963    /// After a successful logout, authentication-gated requests require the
7964    /// client to complete an advertised authentication flow again. There is no
7965    /// guarantee about the behavior of already running sessions.
7966    LogoutAuthRequest(Box<LogoutAuthRequest>),
7967    /// **UNSTABLE**
7968    ///
7969    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7970    ///
7971    /// Queries the agent's current authentication state.
7972    ///
7973    /// This method is only available if the agent advertises the `auth.status` capability.
7974    /// It MUST NOT change any agent state, and agents MUST NOT reject it with `auth_required`.
7975    #[cfg(feature = "unstable_auth_status")]
7976    AuthStatusRequest(Box<AuthStatusRequest>),
7977    /// Creates a new conversation session with the agent.
7978    ///
7979    /// Sessions represent independent conversation contexts with their own history and state.
7980    ///
7981    /// The agent should:
7982    /// - Create a new session context
7983    /// - Connect to any specified MCP servers
7984    /// - Return a unique session ID for future requests
7985    ///
7986    /// May return an `auth_required` (`-32000`) error if the agent requires authentication.
7987    ///
7988    /// See protocol docs: [Session Setup](https://agentclientprotocol.com/protocol/v2/session-setup)
7989    NewSessionRequest(Box<NewSessionRequest>),
7990    /// Lists existing sessions known to the agent.
7991    ///
7992    /// The agent should return metadata about sessions with optional filtering and pagination support.
7993    ListSessionsRequest(Box<ListSessionsRequest>),
7994    /// Deletes an existing session from `session/list`.
7995    ///
7996    /// This method is only available if the agent advertises the `session.delete` capability.
7997    DeleteSessionRequest(Box<DeleteSessionRequest>),
7998    #[cfg(feature = "unstable_session_fork")]
7999    /// **UNSTABLE**
8000    ///
8001    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8002    ///
8003    /// Forks an existing session to create a new independent session.
8004    ///
8005    /// This method is only available if the agent advertises the `session.fork` capability.
8006    ///
8007    /// The agent should create a new session with the same conversation context as the
8008    /// original, allowing operations like generating summaries without affecting the
8009    /// original session's history.
8010    ///
8011    /// As with `session/new`, the forked session is active once the agent responds,
8012    /// set up with the request's `cwd`, `additionalDirectories`, and `mcpServers`.
8013    /// The client can prompt it without calling `session/resume` first.
8014    ForkSessionRequest(Box<ForkSessionRequest>),
8015    #[cfg(feature = "unstable_session_archive")]
8016    /// **UNSTABLE**
8017    ///
8018    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8019    ///
8020    /// Archives a session, hiding it from default `session/list` results.
8021    ///
8022    /// This method is only available if the agent advertises the `session.archive` capability.
8023    ArchiveSessionRequest(Box<ArchiveSessionRequest>),
8024    #[cfg(feature = "unstable_session_archive")]
8025    /// **UNSTABLE**
8026    ///
8027    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8028    ///
8029    /// Unarchives a session, returning it to default `session/list` results.
8030    ///
8031    /// This method is only available if the agent advertises the `session.archive` capability.
8032    UnarchiveSessionRequest(Box<UnarchiveSessionRequest>),
8033    #[cfg(feature = "unstable_session_status")]
8034    /// **UNSTABLE**
8035    ///
8036    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8037    ///
8038    /// Checks whether the Agent has a session in memory, without changing it.
8039    ///
8040    /// This method is only available if the agent advertises the `session.status` capability.
8041    SessionStatusRequest(Box<SessionStatusRequest>),
8042    #[cfg(feature = "unstable_session_options")]
8043    /// **UNSTABLE**
8044    ///
8045    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8046    ///
8047    /// Returns the config options a session would start with, without creating or resuming a session.
8048    ///
8049    /// This method is only available if the agent advertises the `session.options` capability.
8050    SessionOptionsRequest(Box<SessionOptionsRequest>),
8051    #[cfg(feature = "unstable_session_set_title")]
8052    /// **UNSTABLE**
8053    ///
8054    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8055    ///
8056    /// Sets the title of a session.
8057    ///
8058    /// This method is only available if the agent advertises the `session.title` capability.
8059    ///
8060    /// The session does not need to be active on the connection. The agent stores the
8061    /// title and returns the stored title, which may be normalized.
8062    SetSessionTitleRequest(Box<SetSessionTitleRequest>),
8063    /// Resumes an existing session.
8064    ///
8065    /// The agent should resume the session context, allowing the conversation
8066    /// to continue. If `replayFrom` is set, the agent should replay
8067    /// retained conversation history before responding.
8068    ResumeSessionRequest(Box<ResumeSessionRequest>),
8069    /// Closes an active session and frees up any resources associated with it.
8070    ///
8071    /// The Agent MUST cancel any ongoing work as if `session/cancel` was called, stop the
8072    /// session's background work, and then free the resources associated with the session.
8073    CloseSessionRequest(Box<CloseSessionRequest>),
8074    /// Cancels one tool call without cancelling the rest of the session's work.
8075    ///
8076    /// This method is only available while the tool call advertises `capabilities.cancel`.
8077    /// The response means the Agent accepted the cancellation. A final `tool_call_update`
8078    /// confirms it.
8079    CancelToolCallRequest(Box<CancelToolCallRequest>),
8080    /// Stops one terminal's process without cancelling the rest of the session's work.
8081    ///
8082    /// This method is only available while the terminal advertises `capabilities.cancel`.
8083    /// The response means the Agent accepted the cancellation. A `terminal_update` with
8084    /// `exitStatus` confirms it.
8085    CancelTerminalRequest(Box<CancelTerminalRequest>),
8086    /// Sets the current value for a session configuration option.
8087    SetSessionConfigOptionRequest(Box<SetSessionConfigOptionRequest>),
8088    /// Processes a user prompt within a session.
8089    ///
8090    /// Acceptance means adding a logical user message with an ID and a position
8091    /// relative to other messages in the ACP conversation, not receipt or queueing.
8092    /// The Agent MUST return the inserted message's ID without waiting for
8093    /// processing to finish.
8094    ///
8095    /// The Agent reports the user message with the same ID through `session/update`.
8096    /// This notification may arrive before or after the response, but neither may
8097    /// precede insertion. Processing state, output, tool calls, and completion are
8098    /// also reported through session updates.
8099    ///
8100    /// An error response means the user message was not inserted. Once it is
8101    /// inserted, the Agent MUST NOT answer with an error, even if the work fails
8102    /// before the response is sent. It ends that work with the `error` stop reason.
8103    ///
8104    /// A rejected submission produces no user-message updates. Foreground state
8105    /// follows its normal lifecycle independently of the request outcome:
8106    /// `running` may precede insertion, and rejection alone does not imply `idle`.
8107    ///
8108    /// See protocol docs: [Prompt Lifecycle](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle)
8109    PromptRequest(Box<PromptRequest>),
8110    /// Handles extension method requests from the client.
8111    ///
8112    /// Extension methods provide a way to add custom functionality while maintaining
8113    /// protocol compatibility.
8114    ///
8115    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
8116    ExtMethodRequest(Box<ExtRequest>),
8117}
8118
8119impl_request_dispatch! {
8120    ClientRequest => AgentResponse {
8121        InitializeRequest => InitializeResponse: AGENT_METHOD_NAMES.initialize,
8122        LoginAuthRequest => LoginAuthResponse: AGENT_METHOD_NAMES.auth_login,
8123        #[cfg(feature = "unstable_llm_providers")]
8124        ListProvidersRequest => ListProvidersResponse: AGENT_METHOD_NAMES.providers_list,
8125        #[cfg(feature = "unstable_llm_providers")]
8126        SetProviderRequest => SetProviderResponse: AGENT_METHOD_NAMES.providers_set,
8127        #[cfg(feature = "unstable_llm_providers")]
8128        DisableProviderRequest => DisableProviderResponse: AGENT_METHOD_NAMES.providers_disable,
8129        LogoutAuthRequest => LogoutAuthResponse: AGENT_METHOD_NAMES.auth_logout,
8130        #[cfg(feature = "unstable_auth_status")]
8131        AuthStatusRequest => AuthStatusResponse: AGENT_METHOD_NAMES.auth_status,
8132        NewSessionRequest => NewSessionResponse: AGENT_METHOD_NAMES.session_new,
8133        ListSessionsRequest => ListSessionsResponse: AGENT_METHOD_NAMES.session_list,
8134        DeleteSessionRequest => DeleteSessionResponse: AGENT_METHOD_NAMES.session_delete,
8135        #[cfg(feature = "unstable_session_fork")]
8136        ForkSessionRequest => ForkSessionResponse: AGENT_METHOD_NAMES.session_fork,
8137        #[cfg(feature = "unstable_session_archive")]
8138        ArchiveSessionRequest => ArchiveSessionResponse: AGENT_METHOD_NAMES.session_archive,
8139        #[cfg(feature = "unstable_session_archive")]
8140        UnarchiveSessionRequest => UnarchiveSessionResponse: AGENT_METHOD_NAMES.session_unarchive,
8141        #[cfg(feature = "unstable_session_status")]
8142        SessionStatusRequest => SessionStatusResponse: AGENT_METHOD_NAMES.session_status,
8143        #[cfg(feature = "unstable_session_options")]
8144        SessionOptionsRequest => SessionOptionsResponse: AGENT_METHOD_NAMES.session_options,
8145        #[cfg(feature = "unstable_session_set_title")]
8146        SetSessionTitleRequest => SetSessionTitleResponse: AGENT_METHOD_NAMES.session_set_title,
8147        ResumeSessionRequest => ResumeSessionResponse: AGENT_METHOD_NAMES.session_resume,
8148        CloseSessionRequest => CloseSessionResponse: AGENT_METHOD_NAMES.session_close,
8149        CancelToolCallRequest => CancelToolCallResponse: AGENT_METHOD_NAMES.tool_call_cancel,
8150        CancelTerminalRequest => CancelTerminalResponse: AGENT_METHOD_NAMES.terminal_cancel,
8151        SetSessionConfigOptionRequest => SetSessionConfigOptionResponse: AGENT_METHOD_NAMES.session_set_config_option,
8152        PromptRequest => PromptResponse: AGENT_METHOD_NAMES.session_prompt,
8153    }
8154    extension ExtMethodRequest(Box<ExtRequest>) => ExtMethodResponse;
8155}
8156
8157/// All possible responses that an agent can send to a client.
8158///
8159/// This enum is used internally for routing RPC responses. You typically won't need
8160/// to use this directly - the responses are handled automatically by the connection.
8161///
8162/// These are responses to the corresponding `ClientRequest` variants.
8163#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
8164#[derive(Clone, Debug, Serialize, Deserialize)]
8165#[serde(untagged)]
8166#[cfg_attr(feature = "schemars", schemars(inline))]
8167#[non_exhaustive]
8168pub enum AgentResponse {
8169    /// Successful result returned for a `initialize` request.
8170    InitializeResponse(Box<InitializeResponse>),
8171    /// Successful result returned for an `auth/login` request.
8172    LoginAuthResponse(#[serde(default)] Box<LoginAuthResponse>),
8173    /// Successful result returned for a `providers/list` request.
8174    #[cfg(feature = "unstable_llm_providers")]
8175    ListProvidersResponse(Box<ListProvidersResponse>),
8176    /// Successful result returned for a `providers/set` request.
8177    #[cfg(feature = "unstable_llm_providers")]
8178    SetProviderResponse(#[serde(default)] Box<SetProviderResponse>),
8179    /// Successful result returned for a `providers/disable` request.
8180    #[cfg(feature = "unstable_llm_providers")]
8181    DisableProviderResponse(#[serde(default)] Box<DisableProviderResponse>),
8182    /// Successful result returned for an `auth/logout` request.
8183    LogoutAuthResponse(#[serde(default)] Box<LogoutAuthResponse>),
8184    /// Successful result returned for an `auth/status` request.
8185    #[cfg(feature = "unstable_auth_status")]
8186    AuthStatusResponse(Box<AuthStatusResponse>),
8187    /// Successful result returned for a `session/new` request.
8188    NewSessionResponse(Box<NewSessionResponse>),
8189    /// Successful result returned for a `session/list` request.
8190    ListSessionsResponse(Box<ListSessionsResponse>),
8191    /// Successful result returned for a `session/delete` request.
8192    DeleteSessionResponse(#[serde(default)] Box<DeleteSessionResponse>),
8193    /// Successful result returned for a `session/fork` request.
8194    #[cfg(feature = "unstable_session_fork")]
8195    ForkSessionResponse(Box<ForkSessionResponse>),
8196    /// Successful result returned for a `session/archive` request.
8197    #[cfg(feature = "unstable_session_archive")]
8198    ArchiveSessionResponse(#[serde(default)] Box<ArchiveSessionResponse>),
8199    /// Successful result returned for a `session/unarchive` request.
8200    #[cfg(feature = "unstable_session_archive")]
8201    UnarchiveSessionResponse(#[serde(default)] Box<UnarchiveSessionResponse>),
8202    /// Successful result returned for a `session/status` request.
8203    #[cfg(feature = "unstable_session_status")]
8204    SessionStatusResponse(Box<SessionStatusResponse>),
8205    /// Successful result returned for a `session/options` request.
8206    #[cfg(feature = "unstable_session_options")]
8207    SessionOptionsResponse(#[serde(default)] Box<SessionOptionsResponse>),
8208    /// Successful result returned for a `session/set_title` request.
8209    #[cfg(feature = "unstable_session_set_title")]
8210    SetSessionTitleResponse(Box<SetSessionTitleResponse>),
8211    /// Successful result returned for a `session/resume` request.
8212    ResumeSessionResponse(#[serde(default)] Box<ResumeSessionResponse>),
8213    /// Successful result returned for a `session/close` request.
8214    CloseSessionResponse(#[serde(default)] Box<CloseSessionResponse>),
8215    /// Successful result returned for a `tool_call/cancel` request.
8216    CancelToolCallResponse(#[serde(default)] Box<CancelToolCallResponse>),
8217    /// Successful result returned for a `terminal/cancel` request.
8218    CancelTerminalResponse(#[serde(default)] Box<CancelTerminalResponse>),
8219    /// Successful result returned for a `session/set_config_option` request.
8220    SetSessionConfigOptionResponse(Box<SetSessionConfigOptionResponse>),
8221    /// Successful result returned for a `session/prompt` request.
8222    PromptResponse(Box<PromptResponse>),
8223    /// Successful result returned by an extension method outside the core ACP method set.
8224    ExtMethodResponse(Box<ExtResponse>),
8225}
8226
8227/// All possible notifications that a client can send to an agent.
8228///
8229/// This enum is used internally for routing RPC notifications. You typically won't need
8230/// to use this directly.
8231///
8232/// Notifications do not expect a response.
8233#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
8234#[derive(Clone, Debug, Serialize, Deserialize)]
8235#[serde(untagged)]
8236#[cfg_attr(feature = "schemars", schemars(inline))]
8237#[non_exhaustive]
8238pub enum ClientNotification {
8239    /// Cancels a session's foreground work and its prompts not yet inserted.
8240    ///
8241    /// Work in the latest `background` list is not covered and keeps running. The
8242    /// Agent MAY stop background activity it does not list.
8243    ///
8244    /// Upon receiving this notification, the Agent SHOULD stop all language model
8245    /// requests and all tool call invocations of the cancelled foreground work as soon
8246    /// as possible.
8247    ///
8248    /// The Agent MUST stop waiting for pending `session/request_permission` requests of
8249    /// the cancelled work and treat them as not approved. It MUST cancel each of them
8250    /// with `$/cancel_request`.
8251    ///
8252    /// After all ongoing operations have been successfully aborted and pending
8253    /// updates have been sent, the Agent MUST send an idle `state_update` session
8254    /// update with the `cancelled` stop reason if cancellation ended active
8255    /// foreground work. No additional completion update is required if no
8256    /// foreground work was active.
8257    ///
8258    /// After cancellation completes, the Agent SHOULD ignore late answers rather
8259    /// than use them to resume the cancelled work.
8260    ///
8261    /// Agents MUST catch errors caused by aborting cancelled work and report the
8262    /// `cancelled` stop reason, not `error`.
8263    ///
8264    /// The Agent MAY send content or tool call updates after receiving
8265    /// `session/cancel`, but MUST send them before the idle `state_update` that
8266    /// reports cancellation.
8267    ///
8268    /// See protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#cancellation)
8269    CancelSessionNotification(Box<CancelSessionNotification>),
8270    /// **UNSTABLE**
8271    ///
8272    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8273    ///
8274    /// Sends an MCP-over-ACP notification.
8275    #[cfg(feature = "unstable_mcp_over_acp")]
8276    MessageMcpNotification(Box<MessageMcpNotification>),
8277    /// Handles extension notifications from the client.
8278    ///
8279    /// Extension notifications provide a way to send one-way messages for custom functionality
8280    /// while maintaining protocol compatibility.
8281    ///
8282    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
8283    ExtNotification(Box<ExtNotification>),
8284}
8285
8286impl_message_dispatch! {
8287    ClientNotification {
8288        CancelSessionNotification => AGENT_METHOD_NAMES.session_cancel,
8289        #[cfg(feature = "unstable_mcp_over_acp")]
8290        MessageMcpNotification => AGENT_METHOD_NAMES.mcp_message,
8291    }
8292    extension ExtNotification(Box<ExtNotification>);
8293}
8294
8295#[cfg(test)]
8296mod test_serialization {
8297    use std::path::PathBuf;
8298
8299    use super::*;
8300    use serde_json::json;
8301
8302    fn test_meta() -> Meta {
8303        json!({ "source": "test" }).as_object().unwrap().clone()
8304    }
8305
8306    #[test]
8307    fn list_sessions_cursor_and_session_directories_are_strict() {
8308        for cursor in [json!(null), json!("next")] {
8309            let response = json!({ "sessions": [], "nextCursor": cursor });
8310            serde_json::from_value::<ListSessionsResponse>(response).unwrap();
8311        }
8312        let malformed = json!({ "sessions": [], "nextCursor": 42 });
8313        assert!(serde_json::from_value::<ListSessionsResponse>(malformed).is_err());
8314
8315        let session = |dirs: serde_json::Value| json!({ "sessionId": "s", "cwd": "/w", "additionalDirectories": dirs });
8316        let info: SessionInfo = serde_json::from_value(session(json!(null))).unwrap();
8317        assert_eq!(info.additional_directories, Vec::<AbsolutePath>::new());
8318        for bad in [json!(["/a", 42]), json!("/a")] {
8319            assert!(serde_json::from_value::<SessionInfo>(session(bad)).is_err());
8320        }
8321        // A session with malformed directories is skipped, not truncated.
8322        let response = json!({ "sessions": [session(json!(["/a", 42]))] });
8323        let response: ListSessionsResponse = serde_json::from_value(response).unwrap();
8324        assert_eq!(response.sessions, Vec::<SessionInfo>::new());
8325    }
8326
8327    #[test]
8328    fn other_fallbacks_preserve_optional_fields_verbatim() {
8329        let valid = json!({ "type": "_custom", "methodId": "m", "name": "M",
8330            "description": "d", "_meta": { "k": 1 } });
8331        let method: AuthMethod = serde_json::from_value(valid.clone()).unwrap();
8332        assert_eq!(method.description(), Some("d"));
8333        assert_eq!(
8334            method.meta(),
8335            Some(&json!({ "k": 1 }).as_object().unwrap().clone())
8336        );
8337        assert_eq!(serde_json::to_value(&method).unwrap(), valid);
8338
8339        // Malformed optional fields are kept as sent and read as absent.
8340        let malformed = json!({ "type": "_custom", "methodId": "m", "name": "M",
8341            "description": 42, "_meta": "bad", "extra": true });
8342        let method: AuthMethod = serde_json::from_value(malformed.clone()).unwrap();
8343        assert_eq!(method.description(), None);
8344        assert_eq!(method.meta(), None);
8345        assert_eq!(serde_json::to_value(&method).unwrap(), malformed);
8346
8347        let replay = json!({ "type": "_custom", "_meta": "bad", "cursor": 3 });
8348        let decoded: ReplayFrom = serde_json::from_value(replay.clone()).unwrap();
8349        assert_eq!(serde_json::to_value(&decoded).unwrap(), replay);
8350    }
8351
8352    fn serialized_meta_key_count(value: &impl serde::Serialize) -> usize {
8353        serde_json::to_string(value)
8354            .unwrap()
8355            .matches("\"_meta\"")
8356            .count()
8357    }
8358
8359    #[test]
8360    fn prompt_response_without_metadata_round_trips() {
8361        let response = PromptResponse::new(MessageId::new("message-1"));
8362        let serialized = serde_json::to_value(&response).unwrap();
8363        assert_eq!(serialized, json!({ "messageId": "message-1" }));
8364        assert_eq!(
8365            serde_json::from_value::<PromptResponse>(serialized).unwrap(),
8366            response
8367        );
8368        assert_eq!(
8369            serde_json::from_value::<PromptResponse>(json!({
8370                "messageId": "message-1",
8371                "_meta": null
8372            }))
8373            .unwrap(),
8374            response
8375        );
8376    }
8377
8378    #[test]
8379    fn prompt_response_requires_message_id_and_preserves_metadata_tolerance() {
8380        let response = PromptResponse::new("message-1").meta(test_meta());
8381        let serialized = serde_json::to_value(&response).unwrap();
8382        assert_eq!(
8383            serialized,
8384            json!({
8385                "messageId": "message-1",
8386                "_meta": { "source": "test" }
8387            })
8388        );
8389
8390        let deserialized: PromptResponse = serde_json::from_value(serialized).unwrap();
8391        assert_eq!(deserialized.message_id, MessageId::new("message-1"));
8392        assert_eq!(deserialized.meta, Some(test_meta()));
8393
8394        let malformed_meta: PromptResponse = serde_json::from_value(json!({
8395            "messageId": "message-2",
8396            "_meta": false
8397        }))
8398        .unwrap();
8399        assert_eq!(malformed_meta.message_id, MessageId::new("message-2"));
8400        assert_eq!(malformed_meta.meta, None);
8401
8402        for invalid in [
8403            json!({}),
8404            json!({ "messageId": null }),
8405            json!({ "messageId": 1 }),
8406            json!({ "messageId": false }),
8407            json!({ "messageId": {} }),
8408            json!({ "messageId": [] }),
8409        ] {
8410            assert!(
8411                serde_json::from_value::<PromptResponse>(invalid).is_err(),
8412                "missing, null, and non-string message IDs must be rejected"
8413            );
8414        }
8415    }
8416
8417    #[cfg(feature = "schemars")]
8418    #[test]
8419    fn prompt_response_schema_requires_non_null_string_message_id_reference() {
8420        let schema = serde_json::to_value(schemars::schema_for!(PromptResponse)).unwrap();
8421
8422        assert_eq!(schema["required"], json!(["messageId"]));
8423        assert_eq!(
8424            schema["properties"]["messageId"]["$ref"],
8425            "#/$defs/MessageId"
8426        );
8427        assert_eq!(schema["$defs"]["MessageId"]["type"], "string");
8428    }
8429
8430    #[test]
8431    fn test_initialize_capabilities_default_on_malformed_values() {
8432        let request: InitializeRequest = serde_json::from_value(json!({
8433            "protocolVersion": 2,
8434            "capabilities": false,
8435            "info": {
8436                "name": "client",
8437                "version": "1.0.0"
8438            }
8439        }))
8440        .unwrap();
8441        assert_eq!(request.capabilities, ClientCapabilities::default());
8442
8443        let response: InitializeResponse = serde_json::from_value(json!({
8444            "protocolVersion": 2,
8445            "capabilities": false,
8446            "info": {
8447                "name": "agent",
8448                "version": "1.0.0"
8449            }
8450        }))
8451        .unwrap();
8452        assert_eq!(response.capabilities, AgentCapabilities::default());
8453    }
8454
8455    #[test]
8456    fn test_agent_capabilities_default_on_malformed_values() {
8457        let capabilities: AgentCapabilities = serde_json::from_value(json!({
8458            "session": false,
8459            "auth": false
8460        }))
8461        .unwrap();
8462
8463        assert!(capabilities.session.is_none());
8464        assert_eq!(capabilities.auth, None);
8465    }
8466
8467    #[test]
8468    fn test_mcp_server_stdio_serialization() {
8469        let server = McpServer::Stdio(
8470            McpServerStdio::new("test-server", "/usr/bin/server")
8471                .args(vec!["--port".to_string(), "3000".to_string()])
8472                .env(vec![EnvVariable::new("API_KEY", "secret123")]),
8473        );
8474
8475        let json = serde_json::to_value(&server).unwrap();
8476        assert_eq!(
8477            json,
8478            json!({
8479                "type": "stdio",
8480                "name": "test-server",
8481                "command": "/usr/bin/server",
8482                "args": ["--port", "3000"],
8483                "env": [
8484                    {
8485                        "name": "API_KEY",
8486                        "value": "secret123"
8487                    }
8488                ]
8489            })
8490        );
8491
8492        let deserialized: McpServer = serde_json::from_value(json).unwrap();
8493        match deserialized {
8494            McpServer::Stdio(McpServerStdio {
8495                name,
8496                command,
8497                args,
8498                env,
8499                meta: _,
8500            }) => {
8501                assert_eq!(name, "test-server");
8502                assert_eq!(command, AbsolutePath::new("/usr/bin/server"));
8503                assert_eq!(args, vec!["--port", "3000"]);
8504                assert_eq!(env.len(), 1);
8505                assert_eq!(env[0].name, "API_KEY");
8506                assert_eq!(env[0].value, "secret123");
8507            }
8508            _ => panic!("Expected Stdio variant"),
8509        }
8510    }
8511
8512    #[test]
8513    fn test_mcp_server_empty_arrays_are_optional() {
8514        let stdio = McpServer::Stdio(McpServerStdio::new("test-server", "/usr/bin/server"));
8515        assert_eq!(
8516            serde_json::to_value(&stdio).unwrap(),
8517            json!({
8518                "type": "stdio",
8519                "name": "test-server",
8520                "command": "/usr/bin/server"
8521            })
8522        );
8523
8524        let McpServer::Stdio(McpServerStdio { args, env, .. }) =
8525            serde_json::from_value::<McpServer>(json!({
8526                "type": "stdio",
8527                "name": "test-server",
8528                "command": "/usr/bin/server"
8529            }))
8530            .unwrap()
8531        else {
8532            panic!("Expected Stdio variant");
8533        };
8534        assert_eq!(args, Vec::<String>::new());
8535        assert_eq!(env, []);
8536
8537        let http = McpServer::Http(McpServerHttp::new("http-server", "https://api.example.com"));
8538        assert_eq!(
8539            serde_json::to_value(&http).unwrap(),
8540            json!({
8541                "type": "http",
8542                "name": "http-server",
8543                "url": "https://api.example.com"
8544            })
8545        );
8546
8547        let McpServer::Http(McpServerHttp { headers, .. }) =
8548            serde_json::from_value::<McpServer>(json!({
8549                "type": "http",
8550                "name": "http-server",
8551                "url": "https://api.example.com"
8552            }))
8553            .unwrap()
8554        else {
8555            panic!("Expected Http variant");
8556        };
8557        assert_eq!(headers, []);
8558    }
8559
8560    #[test]
8561    fn test_mcp_server_unknown_transport_serialization() {
8562        let json = json!({
8563            "type": "websocket",
8564            "name": "future-server",
8565            "url": "wss://example.com/mcp",
8566            "protocolVersion": "2026-01-01"
8567        });
8568
8569        let deserialized: McpServer = serde_json::from_value(json.clone()).unwrap();
8570        let McpServer::Other(OtherMcpServer { type_, fields }) = &deserialized else {
8571            panic!("Expected Other variant");
8572        };
8573
8574        assert_eq!(type_, "websocket");
8575        assert_eq!(fields["name"], "future-server");
8576        assert_eq!(fields["url"], "wss://example.com/mcp");
8577        assert_eq!(fields["protocolVersion"], "2026-01-01");
8578        assert_eq!(serde_json::to_value(&deserialized).unwrap(), json);
8579    }
8580
8581    #[test]
8582    fn test_mcp_server_stdio_requires_type() {
8583        let result = serde_json::from_value::<McpServer>(json!({
8584            "name": "test-server",
8585            "command": "/usr/bin/server",
8586            "args": [],
8587            "env": []
8588        }));
8589
8590        assert!(result.is_err());
8591    }
8592
8593    #[test]
8594    fn test_mcp_server_unknown_does_not_hide_malformed_known_transport() {
8595        let result = serde_json::from_value::<McpServer>(json!({
8596            "type": "stdio",
8597            "name": "test-server",
8598            "args": [],
8599            "env": []
8600        }));
8601
8602        assert!(result.is_err());
8603    }
8604
8605    #[test]
8606    fn test_mcp_server_http_serialization() {
8607        let server = McpServer::Http(
8608            McpServerHttp::new("http-server", "https://api.example.com").headers(vec![
8609                HttpHeader::new("Authorization", "Bearer token123"),
8610                HttpHeader::new("Content-Type", "application/json"),
8611            ]),
8612        );
8613
8614        let json = serde_json::to_value(&server).unwrap();
8615        assert_eq!(
8616            json,
8617            json!({
8618                "type": "http",
8619                "name": "http-server",
8620                "url": "https://api.example.com",
8621                "headers": [
8622                    {
8623                        "name": "Authorization",
8624                        "value": "Bearer token123"
8625                    },
8626                    {
8627                        "name": "Content-Type",
8628                        "value": "application/json"
8629                    }
8630                ]
8631            })
8632        );
8633
8634        let deserialized: McpServer = serde_json::from_value(json).unwrap();
8635        match deserialized {
8636            McpServer::Http(McpServerHttp {
8637                name,
8638                url,
8639                headers,
8640                meta: _,
8641            }) => {
8642                assert_eq!(name, "http-server");
8643                assert_eq!(url, "https://api.example.com");
8644                assert_eq!(headers.len(), 2);
8645                assert_eq!(headers[0].name, "Authorization");
8646                assert_eq!(headers[0].value, "Bearer token123");
8647                assert_eq!(headers[1].name, "Content-Type");
8648                assert_eq!(headers[1].value, "application/json");
8649            }
8650            _ => panic!("Expected Http variant"),
8651        }
8652    }
8653
8654    #[cfg(feature = "schemars")]
8655    #[test]
8656    fn mcp_server_http_schema_marks_url_as_uri() {
8657        let schema = serde_json::to_value(schemars::schema_for!(McpServerHttp)).unwrap();
8658
8659        assert_eq!(schema["properties"]["url"]["format"], "uri");
8660    }
8661
8662    #[cfg(feature = "unstable_mcp_over_acp")]
8663    #[test]
8664    fn test_client_mcp_message_method_names() {
8665        use serde_json::json;
8666
8667        assert_eq!(AGENT_METHOD_NAMES.mcp_message, "mcp/message");
8668
8669        let notification =
8670            MessageMcpNotification::new("server-1", "req-1", "notifications/progress");
8671        assert_eq!(
8672            ClientNotification::MessageMcpNotification(Box::new(notification.clone())).method(),
8673            "mcp/message"
8674        );
8675        assert_eq!(
8676            serde_json::to_value(notification).unwrap(),
8677            json!({
8678                "serverId": "server-1",
8679                "requestId": "req-1",
8680                "method": "notifications/progress"
8681            })
8682        );
8683        let notification: MessageMcpNotification = serde_json::from_value(json!({
8684            "serverId": "server-1", "requestId": "req-1", "method": "notifications/progress",
8685            "params": null, "_meta": null
8686        }))
8687        .unwrap();
8688        assert_eq!(notification.params, None);
8689        assert_eq!(notification.meta, None);
8690        for key in ["serverId", "requestId", "method"] {
8691            let mut value = json!({"serverId":"server-1", "requestId":"req-1", "method":"notifications/progress"});
8692            value.as_object_mut().unwrap().remove(key);
8693            assert!(serde_json::from_value::<MessageMcpNotification>(value).is_err());
8694        }
8695    }
8696
8697    #[test]
8698    fn test_auth_method_names() {
8699        assert_eq!(AGENT_METHOD_NAMES.auth_login, "auth/login");
8700        assert_eq!(AGENT_METHOD_NAMES.auth_logout, "auth/logout");
8701
8702        assert_eq!(
8703            ClientRequest::LoginAuthRequest(Box::new(LoginAuthRequest::new("agent-login")))
8704                .method(),
8705            "auth/login"
8706        );
8707        assert_eq!(
8708            ClientRequest::LogoutAuthRequest(Box::new(LogoutAuthRequest::new())).method(),
8709            "auth/logout"
8710        );
8711    }
8712
8713    #[test]
8714    fn test_session_config_option_category_known_variants() {
8715        // Test serialization of known variants
8716        assert_eq!(
8717            serde_json::to_value(&SessionConfigOptionCategory::Mode).unwrap(),
8718            json!("mode")
8719        );
8720        assert_eq!(
8721            serde_json::to_value(&SessionConfigOptionCategory::Model).unwrap(),
8722            json!("model")
8723        );
8724        assert_eq!(
8725            serde_json::to_value(&SessionConfigOptionCategory::ModelConfig).unwrap(),
8726            json!("model_config")
8727        );
8728        #[cfg(feature = "unstable_speed_config_category")]
8729        assert_eq!(
8730            serde_json::to_value(&SessionConfigOptionCategory::Speed).unwrap(),
8731            json!("speed")
8732        );
8733        assert_eq!(
8734            serde_json::to_value(&SessionConfigOptionCategory::ThoughtLevel).unwrap(),
8735            json!("thought_level")
8736        );
8737
8738        // Test deserialization of known variants
8739        assert_eq!(
8740            serde_json::from_str::<SessionConfigOptionCategory>("\"mode\"").unwrap(),
8741            SessionConfigOptionCategory::Mode
8742        );
8743        assert_eq!(
8744            serde_json::from_str::<SessionConfigOptionCategory>("\"model\"").unwrap(),
8745            SessionConfigOptionCategory::Model
8746        );
8747        assert_eq!(
8748            serde_json::from_str::<SessionConfigOptionCategory>("\"model_config\"").unwrap(),
8749            SessionConfigOptionCategory::ModelConfig
8750        );
8751        #[cfg(feature = "unstable_speed_config_category")]
8752        assert_eq!(
8753            serde_json::from_str::<SessionConfigOptionCategory>("\"speed\"").unwrap(),
8754            SessionConfigOptionCategory::Speed
8755        );
8756        assert_eq!(
8757            serde_json::from_str::<SessionConfigOptionCategory>("\"thought_level\"").unwrap(),
8758            SessionConfigOptionCategory::ThoughtLevel
8759        );
8760    }
8761
8762    #[test]
8763    fn test_session_config_option_category_unknown_variants() {
8764        // Test that unknown strings are captured in Other variant
8765        let unknown: SessionConfigOptionCategory =
8766            serde_json::from_str("\"some_future_category\"").unwrap();
8767        assert_eq!(
8768            unknown,
8769            SessionConfigOptionCategory::Other("some_future_category".to_string())
8770        );
8771
8772        // Test round-trip of unknown category
8773        let json = serde_json::to_value(&unknown).unwrap();
8774        assert_eq!(json, json!("some_future_category"));
8775    }
8776
8777    #[cfg(not(feature = "unstable_speed_config_category"))]
8778    #[test]
8779    fn test_session_config_option_speed_is_unknown_without_feature() {
8780        let unknown: SessionConfigOptionCategory = serde_json::from_str("\"speed\"").unwrap();
8781        assert_eq!(
8782            unknown,
8783            SessionConfigOptionCategory::Other("speed".to_string())
8784        );
8785    }
8786
8787    #[test]
8788    fn test_session_config_option_category_custom_categories() {
8789        // Category names beginning with `_` are free for custom use
8790        let custom: SessionConfigOptionCategory =
8791            serde_json::from_str("\"_my_custom_category\"").unwrap();
8792        assert_eq!(
8793            custom,
8794            SessionConfigOptionCategory::Other("_my_custom_category".to_string())
8795        );
8796
8797        // Test round-trip preserves the custom category name
8798        let json = serde_json::to_value(&custom).unwrap();
8799        assert_eq!(json, json!("_my_custom_category"));
8800
8801        // Deserialize back and verify
8802        let deserialized: SessionConfigOptionCategory = serde_json::from_value(json).unwrap();
8803        assert_eq!(
8804            deserialized,
8805            SessionConfigOptionCategory::Other("_my_custom_category".to_string()),
8806        );
8807    }
8808
8809    fn test_config_option() -> SessionConfigOption {
8810        SessionConfigOption::select(
8811            "mode",
8812            "Mode",
8813            "ask",
8814            vec![SessionConfigSelectOption::new("ask", "Ask")],
8815        )
8816    }
8817
8818    #[test]
8819    fn test_session_response_initial_state_default_empty_and_skip_serializing() {
8820        assert_eq!(
8821            serde_json::to_value(NewSessionResponse::new("sess")).unwrap(),
8822            json!({ "sessionId": "sess" })
8823        );
8824        assert_eq!(
8825            serde_json::to_value(ResumeSessionResponse::new()).unwrap(),
8826            json!({})
8827        );
8828        #[cfg(feature = "unstable_session_fork")]
8829        assert_eq!(
8830            serde_json::to_value(ForkSessionResponse::new("fork")).unwrap(),
8831            json!({ "sessionId": "fork" })
8832        );
8833
8834        let json = serde_json::to_value(
8835            NewSessionResponse::new("sess").config_options(vec![test_config_option()]),
8836        )
8837        .unwrap();
8838        assert_eq!(json["configOptions"].as_array().unwrap().len(), 1);
8839    }
8840
8841    #[test]
8842    fn test_session_response_config_options_deserialize_missing_null_and_invalid() {
8843        let missing: NewSessionResponse =
8844            serde_json::from_value(json!({ "sessionId": "sess" })).unwrap();
8845        assert_eq!(missing.config_options, []);
8846
8847        let null: NewSessionResponse = serde_json::from_value(json!({
8848            "sessionId": "sess",
8849            "configOptions": null
8850        }))
8851        .unwrap();
8852        assert_eq!(null.config_options, []);
8853
8854        let wrong_shape: NewSessionResponse = serde_json::from_value(json!({
8855            "sessionId": "sess",
8856            "configOptions": "oops"
8857        }))
8858        .unwrap();
8859        assert_eq!(wrong_shape.config_options, []);
8860
8861        let valid_option = serde_json::to_value(test_config_option()).unwrap();
8862        let mixed: NewSessionResponse = serde_json::from_value(json!({
8863            "sessionId": "sess",
8864            "configOptions": ["oops", valid_option]
8865        }))
8866        .unwrap();
8867        assert_eq!(mixed.config_options.len(), 1);
8868
8869        let resume: ResumeSessionResponse = serde_json::from_value(json!({})).unwrap();
8870        assert_eq!(resume.config_options, []);
8871        #[cfg(feature = "unstable_session_fork")]
8872        {
8873            let fork: ForkSessionResponse =
8874                serde_json::from_value(json!({ "sessionId": "fork" })).unwrap();
8875            assert_eq!(fork.config_options, []);
8876        }
8877    }
8878
8879    #[test]
8880    fn test_session_response_available_commands_roundtrip_with_config_options() {
8881        use super::super::{AvailableCommandInput, Command, TextCommandInput};
8882
8883        let commands = vec![
8884            AvailableCommand::Command(
8885                Command::new("web", "Search the web")
8886                    .input(AvailableCommandInput::Text(TextCommandInput::new("Query"))),
8887            ),
8888            AvailableCommand::Command(Command::new("test", "Run project tests")),
8889        ];
8890        let mut expected = json!({
8891            "sessionId": "sess",
8892            "configOptions": [test_config_option()],
8893            "availableCommands": [
8894                {
8895                    "type": "command",
8896                    "name": "web",
8897                    "description": "Search the web",
8898                    "input": { "type": "text", "hint": "Query" }
8899                },
8900                { "type": "command", "name": "test", "description": "Run project tests" }
8901            ]
8902        });
8903
8904        let new = NewSessionResponse::new("sess")
8905            .config_options(vec![test_config_option()])
8906            .available_commands(commands.clone());
8907        assert_eq!(serde_json::to_value(&new).unwrap(), expected);
8908        assert_eq!(
8909            serde_json::from_value::<NewSessionResponse>(expected.clone()).unwrap(),
8910            new
8911        );
8912
8913        expected.as_object_mut().unwrap().remove("sessionId");
8914        let resume = ResumeSessionResponse::new()
8915            .config_options(vec![test_config_option()])
8916            .available_commands(commands.clone());
8917        assert_eq!(serde_json::to_value(&resume).unwrap(), expected);
8918        assert_eq!(
8919            serde_json::from_value::<ResumeSessionResponse>(expected.clone()).unwrap(),
8920            resume
8921        );
8922
8923        #[cfg(feature = "unstable_session_fork")]
8924        {
8925            expected["sessionId"] = json!("fork");
8926            let fork = ForkSessionResponse::new("fork")
8927                .config_options(vec![test_config_option()])
8928                .available_commands(commands);
8929            assert_eq!(serde_json::to_value(&fork).unwrap(), expected);
8930            assert_eq!(
8931                serde_json::from_value::<ForkSessionResponse>(expected).unwrap(),
8932                fork
8933            );
8934        }
8935    }
8936
8937    #[test]
8938    fn test_session_response_available_commands_deserialize_missing_null_and_invalid() {
8939        let command =
8940            AvailableCommand::Command(super::super::Command::new("test", "Run project tests"));
8941        let config_options = vec![test_config_option()];
8942
8943        for (commands, expected) in [
8944            (None, vec![]),
8945            (Some(json!(null)), vec![]),
8946            (Some(json!([])), vec![]),
8947            (Some(json!("oops")), vec![]),
8948            (Some(json!({})), vec![]),
8949            (Some(json!([null, {}, { "name": "invalid" }])), vec![]),
8950            (
8951                Some(json!([{ "name": "test", "description": "Run project tests" }])),
8952                vec![],
8953            ),
8954            (
8955                Some(json!([null, command, { "name": "invalid" }])),
8956                vec![command.clone()],
8957            ),
8958        ] {
8959            let mut value = json!({
8960                "sessionId": "sess",
8961                "configOptions": config_options
8962            });
8963            if let Some(commands) = commands {
8964                value["availableCommands"] = commands;
8965            }
8966
8967            let new: NewSessionResponse = serde_json::from_value(value.clone()).unwrap();
8968            assert_eq!(new.available_commands, expected);
8969            assert_eq!(new.config_options, config_options);
8970
8971            #[cfg(feature = "unstable_session_fork")]
8972            {
8973                let fork: ForkSessionResponse = serde_json::from_value(value.clone()).unwrap();
8974                assert_eq!(fork.available_commands, expected);
8975                assert_eq!(fork.config_options, config_options);
8976            }
8977
8978            value.as_object_mut().unwrap().remove("sessionId");
8979            let resume: ResumeSessionResponse = serde_json::from_value(value).unwrap();
8980            assert_eq!(resume.available_commands, expected);
8981            assert_eq!(resume.config_options, config_options);
8982        }
8983
8984        let resume: ResumeSessionResponse = serde_json::from_value(json!(null)).unwrap();
8985        assert_eq!(resume.available_commands, []);
8986    }
8987
8988    #[test]
8989    fn test_resume_session_replay_from_serialization() {
8990        assert_eq!(
8991            serde_json::to_value(ResumeSessionRequest::new(
8992                "sess_abc123",
8993                "/home/user/project"
8994            ))
8995            .unwrap(),
8996            json!({
8997                "sessionId": "sess_abc123",
8998                "cwd": "/home/user/project"
8999            })
9000        );
9001        assert_eq!(
9002            serde_json::to_value(
9003                ResumeSessionRequest::new("sess_abc123", "/home/user/project")
9004                    .replay_from(ReplayFrom::from(ReplayFromStart::new()))
9005            )
9006            .unwrap(),
9007            json!({
9008                "sessionId": "sess_abc123",
9009                "cwd": "/home/user/project",
9010                "replayFrom": {
9011                    "type": "start"
9012                }
9013            })
9014        );
9015
9016        let replay: ResumeSessionRequest = serde_json::from_value(json!({
9017            "sessionId": "sess_abc123",
9018            "cwd": "/home/user/project",
9019            "replayFrom": {
9020                "type": "start"
9021            }
9022        }))
9023        .unwrap();
9024        assert!(matches!(replay.replay_from, Some(ReplayFrom::Start(_))));
9025
9026        let none: ResumeSessionRequest = serde_json::from_value(json!({
9027            "sessionId": "sess_abc123",
9028            "cwd": "/home/user/project",
9029            "replayFrom": null
9030        }))
9031        .unwrap();
9032        assert!(none.replay_from.is_none());
9033    }
9034
9035    #[test]
9036    fn test_auth_method_agent_serialization() {
9037        let method = AuthMethod::Agent(AuthMethodAgent::new("default-auth", "Default Auth"));
9038
9039        let json = serde_json::to_value(&method).unwrap();
9040        assert_eq!(
9041            json,
9042            json!({
9043                "methodId": "default-auth",
9044                "name": "Default Auth",
9045                "type": "agent"
9046            })
9047        );
9048        // description should be omitted when None
9049        assert!(!json.as_object().unwrap().contains_key("description"));
9050
9051        let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9052        match deserialized {
9053            AuthMethod::Agent(AuthMethodAgent {
9054                method_id, name, ..
9055            }) => {
9056                assert_eq!(method_id.0.as_ref(), "default-auth");
9057                assert_eq!(name, "Default Auth");
9058            }
9059            _ => panic!("Expected Agent variant"),
9060        }
9061    }
9062
9063    #[test]
9064    fn test_auth_method_agent_deserialization() {
9065        let json = json!({
9066            "methodId": "agent-auth",
9067            "name": "Agent Auth",
9068            "type": "agent"
9069        });
9070
9071        let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9072        assert!(matches!(deserialized, AuthMethod::Agent(_)));
9073    }
9074
9075    #[test]
9076    fn test_auth_method_agent_requires_type() {
9077        assert!(
9078            serde_json::from_value::<AuthMethod>(json!({
9079                "methodId": "agent-auth",
9080                "name": "Agent Auth"
9081            }))
9082            .is_err()
9083        );
9084    }
9085
9086    #[test]
9087    fn test_auth_method_agent_rejects_null_type() {
9088        assert!(
9089            serde_json::from_value::<AuthMethod>(json!({
9090                "methodId": "agent-auth",
9091                "name": "Agent Auth",
9092                "type": null
9093            }))
9094            .is_err()
9095        );
9096    }
9097
9098    #[test]
9099    fn test_auth_method_unknown_does_not_hide_malformed_agent() {
9100        assert!(
9101            serde_json::from_value::<AuthMethod>(json!({
9102                "methodId": "agent-auth",
9103                "type": "agent"
9104            }))
9105            .is_err()
9106        );
9107        assert!(
9108            serde_json::from_value::<AuthMethod>(json!({
9109                "methodId": "api-key",
9110                "type": "env_var",
9111                "vars": [{"name": "API_KEY"}]
9112            }))
9113            .is_err()
9114        );
9115    }
9116
9117    #[test]
9118    fn test_auth_method_unknown_variant_roundtrip() {
9119        let method: AuthMethod = serde_json::from_value(json!({
9120            "methodId": "oauth",
9121            "name": "OAuth",
9122            "type": "_oauth",
9123            "authorizationUrl": "https://example.com/auth"
9124        }))
9125        .unwrap();
9126
9127        assert_eq!(method.method_id().0.as_ref(), "oauth");
9128        assert_eq!(method.name(), "OAuth");
9129        let AuthMethod::Other(unknown) = method else {
9130            panic!("expected unknown auth method");
9131        };
9132        assert_eq!(unknown.type_, "_oauth");
9133        assert_eq!(
9134            unknown.fields.get("authorizationUrl"),
9135            Some(&json!("https://example.com/auth"))
9136        );
9137
9138        assert_eq!(
9139            serde_json::to_value(AuthMethod::Other(unknown)).unwrap(),
9140            json!({
9141                "methodId": "oauth",
9142                "name": "OAuth",
9143                "type": "_oauth",
9144                "authorizationUrl": "https://example.com/auth"
9145            })
9146        );
9147    }
9148
9149    #[test]
9150    fn test_auth_method_unknown_does_not_hide_malformed_known_variant() {
9151        assert!(
9152            serde_json::from_value::<AuthMethod>(json!({
9153                "methodId": "terminal-auth",
9154                "type": "terminal"
9155            }))
9156            .is_err()
9157        );
9158    }
9159
9160    #[test]
9161    fn test_tool_call_and_terminal_cancel_serialization() {
9162        assert_eq!(AGENT_METHOD_NAMES.tool_call_cancel, "tool_call/cancel");
9163        assert_eq!(AGENT_METHOD_NAMES.terminal_cancel, "terminal/cancel");
9164        assert_eq!(
9165            ClientRequest::CancelToolCallRequest(Box::new(CancelToolCallRequest::new(
9166                "sess_abc123",
9167                "call_012"
9168            )))
9169            .method(),
9170            "tool_call/cancel"
9171        );
9172        assert_eq!(
9173            ClientRequest::CancelTerminalRequest(Box::new(CancelTerminalRequest::new(
9174                "sess_abc123",
9175                "term_003"
9176            )))
9177            .method(),
9178            "terminal/cancel"
9179        );
9180        assert_eq!(
9181            serde_json::to_value(CancelToolCallRequest::new("sess_abc123", "call_012")).unwrap(),
9182            json!({"sessionId": "sess_abc123", "toolCallId": "call_012"})
9183        );
9184        assert_eq!(
9185            serde_json::to_value(CancelTerminalRequest::new("sess_abc123", "term_003")).unwrap(),
9186            json!({"sessionId": "sess_abc123", "terminalId": "term_003"})
9187        );
9188        assert!(
9189            serde_json::from_value::<CancelToolCallRequest>(json!({"sessionId": "sess_abc123"}))
9190                .is_err()
9191        );
9192        assert_eq!(
9193            serde_json::to_value(CancelTerminalResponse::new()).unwrap(),
9194            json!({})
9195        );
9196    }
9197
9198    #[test]
9199    fn test_session_delete_serialization() {
9200        assert_eq!(AGENT_METHOD_NAMES.session_delete, "session/delete");
9201        assert_eq!(
9202            ClientRequest::DeleteSessionRequest(Box::new(DeleteSessionRequest::new("sess_abc123")))
9203                .method(),
9204            "session/delete"
9205        );
9206        assert_eq!(
9207            serde_json::to_value(DeleteSessionRequest::new("sess_abc123")).unwrap(),
9208            json!({
9209                "sessionId": "sess_abc123"
9210            })
9211        );
9212        assert_eq!(
9213            serde_json::to_value(DeleteSessionResponse::new()).unwrap(),
9214            json!({})
9215        );
9216        assert_eq!(
9217            serde_json::to_value(
9218                SessionCapabilities::new().delete(SessionDeleteCapabilities::new())
9219            )
9220            .unwrap(),
9221            json!({
9222                "delete": {}
9223            })
9224        );
9225    }
9226    #[cfg(feature = "unstable_session_set_title")]
9227    #[test]
9228    fn test_session_set_title_serialization() {
9229        assert_eq!(AGENT_METHOD_NAMES.session_set_title, "session/set_title");
9230        assert_eq!(
9231            ClientRequest::SetSessionTitleRequest(Box::new(SetSessionTitleRequest::new(
9232                "sess_abc123",
9233                "Investigate OAuth timeout"
9234            )))
9235            .method(),
9236            "session/set_title"
9237        );
9238        assert_eq!(
9239            serde_json::to_value(SetSessionTitleRequest::new(
9240                "sess_abc123",
9241                "Investigate OAuth timeout"
9242            ))
9243            .unwrap(),
9244            json!({
9245                "sessionId": "sess_abc123",
9246                "title": "Investigate OAuth timeout"
9247            })
9248        );
9249        assert_eq!(
9250            serde_json::to_value(SetSessionTitleResponse::new("Investigate OAuth timeout"))
9251                .unwrap(),
9252            json!({
9253                "title": "Investigate OAuth timeout"
9254            })
9255        );
9256        assert_eq!(
9257            serde_json::to_value(SessionCapabilities::new().title(SessionTitleCapabilities::new()))
9258                .unwrap(),
9259            json!({
9260                "title": {}
9261            })
9262        );
9263    }
9264
9265    #[cfg(feature = "unstable_session_set_title")]
9266    #[test]
9267    fn test_session_set_title_requires_title() {
9268        for params in [
9269            json!({"sessionId": "sess_abc123"}),
9270            json!({"sessionId": "sess_abc123", "title": null}),
9271            json!({"sessionId": "sess_abc123", "title": 42}),
9272        ] {
9273            assert!(serde_json::from_value::<SetSessionTitleRequest>(params).is_err());
9274        }
9275        for result in [json!({}), json!({"title": null})] {
9276            assert!(serde_json::from_value::<SetSessionTitleResponse>(result).is_err());
9277        }
9278    }
9279
9280    #[cfg(feature = "unstable_session_options")]
9281    #[test]
9282    fn test_session_options_serialization() {
9283        assert_eq!(AGENT_METHOD_NAMES.session_options, "session/options");
9284        assert_eq!(
9285            ClientRequest::SessionOptionsRequest(Box::new(SessionOptionsRequest::new(
9286                "/home/user/project"
9287            )))
9288            .method(),
9289            "session/options"
9290        );
9291        assert_eq!(
9292            serde_json::to_value(
9293                SessionOptionsRequest::new("/home/user/project")
9294                    .session_id(SessionId::new("sess_abc123"))
9295            )
9296            .unwrap(),
9297            json!({"cwd": "/home/user/project", "sessionId": "sess_abc123"})
9298        );
9299        assert_eq!(
9300            serde_json::from_value::<SessionOptionsRequest>(
9301                json!({"cwd": "/home/user/project", "additionalDirectories": null, "sessionId": null})
9302            )
9303            .unwrap(),
9304            SessionOptionsRequest::new("/home/user/project")
9305        );
9306        let request = NewSessionRequest::new("/home/user/project").config_options(vec![
9307            InitialSessionConfigOption::new("model", SessionConfigOptionValue::id("model-2")),
9308            InitialSessionConfigOption::new("fast", SessionConfigOptionValue::boolean(true)),
9309        ]);
9310        let value = serde_json::to_value(&request).unwrap();
9311        assert_eq!(
9312            value["configOptions"],
9313            json!([
9314                {"configId": "model", "type": "id", "value": "model-2"},
9315                {"configId": "fast", "type": "boolean", "value": true}
9316            ])
9317        );
9318        assert_eq!(
9319            serde_json::from_value::<NewSessionRequest>(value).unwrap(),
9320            request
9321        );
9322        assert!(
9323            serde_json::from_value::<NewSessionRequest>(json!({
9324                "cwd": "/home/user/project",
9325                "mcpServers": [],
9326                "configOptions": [{"type": "boolean", "value": true}]
9327            }))
9328            .is_err()
9329        );
9330        assert_eq!(
9331            serde_json::to_value(SessionOptionsResponse::new()).unwrap(),
9332            json!({})
9333        );
9334        #[cfg(feature = "unstable_session_fork")]
9335        {
9336            let fork =
9337                ForkSessionRequest::new("sess_abc123", "/home/user/project").config_options(vec![
9338                    InitialSessionConfigOption::new(
9339                        "model",
9340                        SessionConfigOptionValue::id("model-2"),
9341                    ),
9342                ]);
9343            let value = serde_json::to_value(&fork).unwrap();
9344            assert_eq!(
9345                value["configOptions"],
9346                json!([{"configId": "model", "type": "id", "value": "model-2"}])
9347            );
9348            assert_eq!(
9349                serde_json::from_value::<ForkSessionRequest>(value).unwrap(),
9350                fork
9351            );
9352            // `null` is an empty list, and a malformed entry fails the request.
9353            assert_eq!(
9354                serde_json::from_value::<ForkSessionRequest>(json!({
9355                    "sessionId": "sess_abc123",
9356                    "cwd": "/home/user/project",
9357                    "configOptions": null
9358                }))
9359                .unwrap(),
9360                ForkSessionRequest::new("sess_abc123", "/home/user/project")
9361            );
9362            assert!(
9363                serde_json::from_value::<ForkSessionRequest>(json!({
9364                    "sessionId": "sess_abc123",
9365                    "cwd": "/home/user/project",
9366                    "configOptions": [{"type": "boolean", "value": true}]
9367                }))
9368                .is_err()
9369            );
9370        }
9371        assert_eq!(
9372            serde_json::to_value(
9373                SessionCapabilities::new().options(SessionOptionsCapabilities::new())
9374            )
9375            .unwrap(),
9376            json!({"options": {}})
9377        );
9378    }
9379
9380    #[cfg(feature = "unstable_session_status")]
9381    #[test]
9382    fn test_session_status_serialization() {
9383        assert_eq!(AGENT_METHOD_NAMES.session_status, "session/status");
9384        assert_eq!(
9385            ClientRequest::SessionStatusRequest(Box::new(SessionStatusRequest::new("sess_abc123")))
9386                .method(),
9387            "session/status"
9388        );
9389        assert_eq!(
9390            serde_json::to_value(SessionStatusRequest::new("sess_abc123")).unwrap(),
9391            json!({"sessionId": "sess_abc123"})
9392        );
9393        assert_eq!(
9394            serde_json::to_value(SessionStatusResponse::new(SessionStatus::Saved)).unwrap(),
9395            json!({"status": "saved"})
9396        );
9397        assert_eq!(
9398            serde_json::to_value(
9399                SessionCapabilities::new().status(SessionStatusCapabilities::new())
9400            )
9401            .unwrap(),
9402            json!({"status": {}})
9403        );
9404        assert_eq!(
9405            serde_json::to_value(SessionStatusResponse::new(SessionStatus::Open).state(
9406                StateUpdate::RequiresAction(crate::v2::RequiresActionStateUpdate::new())
9407            ))
9408            .unwrap(),
9409            json!({
9410                "status": "open",
9411                "state": {"state": "requires_action"}
9412            })
9413        );
9414        for state in [json!(null), json!("running"), json!({"state": 7})] {
9415            let response = serde_json::from_value::<SessionStatusResponse>(
9416                json!({"status": "open", "state": state}),
9417            )
9418            .unwrap();
9419            assert_eq!(response.state, None);
9420        }
9421    }
9422
9423    #[cfg(feature = "unstable_session_status")]
9424    #[test]
9425    fn test_session_status_is_strict_and_open() {
9426        let custom =
9427            serde_json::from_value::<SessionStatusResponse>(json!({"status": "_suspended"}))
9428                .unwrap();
9429        assert_eq!(
9430            custom.status,
9431            SessionStatus::Other("_suspended".to_string())
9432        );
9433        assert_eq!(
9434            serde_json::to_value(&custom).unwrap(),
9435            json!({"status": "_suspended"})
9436        );
9437        for result in [json!({}), json!({"status": null}), json!({"status": 1})] {
9438            assert!(serde_json::from_value::<SessionStatusResponse>(result).is_err());
9439        }
9440        for params in [json!({}), json!({"sessionId": null})] {
9441            assert!(serde_json::from_value::<SessionStatusRequest>(params).is_err());
9442        }
9443    }
9444
9445    #[cfg(feature = "unstable_session_archive")]
9446    #[test]
9447    fn test_session_archive_serialization() {
9448        assert_eq!(AGENT_METHOD_NAMES.session_archive, "session/archive");
9449        assert_eq!(AGENT_METHOD_NAMES.session_unarchive, "session/unarchive");
9450        assert_eq!(
9451            ClientRequest::ArchiveSessionRequest(Box::new(ArchiveSessionRequest::new(
9452                "sess_abc123"
9453            )))
9454            .method(),
9455            "session/archive"
9456        );
9457        assert_eq!(
9458            ClientRequest::UnarchiveSessionRequest(Box::new(UnarchiveSessionRequest::new(
9459                "sess_abc123"
9460            )))
9461            .method(),
9462            "session/unarchive"
9463        );
9464        assert_eq!(
9465            serde_json::to_value(ArchiveSessionRequest::new("sess_abc123")).unwrap(),
9466            json!({"sessionId": "sess_abc123"})
9467        );
9468        assert_eq!(
9469            serde_json::to_value(UnarchiveSessionResponse::new()).unwrap(),
9470            json!({})
9471        );
9472        assert_eq!(
9473            serde_json::to_value(
9474                SessionCapabilities::new().archive(SessionArchiveCapabilities::new())
9475            )
9476            .unwrap(),
9477            json!({"archive": {}})
9478        );
9479        assert_eq!(
9480            serde_json::to_value(
9481                ListSessionsRequest::new()
9482                    .cwd("/home/user/project")
9483                    .archived(SessionArchiveFilter::Only)
9484            )
9485            .unwrap(),
9486            json!({"cwd": "/home/user/project", "archived": "only"})
9487        );
9488        assert_eq!(
9489            serde_json::to_value(
9490                SessionInfo::new("sess_abc123", "/home/user/project").archived(true)
9491            )
9492            .unwrap(),
9493            json!({"sessionId": "sess_abc123", "cwd": "/home/user/project", "archived": true})
9494        );
9495    }
9496
9497    #[cfg(feature = "unstable_session_archive")]
9498    #[test]
9499    fn test_session_archive_filter_is_strict_and_open() {
9500        for (value, expected) in [
9501            (json!(null), None),
9502            (json!("include"), Some(SessionArchiveFilter::Include)),
9503            (
9504                json!("_recent"),
9505                Some(SessionArchiveFilter::Other("_recent".to_string())),
9506            ),
9507        ] {
9508            let request =
9509                serde_json::from_value::<ListSessionsRequest>(json!({"archived": value})).unwrap();
9510            assert_eq!(request.archived, expected);
9511        }
9512        for value in [json!(true), json!(1), json!({})] {
9513            assert!(
9514                serde_json::from_value::<ListSessionsRequest>(json!({"archived": value})).is_err()
9515            );
9516        }
9517        let info = serde_json::from_value::<SessionInfo>(
9518            json!({"sessionId": "sess_abc123", "cwd": "/home/user/project", "archived": "yes"}),
9519        )
9520        .unwrap();
9521        assert_eq!(info.archived, None);
9522    }
9523
9524    #[test]
9525    fn test_session_additional_directories_serialization() {
9526        assert_eq!(
9527            serde_json::to_value(NewSessionRequest::new("/home/user/project")).unwrap(),
9528            json!({
9529                "cwd": "/home/user/project",
9530            })
9531        );
9532        assert_eq!(
9533            serde_json::to_value(
9534                NewSessionRequest::new("/home/user/project").additional_directories(vec![
9535                    PathBuf::from("/home/user/shared-lib"),
9536                    PathBuf::from("/home/user/product-docs"),
9537                ])
9538            )
9539            .unwrap(),
9540            json!({
9541                "cwd": "/home/user/project",
9542                "additionalDirectories": [
9543                    "/home/user/shared-lib",
9544                    "/home/user/product-docs"
9545                ],
9546            })
9547        );
9548        assert_eq!(
9549            serde_json::to_value(ResumeSessionRequest::new(
9550                "sess_abc123",
9551                "/home/user/project"
9552            ))
9553            .unwrap(),
9554            json!({
9555                "sessionId": "sess_abc123",
9556                "cwd": "/home/user/project",
9557            })
9558        );
9559        assert_eq!(
9560            serde_json::from_value::<ResumeSessionRequest>(json!({
9561                "sessionId": "sess_abc123",
9562                "cwd": "/home/user/project"
9563            }))
9564            .unwrap()
9565            .mcp_servers,
9566            Vec::<McpServer>::new()
9567        );
9568        assert_eq!(
9569            serde_json::from_value::<ResumeSessionRequest>(json!({
9570                "sessionId": "sess_abc123",
9571                "cwd": "/home/user/project",
9572                "mcpServers": null
9573            }))
9574            .unwrap()
9575            .mcp_servers,
9576            Vec::<McpServer>::new()
9577        );
9578        assert_eq!(
9579            serde_json::to_value(SessionInfo::new("sess_abc123", "/home/user/project")).unwrap(),
9580            json!({
9581                "sessionId": "sess_abc123",
9582                "cwd": "/home/user/project"
9583            })
9584        );
9585        assert_eq!(
9586            serde_json::to_value(
9587                SessionInfo::new("sess_abc123", "/home/user/project").additional_directories(vec![
9588                    PathBuf::from("/home/user/shared-lib"),
9589                    PathBuf::from("/home/user/product-docs"),
9590                ])
9591            )
9592            .unwrap(),
9593            json!({
9594                "sessionId": "sess_abc123",
9595                "cwd": "/home/user/project",
9596                "additionalDirectories": [
9597                    "/home/user/shared-lib",
9598                    "/home/user/product-docs"
9599                ]
9600            })
9601        );
9602        assert_eq!(
9603            serde_json::from_value::<SessionInfo>(json!({
9604                "sessionId": "sess_abc123",
9605                "cwd": "/home/user/project"
9606            }))
9607            .unwrap()
9608            .additional_directories,
9609            Vec::<AbsolutePath>::new()
9610        );
9611    }
9612    #[test]
9613    fn test_session_additional_directories_capabilities_serialization() {
9614        assert_eq!(
9615            serde_json::to_value(
9616                SessionCapabilities::new()
9617                    .additional_directories(SessionAdditionalDirectoriesCapabilities::new())
9618            )
9619            .unwrap(),
9620            json!({
9621                "additionalDirectories": {}
9622            })
9623        );
9624    }
9625
9626    #[test]
9627    fn test_session_system_prompt_capabilities_serialization() {
9628        assert_eq!(
9629            serde_json::to_value(
9630                SessionCapabilities::new().system_prompt(SessionSystemPromptCapabilities::new())
9631            )
9632            .unwrap(),
9633            json!({ "systemPrompt": {} })
9634        );
9635        assert_eq!(
9636            serde_json::to_value(
9637                SessionCapabilities::new().system_prompt(
9638                    SessionSystemPromptCapabilities::new().mode(
9639                        SessionSystemPromptModeCapabilities::new()
9640                            .override_(SessionSystemPromptOverrideCapabilities::new())
9641                    )
9642                )
9643            )
9644            .unwrap(),
9645            json!({ "systemPrompt": { "mode": { "override": {} } } })
9646        );
9647        assert_eq!(
9648            serde_json::from_value::<SessionCapabilities>(
9649                json!({ "systemPrompt": { "mode": { "override": {} } } })
9650            )
9651            .unwrap()
9652            .system_prompt
9653            .and_then(|capabilities| capabilities.mode)
9654            .and_then(|mode| mode.override_),
9655            Some(SessionSystemPromptOverrideCapabilities::new())
9656        );
9657
9658        // Capabilities fall back to "not advertised" when malformed.
9659        assert_eq!(
9660            serde_json::from_value::<SessionCapabilities>(json!({ "systemPrompt": "yes" }))
9661                .unwrap()
9662                .system_prompt,
9663            None
9664        );
9665        assert_eq!(
9666            serde_json::from_value::<SessionCapabilities>(
9667                json!({ "systemPrompt": { "mode": { "override": true } } })
9668            )
9669            .unwrap()
9670            .system_prompt,
9671            Some(
9672                SessionSystemPromptCapabilities::new()
9673                    .mode(SessionSystemPromptModeCapabilities::new())
9674            )
9675        );
9676        assert_eq!(
9677            serde_json::from_value::<SessionCapabilities>(
9678                json!({ "systemPrompt": { "mode": "override" } })
9679            )
9680            .unwrap()
9681            .system_prompt,
9682            Some(SessionSystemPromptCapabilities::new())
9683        );
9684    }
9685
9686    #[test]
9687    fn test_system_prompt_lifecycle_request_serialization() {
9688        let system_prompt = SystemPrompt::new(vec![ContentBlock::from(
9689            "You are a code review specialist.",
9690        )]);
9691        let system_prompt_json = json!({
9692            "mode": "append",
9693            "content": [{ "type": "text", "text": "You are a code review specialist." }]
9694        });
9695
9696        let request =
9697            NewSessionRequest::new("/home/user/project").system_prompt(system_prompt.clone());
9698        let request_json = json!({
9699            "cwd": "/home/user/project",
9700            "systemPrompt": system_prompt_json
9701        });
9702        assert_eq!(serde_json::to_value(&request).unwrap(), request_json);
9703        assert_eq!(
9704            serde_json::from_value::<NewSessionRequest>(request_json).unwrap(),
9705            request
9706        );
9707
9708        assert_eq!(
9709            serde_json::to_value(
9710                ResumeSessionRequest::new("sess_abc123", "/home/user/project")
9711                    .system_prompt(system_prompt.clone())
9712            )
9713            .unwrap()["systemPrompt"],
9714            system_prompt_json
9715        );
9716        #[cfg(feature = "unstable_session_fork")]
9717        assert_eq!(
9718            serde_json::to_value(
9719                ForkSessionRequest::new("sess_abc123", "/home/user/project")
9720                    .system_prompt(system_prompt.clone())
9721            )
9722            .unwrap()["systemPrompt"],
9723            system_prompt_json
9724        );
9725
9726        let override_prompt =
9727            SystemPrompt::new(vec![ContentBlock::from("...")]).mode(SystemPromptMode::Override);
9728        let override_json = json!({
9729            "mode": "override",
9730            "content": [{ "type": "text", "text": "..." }]
9731        });
9732        assert_eq!(
9733            serde_json::to_value(&override_prompt).unwrap(),
9734            override_json
9735        );
9736        assert_eq!(
9737            serde_json::from_value::<SystemPrompt>(override_json).unwrap(),
9738            override_prompt
9739        );
9740    }
9741
9742    /// `SystemPrompt::new` defaults to `append` in Rust, but `mode` is required on
9743    /// the wire, so it is always serialized.
9744    #[test]
9745    fn test_system_prompt_new_defaults_to_append() {
9746        let system_prompt = SystemPrompt::new(vec![ContentBlock::from("...")]);
9747        assert_eq!(system_prompt.mode, SystemPromptMode::Append);
9748        assert_eq!(
9749            serde_json::to_value(&system_prompt).unwrap(),
9750            json!({ "mode": "append", "content": [{ "type": "text", "text": "..." }] })
9751        );
9752    }
9753
9754    /// Unknown modes follow the enum variant extension rule: they parse as
9755    /// `SystemPromptMode::Other` so they are not dropped, and an agent that does
9756    /// not support them must reject the request.
9757    #[test]
9758    fn test_system_prompt_preserves_unknown_modes() {
9759        for mode in ["_vendor_mode", "prepend"] {
9760            let system_prompt_json =
9761                json!({ "mode": mode, "content": [{ "type": "text", "text": "..." }] });
9762            let system_prompt: SystemPrompt =
9763                serde_json::from_value(system_prompt_json.clone()).unwrap();
9764            assert_eq!(
9765                system_prompt.mode,
9766                SystemPromptMode::Other(mode.to_string())
9767            );
9768            assert_eq!(
9769                serde_json::to_value(&system_prompt).unwrap(),
9770                system_prompt_json
9771            );
9772        }
9773    }
9774
9775    /// The receiver acts on `systemPrompt`, so malformed values fail the request
9776    /// (`-32602`) instead of creating a session without the prompt, and `null`
9777    /// is equivalent to omitting the field.
9778    fn assert_system_prompt_is_strict<T>(base: &serde_json::Value)
9779    where
9780        T: serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
9781    {
9782        let name = std::any::type_name::<T>();
9783        let with = |system_prompt: serde_json::Value| {
9784            let mut request = base.clone();
9785            request["systemPrompt"] = system_prompt;
9786            serde_json::from_value::<T>(request)
9787        };
9788
9789        for system_prompt in [
9790            json!("You are a code review specialist."),
9791            json!({ "content": [{ "type": "text", "text": "..." }] }),
9792            json!({ "mode": null, "content": [{ "type": "text", "text": "..." }] }),
9793            json!({ "mode": 1, "content": [{ "type": "text", "text": "..." }] }),
9794            json!({ "mode": "append" }),
9795            json!({ "mode": "append", "content": "..." }),
9796            json!({ "mode": "append", "content": [{ "type": "text" }] }),
9797        ] {
9798            assert!(
9799                with(system_prompt.clone()).is_err(),
9800                "{name}.systemPrompt: {system_prompt}"
9801            );
9802        }
9803
9804        assert_eq!(
9805            with(serde_json::Value::Null).unwrap(),
9806            serde_json::from_value::<T>(base.clone()).unwrap(),
9807            "{name}.systemPrompt"
9808        );
9809    }
9810
9811    #[test]
9812    fn test_session_setup_requests_reject_malformed_system_prompts() {
9813        assert!(
9814            serde_json::to_value(NewSessionRequest::new("/repo"))
9815                .unwrap()
9816                .get("systemPrompt")
9817                .is_none()
9818        );
9819        assert_system_prompt_is_strict::<NewSessionRequest>(&json!({ "cwd": "/repo" }));
9820        assert_system_prompt_is_strict::<ResumeSessionRequest>(&json!({
9821            "sessionId": "sess-1",
9822            "cwd": "/repo"
9823        }));
9824        #[cfg(feature = "unstable_session_fork")]
9825        assert_system_prompt_is_strict::<ForkSessionRequest>(&json!({
9826            "sessionId": "sess-1",
9827            "cwd": "/repo"
9828        }));
9829    }
9830
9831    /// Unknown content block types parse as `ContentBlock::Other` so they are not
9832    /// dropped. An agent that does not support them must reject the request.
9833    #[test]
9834    fn test_system_prompt_preserves_unknown_content_blocks() {
9835        let request: NewSessionRequest = serde_json::from_value(json!({
9836            "cwd": "/home/user/project",
9837            "systemPrompt": {
9838                "mode": "append",
9839                "content": [{ "type": "_vendor_video", "uri": "https://example.com/intro.mp4" }]
9840            }
9841        }))
9842        .unwrap();
9843        let content = request.system_prompt.unwrap().content;
9844        assert_eq!(content.len(), 1);
9845        assert!(matches!(content[0], ContentBlock::Other(_)));
9846    }
9847
9848    #[test]
9849    fn test_auth_method_terminal_serialization() {
9850        let method = AuthMethod::Terminal(AuthMethodTerminal::new("tui-auth", "Terminal Auth"));
9851
9852        let json = serde_json::to_value(&method).unwrap();
9853        assert_eq!(
9854            json,
9855            json!({
9856                "methodId": "tui-auth",
9857                "name": "Terminal Auth",
9858                "type": "terminal"
9859            })
9860        );
9861        // args and env should be omitted when empty
9862        assert!(!json.as_object().unwrap().contains_key("args"));
9863        assert!(!json.as_object().unwrap().contains_key("env"));
9864
9865        let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9866        match deserialized {
9867            AuthMethod::Terminal(AuthMethodTerminal { args, env, .. }) => {
9868                assert_eq!(args, Vec::<String>::new());
9869                assert_eq!(env, []);
9870            }
9871            _ => panic!("Expected Terminal variant"),
9872        }
9873    }
9874
9875    #[test]
9876    fn test_auth_method_terminal_with_args_and_env_serialization() {
9877        let method = AuthMethod::Terminal(
9878            AuthMethodTerminal::new("tui-auth", "Terminal Auth")
9879                .args(vec!["--interactive".to_string(), "--color".to_string()])
9880                .env(vec![EnvVariable::new("TERM", "xterm-256color")]),
9881        );
9882
9883        let json = serde_json::to_value(&method).unwrap();
9884        assert_eq!(
9885            json,
9886            json!({
9887                "methodId": "tui-auth",
9888                "name": "Terminal Auth",
9889                "type": "terminal",
9890                "args": ["--interactive", "--color"],
9891                "env": [
9892                    {
9893                        "name": "TERM",
9894                        "value": "xterm-256color"
9895                    }
9896                ]
9897            })
9898        );
9899
9900        let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9901        match deserialized {
9902            AuthMethod::Terminal(AuthMethodTerminal { args, env, .. }) => {
9903                assert_eq!(args, vec!["--interactive", "--color"]);
9904                assert_eq!(env.len(), 1);
9905                assert_eq!(env[0].name, "TERM");
9906                assert_eq!(env[0].value, "xterm-256color");
9907            }
9908            _ => panic!("Expected Terminal variant"),
9909        }
9910    }
9911
9912    #[test]
9913    fn test_session_config_option_id_serialize() {
9914        let val = SessionConfigOptionValue::id("model-1");
9915        let json = serde_json::to_value(&val).unwrap();
9916        assert_eq!(json, json!({ "type": "id", "value": "model-1" }));
9917    }
9918
9919    #[test]
9920    fn test_session_config_option_value_boolean_serialize() {
9921        let val = SessionConfigOptionValue::boolean(true);
9922        let json = serde_json::to_value(&val).unwrap();
9923        assert_eq!(json, json!({ "type": "boolean", "value": true }));
9924    }
9925
9926    #[test]
9927    fn test_session_config_option_value_deserialize_id() {
9928        let json = json!({ "type": "id", "value": "model-1" });
9929        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9930        assert_eq!(val, SessionConfigOptionValue::id("model-1"));
9931        assert_eq!(val.as_id().unwrap().to_string(), "model-1");
9932    }
9933
9934    #[test]
9935    fn test_session_config_option_value_deserialize_requires_type() {
9936        let json = json!({ "value": "model-1" });
9937        let result = serde_json::from_value::<SessionConfigOptionValue>(json);
9938        assert!(result.is_err());
9939    }
9940
9941    #[test]
9942    fn test_session_config_option_value_deserialize_boolean() {
9943        let json = json!({ "type": "boolean", "value": true });
9944        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9945        assert_eq!(val, SessionConfigOptionValue::boolean(true));
9946        assert_eq!(val.as_bool(), Some(true));
9947    }
9948
9949    #[test]
9950    fn test_session_config_option_value_deserialize_boolean_false() {
9951        let json = json!({ "type": "boolean", "value": false });
9952        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9953        assert_eq!(val, SessionConfigOptionValue::boolean(false));
9954        assert_eq!(val.as_bool(), Some(false));
9955    }
9956
9957    #[test]
9958    fn test_session_config_option_value_deserialize_unknown_type_with_string_value() {
9959        let json = json!({
9960            "type": "text",
9961            "value": "freeform input",
9962            "maxLength": 200
9963        });
9964        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9965        let SessionConfigOptionValue::Other(unknown) = val else {
9966            panic!("Expected Other variant");
9967        };
9968        assert_eq!(unknown.type_, "text");
9969        assert_eq!(unknown.value, json!("freeform input"));
9970        assert_eq!(unknown.fields["maxLength"], json!(200));
9971    }
9972
9973    #[test]
9974    fn test_session_config_option_value_deserialize_unknown_type_with_object_value() {
9975        let json = json!({
9976            "type": "range",
9977            "value": { "min": 1, "max": 5 }
9978        });
9979        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9980        let SessionConfigOptionValue::Other(unknown) = val else {
9981            panic!("Expected Other variant");
9982        };
9983        assert_eq!(unknown.type_, "range");
9984        assert_eq!(unknown.value, json!({ "min": 1, "max": 5 }));
9985    }
9986
9987    #[test]
9988    fn test_session_config_option_value_roundtrip_id() {
9989        let original = SessionConfigOptionValue::id("option-a");
9990        let json = serde_json::to_value(&original).unwrap();
9991        let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9992        assert_eq!(original, roundtripped);
9993    }
9994
9995    #[test]
9996    fn test_session_config_option_value_roundtrip_boolean() {
9997        let original = SessionConfigOptionValue::boolean(false);
9998        let json = serde_json::to_value(&original).unwrap();
9999        let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10000        assert_eq!(original, roundtripped);
10001    }
10002
10003    #[test]
10004    fn test_session_config_option_value_roundtrip_other() {
10005        let mut fields = BTreeMap::new();
10006        fields.insert("maxLength".to_string(), json!(200));
10007        let original = SessionConfigOptionValue::Other(OtherSessionConfigOptionValue::new(
10008            "text",
10009            json!("freeform input"),
10010            fields,
10011        ));
10012        let json = serde_json::to_value(&original).unwrap();
10013        let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10014        assert_eq!(original, roundtripped);
10015    }
10016
10017    #[test]
10018    fn test_session_config_option_value_type_mismatch_boolean_with_string() {
10019        let json = json!({ "type": "boolean", "value": "not a bool" });
10020        let result = serde_json::from_value::<SessionConfigOptionValue>(json);
10021        assert!(result.is_err());
10022    }
10023
10024    #[test]
10025    fn test_session_config_option_value_from_impls() {
10026        let from_str: SessionConfigOptionValue = "model-1".into();
10027        assert_eq!(from_str.as_id().unwrap().to_string(), "model-1");
10028
10029        let from_id: SessionConfigOptionValue = SessionConfigValueId::new("model-2").into();
10030        assert_eq!(from_id.as_id().unwrap().to_string(), "model-2");
10031
10032        let from_bool: SessionConfigOptionValue = true.into();
10033        assert_eq!(from_bool.as_bool(), Some(true));
10034    }
10035
10036    #[test]
10037    fn test_set_session_config_option_request_id() {
10038        let req = SetSessionConfigOptionRequest::new("sess_1", "model", "model-1");
10039        let json = serde_json::to_value(&req).unwrap();
10040        assert_eq!(
10041            json,
10042            json!({
10043                "sessionId": "sess_1",
10044                "configId": "model",
10045                "type": "id",
10046                "value": "model-1"
10047            })
10048        );
10049    }
10050
10051    #[test]
10052    fn test_set_session_config_option_request_boolean() {
10053        let req = SetSessionConfigOptionRequest::new("sess_1", "brave_mode", true);
10054        let json = serde_json::to_value(&req).unwrap();
10055        assert_eq!(
10056            json,
10057            json!({
10058                "sessionId": "sess_1",
10059                "configId": "brave_mode",
10060                "type": "boolean",
10061                "value": true
10062            })
10063        );
10064    }
10065
10066    #[test]
10067    fn test_set_session_config_option_request_deserialize_requires_type() {
10068        let json = json!({
10069            "sessionId": "sess_1",
10070            "configId": "model",
10071            "value": "model-1"
10072        });
10073        let result = serde_json::from_value::<SetSessionConfigOptionRequest>(json);
10074        assert!(result.is_err());
10075    }
10076
10077    #[test]
10078    fn test_set_session_config_option_request_deserialize_boolean() {
10079        let json = json!({
10080            "sessionId": "sess_1",
10081            "configId": "brave_mode",
10082            "type": "boolean",
10083            "value": true
10084        });
10085        let req: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
10086        assert_eq!(req.value.as_bool(), Some(true));
10087    }
10088
10089    #[test]
10090    fn test_set_session_config_option_request_roundtrip_id() {
10091        let original = SetSessionConfigOptionRequest::new("s", "c", "v");
10092        let json = serde_json::to_value(&original).unwrap();
10093        let roundtripped: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
10094        assert_eq!(original, roundtripped);
10095    }
10096
10097    #[test]
10098    fn test_set_session_config_option_request_roundtrip_boolean() {
10099        let original = SetSessionConfigOptionRequest::new("s", "c", false);
10100        let json = serde_json::to_value(&original).unwrap();
10101        let roundtripped: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
10102        assert_eq!(original, roundtripped);
10103    }
10104
10105    #[test]
10106    fn test_session_config_boolean_serialization() {
10107        let cfg = SessionConfigBoolean::new(true);
10108        let json = serde_json::to_value(&cfg).unwrap();
10109        assert_eq!(json, json!({ "currentValue": true }));
10110
10111        let deserialized: SessionConfigBoolean = serde_json::from_value(json).unwrap();
10112        assert!(deserialized.current_value);
10113    }
10114
10115    #[test]
10116    fn test_session_config_option_boolean_variant() {
10117        let opt = SessionConfigOption::boolean("brave_mode", "Brave Mode", false)
10118            .description("Skip confirmation prompts")
10119            .meta(test_meta());
10120        assert_eq!(serialized_meta_key_count(&opt), 1);
10121
10122        let json = serde_json::to_value(&opt).unwrap();
10123        assert_eq!(
10124            json,
10125            json!({
10126                "configId": "brave_mode",
10127                "name": "Brave Mode",
10128                "description": "Skip confirmation prompts",
10129                "type": "boolean",
10130                "currentValue": false,
10131                "_meta": {
10132                    "source": "test"
10133                }
10134            })
10135        );
10136
10137        let deserialized: SessionConfigOption = serde_json::from_value(json).unwrap();
10138        assert_eq!(deserialized.config_id.to_string(), "brave_mode");
10139        assert_eq!(deserialized.name, "Brave Mode");
10140        match deserialized.kind {
10141            SessionConfigKind::Boolean(ref b) => assert!(!b.current_value),
10142            _ => panic!("Expected Boolean kind"),
10143        }
10144    }
10145
10146    #[test]
10147    fn test_session_config_option_select_still_works() {
10148        // Make sure existing select options are unaffected
10149        let opt = SessionConfigOption::select(
10150            "model",
10151            "Model",
10152            "model-1",
10153            vec![
10154                SessionConfigSelectOption::new("model-1", "Model 1"),
10155                SessionConfigSelectOption::new("model-2", "Model 2"),
10156            ],
10157        )
10158        .meta(test_meta());
10159        assert_eq!(serialized_meta_key_count(&opt), 1);
10160
10161        let json = serde_json::to_value(&opt).unwrap();
10162        assert_eq!(json["type"], "select");
10163        assert_eq!(json["currentValue"], "model-1");
10164        assert_eq!(json["options"].as_array().unwrap().len(), 2);
10165        assert_eq!(json["_meta"]["source"], "test");
10166
10167        let deserialized: SessionConfigOption = serde_json::from_value(json).unwrap();
10168        match deserialized.kind {
10169            SessionConfigKind::Select(ref s) => {
10170                assert_eq!(s.current_value.to_string(), "model-1");
10171            }
10172            _ => panic!("Expected Select kind"),
10173        }
10174    }
10175
10176    #[test]
10177    fn test_session_config_option_unknown_kind_roundtrip() {
10178        let option: SessionConfigOption = serde_json::from_value(json!({
10179            "configId": "verbosity",
10180            "name": "Verbosity",
10181            "type": "_slider",
10182            "currentValue": 3,
10183            "min": 0,
10184            "max": 5,
10185            "_meta": {
10186                "source": "test"
10187            }
10188        }))
10189        .unwrap();
10190
10191        assert_eq!(option.config_id.to_string(), "verbosity");
10192        assert_eq!(option.meta.as_ref().unwrap()["source"], "test");
10193        let SessionConfigKind::Other(unknown) = &option.kind else {
10194            panic!("expected unknown config kind");
10195        };
10196        assert_eq!(unknown.type_, "_slider");
10197        assert_eq!(unknown.fields.get("currentValue"), Some(&json!(3)));
10198        assert!(!unknown.fields.contains_key("_meta"));
10199        assert_eq!(serialized_meta_key_count(&option), 1);
10200
10201        let json = serde_json::to_value(&option).unwrap();
10202        assert_eq!(json["type"], "_slider");
10203        assert_eq!(json["currentValue"], 3);
10204        assert_eq!(json["min"], 0);
10205        assert_eq!(json["max"], 5);
10206        assert_eq!(json["_meta"]["source"], "test");
10207    }
10208
10209    #[test]
10210    fn test_session_config_option_unknown_kind_does_not_duplicate_flattened_meta() {
10211        let mut fields = std::collections::BTreeMap::new();
10212        fields.insert("currentValue".to_string(), json!(3));
10213        fields.insert("_meta".to_string(), json!({ "inner": "ignored" }));
10214
10215        let option = SessionConfigOption::new(
10216            "verbosity",
10217            "Verbosity",
10218            SessionConfigKind::Other(OtherSessionConfigKind::new("_slider", fields)),
10219        )
10220        .meta(test_meta());
10221
10222        let SessionConfigKind::Other(unknown) = &option.kind else {
10223            panic!("expected unknown config kind");
10224        };
10225        assert!(!unknown.fields.contains_key("_meta"));
10226        assert_eq!(serialized_meta_key_count(&option), 1);
10227
10228        let json = serde_json::to_value(&option).unwrap();
10229        assert_eq!(json["type"], "_slider");
10230        assert_eq!(json["currentValue"], 3);
10231        assert_eq!(json["_meta"]["source"], "test");
10232    }
10233
10234    #[test]
10235    fn test_session_config_option_unknown_does_not_hide_malformed_known_kind() {
10236        assert!(
10237            serde_json::from_value::<SessionConfigOption>(json!({
10238                "configId": "model",
10239                "name": "Model",
10240                "type": "select"
10241            }))
10242            .is_err()
10243        );
10244    }
10245
10246    #[cfg(feature = "unstable_llm_providers")]
10247    #[test]
10248    fn test_llm_protocol_known_variants() {
10249        assert_eq!(
10250            serde_json::to_value(&LlmProtocol::Anthropic).unwrap(),
10251            json!("anthropic")
10252        );
10253        assert_eq!(
10254            serde_json::to_value(&LlmProtocol::OpenAi).unwrap(),
10255            json!("openai")
10256        );
10257        assert_eq!(
10258            serde_json::to_value(&LlmProtocol::Azure).unwrap(),
10259            json!("azure")
10260        );
10261        assert_eq!(
10262            serde_json::to_value(&LlmProtocol::Vertex).unwrap(),
10263            json!("vertex")
10264        );
10265        assert_eq!(
10266            serde_json::to_value(&LlmProtocol::Bedrock).unwrap(),
10267            json!("bedrock")
10268        );
10269
10270        assert_eq!(
10271            serde_json::from_str::<LlmProtocol>("\"anthropic\"").unwrap(),
10272            LlmProtocol::Anthropic
10273        );
10274        assert_eq!(
10275            serde_json::from_str::<LlmProtocol>("\"openai\"").unwrap(),
10276            LlmProtocol::OpenAi
10277        );
10278        assert_eq!(
10279            serde_json::from_str::<LlmProtocol>("\"azure\"").unwrap(),
10280            LlmProtocol::Azure
10281        );
10282        assert_eq!(
10283            serde_json::from_str::<LlmProtocol>("\"vertex\"").unwrap(),
10284            LlmProtocol::Vertex
10285        );
10286        assert_eq!(
10287            serde_json::from_str::<LlmProtocol>("\"bedrock\"").unwrap(),
10288            LlmProtocol::Bedrock
10289        );
10290    }
10291
10292    #[cfg(feature = "unstable_llm_providers")]
10293    #[test]
10294    fn test_llm_protocol_unknown_variant() {
10295        let unknown: LlmProtocol = serde_json::from_str("\"cohere\"").unwrap();
10296        assert_eq!(unknown, LlmProtocol::Other("cohere".to_string()));
10297
10298        let json = serde_json::to_value(&unknown).unwrap();
10299        assert_eq!(json, json!("cohere"));
10300    }
10301
10302    #[cfg(feature = "unstable_llm_providers")]
10303    #[test]
10304    fn test_provider_current_config_serialization() {
10305        let config =
10306            ProviderCurrentConfig::new(LlmProtocol::Anthropic, "https://api.anthropic.com");
10307
10308        let json = serde_json::to_value(&config).unwrap();
10309        assert_eq!(
10310            json,
10311            json!({
10312                "apiType": "anthropic",
10313                "baseUrl": "https://api.anthropic.com"
10314            })
10315        );
10316
10317        let deserialized: ProviderCurrentConfig = serde_json::from_value(json).unwrap();
10318        assert_eq!(deserialized.api_type, LlmProtocol::Anthropic);
10319        assert_eq!(deserialized.base_url, "https://api.anthropic.com");
10320    }
10321
10322    #[cfg(feature = "unstable_llm_providers")]
10323    #[test]
10324    fn test_provider_info_with_current_config() {
10325        let info = ProviderInfo::new(
10326            "main",
10327            vec![LlmProtocol::Anthropic, LlmProtocol::OpenAi],
10328            true,
10329            Some(ProviderCurrentConfig::new(
10330                LlmProtocol::Anthropic,
10331                "https://api.anthropic.com",
10332            )),
10333        );
10334
10335        let json = serde_json::to_value(&info).unwrap();
10336        assert_eq!(
10337            json,
10338            json!({
10339                "providerId": "main",
10340                "supported": ["anthropic", "openai"],
10341                "required": true,
10342                "current": {
10343                    "apiType": "anthropic",
10344                    "baseUrl": "https://api.anthropic.com"
10345                }
10346            })
10347        );
10348
10349        let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10350        assert_eq!(deserialized.provider_id.to_string(), "main");
10351        assert_eq!(deserialized.supported.len(), 2);
10352        assert!(deserialized.required);
10353        assert!(deserialized.current.is_some());
10354        assert_eq!(
10355            deserialized.current.as_ref().unwrap().api_type,
10356            LlmProtocol::Anthropic
10357        );
10358    }
10359
10360    #[cfg(feature = "unstable_llm_providers")]
10361    #[test]
10362    fn test_provider_info_disabled() {
10363        let info = ProviderInfo::new(
10364            "secondary",
10365            vec![LlmProtocol::OpenAi],
10366            false,
10367            None::<ProviderCurrentConfig>,
10368        );
10369
10370        let json = serde_json::to_value(&info).unwrap();
10371        assert_eq!(
10372            json,
10373            json!({
10374                "providerId": "secondary",
10375                "supported": ["openai"],
10376                "required": false
10377            })
10378        );
10379
10380        let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10381        assert_eq!(deserialized.provider_id.to_string(), "secondary");
10382        assert!(!deserialized.required);
10383        assert!(deserialized.current.is_none());
10384    }
10385
10386    #[cfg(feature = "unstable_llm_providers")]
10387    #[test]
10388    fn test_provider_info_missing_current_defaults_to_none() {
10389        // current is optional; omitting it should decode as None
10390        let json = json!({
10391            "providerId": "main",
10392            "supported": ["anthropic"],
10393            "required": true
10394        });
10395        let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10396        assert!(deserialized.current.is_none());
10397    }
10398
10399    #[cfg(feature = "unstable_llm_providers")]
10400    #[test]
10401    fn test_provider_info_explicit_null_current_decodes_to_none() {
10402        // current: null and an omitted current are equivalent on the wire;
10403        // both must deserialize into None so the disabled state is preserved
10404        // regardless of which form the peer chose to send.
10405        let json = json!({
10406            "providerId": "main",
10407            "supported": ["anthropic"],
10408            "required": true,
10409            "current": null
10410        });
10411        let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10412        assert!(deserialized.current.is_none());
10413    }
10414
10415    #[cfg(feature = "unstable_llm_providers")]
10416    #[test]
10417    fn test_list_providers_response_serialization() {
10418        let response = ListProvidersResponse::new(vec![ProviderInfo::new(
10419            "main",
10420            vec![LlmProtocol::Anthropic],
10421            true,
10422            Some(ProviderCurrentConfig::new(
10423                LlmProtocol::Anthropic,
10424                "https://api.anthropic.com",
10425            )),
10426        )]);
10427
10428        let json = serde_json::to_value(&response).unwrap();
10429        assert_eq!(json["providers"].as_array().unwrap().len(), 1);
10430        assert_eq!(json["providers"][0]["providerId"], "main");
10431
10432        let deserialized: ListProvidersResponse = serde_json::from_value(json).unwrap();
10433        assert_eq!(deserialized.providers.len(), 1);
10434    }
10435
10436    #[cfg(feature = "unstable_llm_providers")]
10437    #[test]
10438    fn test_set_provider_request_serialization() {
10439        use std::collections::HashMap;
10440
10441        let mut headers = HashMap::new();
10442        headers.insert("Authorization".to_string(), "Bearer sk-test".to_string());
10443
10444        let request =
10445            SetProviderRequest::new("main", LlmProtocol::OpenAi, "https://api.openai.com/v1")
10446                .headers(headers);
10447
10448        let json = serde_json::to_value(&request).unwrap();
10449        assert_eq!(
10450            json,
10451            json!({
10452                "providerId": "main",
10453                "apiType": "openai",
10454                "baseUrl": "https://api.openai.com/v1",
10455                "headers": {
10456                    "Authorization": "Bearer sk-test"
10457                }
10458            })
10459        );
10460
10461        let deserialized: SetProviderRequest = serde_json::from_value(json).unwrap();
10462        assert_eq!(deserialized.provider_id.to_string(), "main");
10463        assert_eq!(deserialized.api_type, LlmProtocol::OpenAi);
10464        assert_eq!(deserialized.base_url, "https://api.openai.com/v1");
10465        assert_eq!(deserialized.headers.len(), 1);
10466        assert_eq!(
10467            deserialized.headers.get("Authorization").unwrap(),
10468            "Bearer sk-test"
10469        );
10470    }
10471
10472    #[cfg(feature = "unstable_llm_providers")]
10473    #[test]
10474    fn test_set_provider_request_omits_empty_headers() {
10475        let request =
10476            SetProviderRequest::new("main", LlmProtocol::Anthropic, "https://api.anthropic.com");
10477
10478        let json = serde_json::to_value(&request).unwrap();
10479        // headers should be omitted when empty
10480        assert!(!json.as_object().unwrap().contains_key("headers"));
10481    }
10482
10483    #[cfg(feature = "unstable_llm_providers")]
10484    #[test]
10485    fn test_disable_provider_request_serialization() {
10486        let request = DisableProviderRequest::new("secondary");
10487
10488        let json = serde_json::to_value(&request).unwrap();
10489        assert_eq!(json, json!({ "providerId": "secondary" }));
10490
10491        let deserialized: DisableProviderRequest = serde_json::from_value(json).unwrap();
10492        assert_eq!(deserialized.provider_id.to_string(), "secondary");
10493    }
10494
10495    #[cfg(feature = "unstable_llm_providers")]
10496    #[test]
10497    fn test_providers_capabilities_serialization() {
10498        let caps = ProvidersCapabilities::new();
10499
10500        let json = serde_json::to_value(&caps).unwrap();
10501        assert_eq!(json, json!({}));
10502
10503        let deserialized: ProvidersCapabilities = serde_json::from_value(json).unwrap();
10504        assert!(deserialized.meta.is_none());
10505    }
10506
10507    #[cfg(feature = "unstable_llm_providers")]
10508    #[test]
10509    fn test_agent_capabilities_with_providers() {
10510        let caps = AgentCapabilities::new().providers(ProvidersCapabilities::new());
10511
10512        let json = serde_json::to_value(&caps).unwrap();
10513        assert_eq!(json["providers"], json!({}));
10514
10515        let deserialized: AgentCapabilities = serde_json::from_value(json).unwrap();
10516        assert!(deserialized.providers.is_some());
10517    }
10518
10519    #[test]
10520    fn test_agent_capabilities_session_is_explicit() {
10521        let json = serde_json::to_value(AgentCapabilities::new()).unwrap();
10522        assert!(json.get("session").is_none());
10523
10524        let caps = AgentCapabilities::new().session(
10525            SessionCapabilities::new()
10526                .prompt(PromptCapabilities::new().image(PromptImageCapabilities::new()))
10527                .mcp(McpCapabilities::new().stdio(McpStdioCapabilities::new())),
10528        );
10529
10530        assert_eq!(
10531            serde_json::to_value(&caps).unwrap(),
10532            json!({
10533                "session": {
10534                    "prompt": {
10535                        "image": {}
10536                    },
10537                    "mcp": {
10538                        "stdio": {}
10539                    }
10540                }
10541            })
10542        );
10543
10544        let deserialized: AgentCapabilities = serde_json::from_value(json!({
10545            "session": false
10546        }))
10547        .unwrap();
10548        assert!(deserialized.session.is_none());
10549    }
10550
10551    #[test]
10552    fn test_prompt_capabilities_serialize_supported_content_as_objects() {
10553        let caps = PromptCapabilities::new()
10554            .image(PromptImageCapabilities::new())
10555            .audio(PromptAudioCapabilities::new())
10556            .embedded_context(PromptEmbeddedContextCapabilities::new());
10557
10558        assert_eq!(
10559            serde_json::to_value(&caps).unwrap(),
10560            json!({
10561                "image": {},
10562                "audio": {},
10563                "embeddedContext": {}
10564            })
10565        );
10566
10567        let deserialized: PromptCapabilities = serde_json::from_value(json!({
10568            "image": null,
10569            "audio": false,
10570            "embeddedContext": {}
10571        }))
10572        .unwrap();
10573        assert!(deserialized.image.is_none());
10574        assert!(deserialized.audio.is_none());
10575        assert!(deserialized.embedded_context.is_some());
10576    }
10577
10578    #[cfg(feature = "unstable_agent_skills")]
10579    #[test]
10580    fn prompt_skill_capability_has_two_levels() {
10581        // `{}` allows one leading skill block. `inline` allows them anywhere.
10582        let leading = PromptCapabilities::new().skill(PromptSkillCapabilities::new());
10583        assert_eq!(
10584            serde_json::to_value(&leading).unwrap(),
10585            json!({ "skill": {} })
10586        );
10587
10588        let inline = PromptCapabilities::new()
10589            .skill(PromptSkillCapabilities::new().inline(PromptSkillInlineCapabilities::new()));
10590        let wire = json!({ "skill": { "inline": {} } });
10591        assert_eq!(serde_json::to_value(&inline).unwrap(), wire);
10592        assert_eq!(
10593            serde_json::from_value::<PromptCapabilities>(wire).unwrap(),
10594            inline
10595        );
10596
10597        for unsupported in [
10598            json!({}),
10599            json!({ "skill": null }),
10600            json!({ "skill": false }),
10601            json!({ "skill": true }),
10602        ] {
10603            let caps: PromptCapabilities = serde_json::from_value(unsupported).unwrap();
10604            assert!(caps.skill.is_none());
10605        }
10606
10607        // A malformed `inline` does not withdraw the first level.
10608        for leading_only in [
10609            json!({ "skill": { "inline": null } }),
10610            json!({ "skill": { "inline": true } }),
10611        ] {
10612            assert_eq!(
10613                serde_json::from_value::<PromptCapabilities>(leading_only).unwrap(),
10614                leading
10615            );
10616        }
10617    }
10618
10619    #[test]
10620    fn test_mcp_capabilities_serialize_supported_transports_as_objects() {
10621        let caps = McpCapabilities::new()
10622            .stdio(McpStdioCapabilities::new())
10623            .http(McpHttpCapabilities::new());
10624
10625        assert_eq!(
10626            serde_json::to_value(&caps).unwrap(),
10627            json!({
10628                "stdio": {},
10629                "http": {}
10630            })
10631        );
10632
10633        let deserialized: McpCapabilities = serde_json::from_value(json!({
10634            "stdio": null,
10635            "http": false
10636        }))
10637        .unwrap();
10638        assert!(deserialized.stdio.is_none());
10639        assert!(deserialized.http.is_none());
10640    }
10641
10642    #[cfg(feature = "unstable_mcp_over_acp")]
10643    #[test]
10644    fn test_mcp_capabilities_serialize_acp_support_as_object() {
10645        let caps = McpCapabilities::new().acp(McpAcpCapabilities::new());
10646
10647        assert_eq!(
10648            serde_json::to_value(&caps).unwrap(),
10649            json!({
10650                "acp": {}
10651            })
10652        );
10653    }
10654
10655    #[test]
10656    fn prompt_request_rejects_malformed_content_block() {
10657        use serde_json::json;
10658
10659        assert!(
10660            serde_json::from_value::<PromptRequest>(json!({
10661                "sessionId": "sess-1",
10662                "prompt": [{"type": "text"}]
10663            }))
10664            .is_err()
10665        );
10666    }
10667
10668    #[test]
10669    fn prompt_request_rejects_non_array_prompt() {
10670        use serde_json::json;
10671
10672        assert!(
10673            serde_json::from_value::<PromptRequest>(json!({
10674                "sessionId": "sess-1",
10675                "prompt": "hello"
10676            }))
10677            .is_err()
10678        );
10679    }
10680
10681    fn prompt_request_with_idempotency_key(key: &serde_json::Value) -> serde_json::Value {
10682        serde_json::json!({
10683            "sessionId": "sess-1",
10684            "idempotencyKey": key,
10685            "prompt": [{"type": "text", "text": "hello"}]
10686        })
10687    }
10688
10689    #[test]
10690    fn prompt_request_idempotency_key_round_trips() {
10691        use serde_json::json;
10692
10693        let key = "0b6f3c1e-8d2a-4c57-9a41-5e2f7d90c3ab";
10694        let value = prompt_request_with_idempotency_key(&json!(key));
10695
10696        let request: PromptRequest = serde_json::from_value(value.clone()).unwrap();
10697        assert_eq!(
10698            request.idempotency_key.as_ref().map(IdempotencyKey::as_str),
10699            Some(key)
10700        );
10701        assert_eq!(serde_json::to_value(&request).unwrap(), value);
10702
10703        let built = PromptRequest::new("sess-1", vec![ContentBlock::from("hello")])
10704            .idempotency_key(IdempotencyKey::new(key).unwrap());
10705        assert_eq!(built, request);
10706    }
10707
10708    #[test]
10709    fn prompt_request_omitted_and_null_idempotency_key_mean_no_key() {
10710        use serde_json::json;
10711
10712        let omitted = json!({
10713            "sessionId": "sess-1",
10714            "prompt": [{"type": "text", "text": "hello"}]
10715        });
10716        let request: PromptRequest = serde_json::from_value(omitted.clone()).unwrap();
10717        assert_eq!(request.idempotency_key, None);
10718        // No key is serialized as an omitted field, not as `null`.
10719        assert_eq!(serde_json::to_value(&request).unwrap(), omitted);
10720
10721        let null: PromptRequest =
10722            serde_json::from_value(prompt_request_with_idempotency_key(&json!(null))).unwrap();
10723        assert_eq!(null, request);
10724    }
10725
10726    #[test]
10727    fn prompt_request_rejects_malformed_idempotency_key() {
10728        use serde_json::json;
10729
10730        let too_long = "k".repeat(IdempotencyKey::MAX_LENGTH + 1);
10731        for (name, key) in [
10732            ("an empty string", json!("")),
10733            ("a string over 255 characters", json!(too_long)),
10734            ("a number", json!(7)),
10735            ("a boolean", json!(true)),
10736            ("an object", json!({"key": "k"})),
10737            ("an array", json!(["k"])),
10738        ] {
10739            assert!(
10740                serde_json::from_value::<PromptRequest>(prompt_request_with_idempotency_key(&key))
10741                    .is_err(),
10742                "{name} must fail the request instead of being treated as no key"
10743            );
10744        }
10745    }
10746
10747    #[test]
10748    fn idempotency_key_length_is_counted_in_characters() {
10749        use serde_json::json;
10750
10751        assert_eq!(IdempotencyKey::new(""), Err(InvalidIdempotencyKey::Empty));
10752        assert_eq!(IdempotencyKey::new("k").unwrap().as_str(), "k");
10753
10754        let longest = "k".repeat(IdempotencyKey::MAX_LENGTH);
10755        assert_eq!(
10756            IdempotencyKey::new(longest.as_str()).unwrap().as_str(),
10757            longest
10758        );
10759        assert_eq!(
10760            IdempotencyKey::new(format!("{longest}k")),
10761            Err(InvalidIdempotencyKey::TooLong)
10762        );
10763
10764        // 255 two-byte characters are 510 bytes and still within the limit.
10765        let multibyte = "é".repeat(IdempotencyKey::MAX_LENGTH);
10766        assert!(IdempotencyKey::new(multibyte.as_str()).is_ok());
10767        assert!(
10768            serde_json::from_value::<PromptRequest>(prompt_request_with_idempotency_key(&json!(
10769                multibyte
10770            )))
10771            .is_ok()
10772        );
10773        assert_eq!(
10774            IdempotencyKey::new(format!("{multibyte}é")),
10775            Err(InvalidIdempotencyKey::TooLong)
10776        );
10777
10778        assert_eq!("k".parse::<IdempotencyKey>().unwrap().to_string(), "k");
10779        assert_eq!(
10780            IdempotencyKey::try_from(String::new()),
10781            Err(InvalidIdempotencyKey::Empty)
10782        );
10783        assert_eq!(
10784            InvalidIdempotencyKey::TooLong.to_string(),
10785            "idempotency key must be at most 255 characters"
10786        );
10787    }
10788
10789    #[cfg(feature = "uuid")]
10790    #[test]
10791    fn generated_idempotency_keys_are_distinct_valid_v4_uuids() {
10792        let first = IdempotencyKey::generate();
10793        let second = IdempotencyKey::generate();
10794        assert_ne!(first, second);
10795
10796        for key in [&first, &second] {
10797            let uuid = uuid::Uuid::parse_str(key.as_str()).unwrap();
10798            assert_eq!(uuid.get_version_num(), 4);
10799            // A generated key passes the same validation as any other key.
10800            assert_eq!(IdempotencyKey::new(key.as_str()).as_ref(), Ok(key));
10801            let request = PromptRequest::new("sess-1", vec![ContentBlock::from("hello")])
10802                .idempotency_key(key.clone());
10803            let value = serde_json::to_value(&request).unwrap();
10804            assert_eq!(value["idempotencyKey"], key.as_str());
10805            assert_eq!(
10806                serde_json::from_value::<PromptRequest>(value).unwrap(),
10807                request
10808            );
10809        }
10810
10811        assert_eq!(
10812            IdempotencyKey::from(uuid::Uuid::nil()).as_str(),
10813            "00000000-0000-0000-0000-000000000000"
10814        );
10815    }
10816
10817    #[cfg(feature = "schemars")]
10818    #[test]
10819    fn idempotency_key_schema_is_a_strict_bounded_string() {
10820        use serde_json::json;
10821
10822        let key = serde_json::to_value(schemars::schema_for!(IdempotencyKey)).unwrap();
10823        assert_eq!(key["type"], "string");
10824        assert_eq!(key["minLength"], 1);
10825        assert_eq!(key["maxLength"], json!(IdempotencyKey::MAX_LENGTH));
10826
10827        let request = serde_json::to_value(schemars::schema_for!(PromptRequest)).unwrap();
10828        assert_eq!(request["required"], json!(["sessionId", "prompt"]));
10829        let property = &request["properties"]["idempotencyKey"];
10830        assert_eq!(
10831            property["anyOf"],
10832            json!([{"$ref": "#/$defs/IdempotencyKey"}, {"type": "null"}])
10833        );
10834        // The Agent acts on the key, so the schema must not mark it as tolerant
10835        // of malformed values.
10836        assert!(property.get("x-deserialize-default-on-error").is_none());
10837    }
10838
10839    fn assert_session_setup_lists_are_strict<T>(base: &serde_json::Value)
10840    where
10841        T: serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
10842    {
10843        let name = std::any::type_name::<T>();
10844        let with = |field: &str, value: serde_json::Value| {
10845            let mut request = base.clone();
10846            request[field] = value;
10847            serde_json::from_value::<T>(request)
10848        };
10849
10850        for (field, value) in [
10851            // Dropping the malformed server would start the session without it.
10852            (
10853                "mcpServers",
10854                json!([
10855                    {"type": "stdio", "name": "github", "command": "/usr/bin/gh-mcp", "env": [{"name": "GITHUB_TOKEN", "value": null}]},
10856                    {"type": "stdio", "name": "fs", "command": "/usr/bin/fs-mcp"}
10857                ]),
10858            ),
10859            ("mcpServers", json!({"type": "stdio", "name": "fs"})),
10860            ("additionalDirectories", json!(["/repo/lib", 42])),
10861            ("additionalDirectories", json!("/repo/lib")),
10862        ] {
10863            assert!(
10864                with(field, value.clone()).is_err(),
10865                "{name}.{field}: {value}"
10866            );
10867        }
10868
10869        let empty = serde_json::from_value::<T>(base.clone()).unwrap();
10870        for field in ["mcpServers", "additionalDirectories"] {
10871            assert_eq!(
10872                with(field, serde_json::Value::Null).unwrap(),
10873                empty,
10874                "{name}.{field}"
10875            );
10876        }
10877    }
10878
10879    #[test]
10880    fn session_setup_requests_reject_malformed_mcp_servers_and_directories() {
10881        assert_session_setup_lists_are_strict::<NewSessionRequest>(&json!({"cwd": "/repo"}));
10882        assert_session_setup_lists_are_strict::<ResumeSessionRequest>(&json!({
10883            "sessionId": "sess-1",
10884            "cwd": "/repo"
10885        }));
10886        #[cfg(feature = "unstable_session_fork")]
10887        assert_session_setup_lists_are_strict::<ForkSessionRequest>(&json!({
10888            "sessionId": "sess-1",
10889            "cwd": "/repo"
10890        }));
10891    }
10892
10893    #[test]
10894    fn resume_session_request_rejects_malformed_replay_from() {
10895        let request = |replay_from: serde_json::Value| {
10896            serde_json::from_value::<ResumeSessionRequest>(json!({
10897                "sessionId": "sess-1",
10898                "cwd": "/repo",
10899                "replayFrom": replay_from
10900            }))
10901        };
10902
10903        // Treating this as omitted would reconnect without the requested replay.
10904        assert!(request(json!("start")).is_err());
10905        assert_eq!(request(serde_json::Value::Null).unwrap().replay_from, None);
10906        assert!(matches!(
10907            request(json!({"type": "start"})).unwrap().replay_from,
10908            Some(ReplayFrom::Start(_))
10909        ));
10910    }
10911
10912    #[test]
10913    fn mcp_server_lists_treat_null_as_empty() {
10914        let servers: Vec<McpServer> = serde_json::from_value(json!([
10915            {"type": "stdio", "name": "fs", "command": "/usr/bin/fs-mcp", "args": null, "env": null},
10916            {"type": "http", "name": "api", "url": "https://example.com/mcp", "headers": null}
10917        ]))
10918        .unwrap();
10919
10920        assert_eq!(
10921            servers,
10922            vec![
10923                McpServer::Stdio(McpServerStdio::new("fs", "/usr/bin/fs-mcp")),
10924                McpServer::Http(McpServerHttp::new("api", "https://example.com/mcp")),
10925            ]
10926        );
10927    }
10928
10929    #[test]
10930    fn terminal_auth_methods_reject_malformed_launch_config() {
10931        // The client spawns a process from `args` and `env`, so a malformed
10932        // method is dropped from `authMethods` instead of launched with
10933        // altered arguments or preserved as an unknown method.
10934        let response: InitializeResponse = serde_json::from_value(json!({
10935            "protocolVersion": 2,
10936            "info": {"name": "agent", "version": "1.0.0"},
10937            "authMethods": [
10938                {"type": "terminal", "methodId": "bad-args", "name": "Log in", "args": ["auth", "--port", 8123]},
10939                {"type": "terminal", "methodId": "bad-env", "name": "Log in", "env": [{"name": "DEBUG", "value": 1}]},
10940                {"type": "terminal", "methodId": "null-config", "name": "Log in", "args": null, "env": null},
10941                {"type": "agent", "methodId": "agent", "name": "Agent login"}
10942            ]
10943        }))
10944        .unwrap();
10945
10946        assert_eq!(
10947            response.auth_methods,
10948            vec![
10949                AuthMethod::Terminal(AuthMethodTerminal::new("null-config", "Log in")),
10950                AuthMethod::Agent(AuthMethodAgent::new("agent", "Agent login")),
10951            ]
10952        );
10953    }
10954
10955    #[cfg(feature = "unstable_auth_status")]
10956    #[test]
10957    fn auth_status_response_round_trips() {
10958        let response = AuthStatusResponse::new(AuthState::Authenticated).accounts(vec![
10959            AuthAccount::new("Anthropic API key")
10960                .description("API key helper".to_string())
10961                .active(true),
10962            AuthAccount::new("Claude Max").email("user@example.com".to_string()),
10963        ]);
10964        let json = serde_json::to_value(&response).unwrap();
10965        assert_eq!(
10966            json,
10967            json!({
10968                "state": "authenticated",
10969                "accounts": [
10970                    {
10971                        "label": "Anthropic API key",
10972                        "description": "API key helper",
10973                        "active": true
10974                    },
10975                    {
10976                        "label": "Claude Max",
10977                        "email": "user@example.com"
10978                    }
10979                ]
10980            })
10981        );
10982        assert_eq!(
10983            serde_json::from_value::<AuthStatusResponse>(json).unwrap(),
10984            response
10985        );
10986        assert_eq!(
10987            serde_json::to_value(AuthStatusResponse::new(AuthState::NotRequired)).unwrap(),
10988            json!({"state": "not_required"})
10989        );
10990    }
10991
10992    #[cfg(feature = "unstable_auth_status")]
10993    #[test]
10994    fn auth_status_state_is_strict_and_accounts_are_lenient() {
10995        assert!(serde_json::from_value::<AuthStatusResponse>(json!({})).is_err());
10996        assert!(serde_json::from_value::<AuthStatusResponse>(json!({"state": null})).is_err());
10997        assert!(serde_json::from_value::<AuthStatusResponse>(json!({"state": 1})).is_err());
10998
10999        let response: AuthStatusResponse = serde_json::from_value(json!({
11000            "state": "_vendor_state",
11001            "accounts": [
11002                {"active": true},
11003                {
11004                    "label": "Vertex AI",
11005                    "description": 42,
11006                    "active": "yes",
11007                    "email": ["not", "a", "string"]
11008                }
11009            ]
11010        }))
11011        .unwrap();
11012        assert_eq!(
11013            response,
11014            AuthStatusResponse::new(AuthState::Other("_vendor_state".to_string()))
11015                .accounts(vec![AuthAccount::new("Vertex AI")])
11016        );
11017        assert_eq!(
11018            serde_json::from_value::<AuthStatusResponse>(
11019                json!({"state": "unknown", "accounts": null})
11020            )
11021            .unwrap(),
11022            AuthStatusResponse::new(AuthState::Unknown)
11023        );
11024    }
11025
11026    #[cfg(feature = "unstable_auth_status")]
11027    #[test]
11028    fn auth_status_update_notification_routes() {
11029        use crate::v2::{AgentNotification, CLIENT_METHOD_NAMES};
11030
11031        assert_eq!(AGENT_METHOD_NAMES.auth_status, "auth/status");
11032        assert_eq!(CLIENT_METHOD_NAMES.auth_status_update, "auth/status_update");
11033        let notification = AgentNotification::AuthStatusUpdateNotification(Box::new(
11034            AuthStatusUpdateNotification::new(AuthState::Unauthenticated),
11035        ));
11036        assert_eq!(notification.method(), "auth/status_update");
11037        assert_eq!(
11038            serde_json::to_value(&notification).unwrap(),
11039            json!({"state": "unauthenticated"})
11040        );
11041    }
11042
11043    #[cfg(all(
11044        feature = "unstable_session_fork",
11045        feature = "unstable_session_cursors"
11046    ))]
11047    #[test]
11048    fn fork_session_request_cursor_id_is_optional_and_strict() {
11049        let request = ForkSessionRequest::new("sess_abc123", "/home/user/project")
11050            .cursor_id(CursorId::new("cur_1"));
11051        let wire = json!({
11052            "sessionId": "sess_abc123",
11053            "cursorId": "cur_1",
11054            "cwd": "/home/user/project"
11055        });
11056        assert_eq!(serde_json::to_value(&request).unwrap(), wire);
11057        assert_eq!(
11058            serde_json::from_value::<ForkSessionRequest>(wire).unwrap(),
11059            request
11060        );
11061
11062        // Omitted and `null` both fork the whole session.
11063        for wire in [
11064            json!({ "sessionId": "sess_abc123", "cwd": "/home/user/project" }),
11065            json!({ "sessionId": "sess_abc123", "cwd": "/home/user/project", "cursorId": null }),
11066        ] {
11067            assert_eq!(
11068                serde_json::from_value::<ForkSessionRequest>(wire)
11069                    .unwrap()
11070                    .cursor_id,
11071                None
11072            );
11073        }
11074
11075        // A malformed cursor ID fails the request. It never forks the whole session.
11076        assert!(
11077            serde_json::from_value::<ForkSessionRequest>(json!({
11078                "sessionId": "sess_abc123",
11079                "cwd": "/home/user/project",
11080                "cursorId": 7
11081            }))
11082            .is_err()
11083        );
11084    }
11085}