Skip to main content

agent_client_protocol_schema/v2/
conversion.rs

1//! Explicit conversion helpers for experimenting with ACP v2 while SDKs still speak v1.
2//!
3//! The conversions below intentionally move values field-by-field and
4//! variant-by-variant instead of serializing through JSON so v2 shape changes
5//! have obvious edit points. Conversions use [`From`] when every source value
6//! has a target representation and [`TryFrom`] when values outside the shared
7//! protocol subset must be rejected instead of guessed, dropped, or defaulted.
8//! One-to-many fan-out is represented as `TryFrom<Source> for Vec<Target>`.
9//!
10//! These helpers are convenience APIs for code that wants to share internal
11//! ACP-shaped values while supporting both protocol versions. They are not a
12//! protocol router: SDKs should choose the v1 or v2 implementation for a
13//! connection before dispatching JSON-RPC messages.
14
15use std::{
16    collections::{BTreeMap, HashMap},
17    convert::Infallible,
18    fmt,
19    hash::{BuildHasher, Hash},
20    path::{Path, PathBuf},
21    sync::Arc,
22};
23
24use serde_json::value::RawValue;
25
26use crate::version::ProtocolVersion;
27
28/// Result type returned by protocol try-conversion helpers.
29pub type Result<T> = std::result::Result<T, ProtocolConversionError>;
30
31/// Error returned when converting between v1 and v2 protocol type namespaces fails.
32#[derive(Debug, Clone, PartialEq, Eq)]
33#[non_exhaustive]
34pub struct ProtocolConversionError {
35    message: String,
36}
37
38impl ProtocolConversionError {
39    /// Creates a conversion error with a human-readable message.
40    #[must_use]
41    pub fn new(message: impl Into<String>) -> Self {
42        Self {
43            message: message.into(),
44        }
45    }
46
47    /// Returns the human-readable conversion error message.
48    #[must_use]
49    pub fn message(&self) -> &str {
50        &self.message
51    }
52}
53
54impl fmt::Display for ProtocolConversionError {
55    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
56        formatter.write_str(&self.message)
57    }
58}
59
60impl std::error::Error for ProtocolConversionError {}
61
62impl From<Infallible> for ProtocolConversionError {
63    fn from(error: Infallible) -> Self {
64        match error {}
65    }
66}
67
68fn unknown_v2_enum_variant(type_name: &str, value: &str) -> ProtocolConversionError {
69    ProtocolConversionError::new(format!(
70        "v2 {type_name} variant `{value}` cannot be represented in v1"
71    ))
72}
73
74fn removed_v1_enum_variant(type_name: &str, value: &str) -> ProtocolConversionError {
75    ProtocolConversionError::new(format!(
76        "v1 {type_name} variant `{value}` cannot be represented in v2"
77    ))
78}
79
80fn unrepresentable_v1_field(type_name: &str, field: &str) -> ProtocolConversionError {
81    ProtocolConversionError::new(format!(
82        "v1 {type_name}.{field} cannot be represented in v2"
83    ))
84}
85
86fn unrepresentable_v2_field(type_name: &str, field: &str) -> ProtocolConversionError {
87    ProtocolConversionError::new(format!(
88        "v2 {type_name}.{field} cannot be represented in v1"
89    ))
90}
91
92fn reject_v2_marker_meta(type_name: &str, field: &str, meta: Option<&super::Meta>) -> Result<()> {
93    if meta.is_some() {
94        return Err(ProtocolConversionError::new(format!(
95            "v2 {type_name}.{field} metadata cannot be represented in v1"
96        )));
97    }
98    Ok(())
99}
100
101fn reject_v1_marker_meta(
102    type_name: &str,
103    field: &str,
104    meta: Option<&crate::v1::Meta>,
105) -> Result<()> {
106    if meta.is_some() {
107        return Err(ProtocolConversionError::new(format!(
108            "v1 {type_name}.{field} metadata cannot be represented in v2"
109        )));
110    }
111    Ok(())
112}
113
114const LEGACY_V1_PLAN_ID: &str = "main";
115
116/// Converts a [`ProtocolConversionError`] into a v1 [`Error`](crate::v1::Error)
117/// so callers can use `?` to bubble conversion failures through APIs that
118/// already speak the v1 error type.
119///
120/// The conversion is mapped onto [`Error::internal_error`](crate::v1::Error::internal_error)
121/// because a failed cross-version conversion always indicates a protocol
122/// mismatch on this side of the wire rather than a client mistake.
123impl From<ProtocolConversionError> for crate::v1::Error {
124    fn from(error: ProtocolConversionError) -> Self {
125        crate::v1::Error::internal_error().data(error.message)
126    }
127}
128
129/// Mirror of the [v1 `From`](#impl-From%3CProtocolConversionError%3E-for-Error)
130/// impl for the v2 [`Error`](crate::v2::Error) type.
131impl From<ProtocolConversionError> for crate::v2::Error {
132    fn from(error: ProtocolConversionError) -> Self {
133        crate::v2::Error::internal_error().data(error.message)
134    }
135}
136
137trait TryToV1 {
138    /// The corresponding v1 type.
139    type Output;
140
141    /// Attempts to convert this value into the corresponding v1 type.
142    ///
143    /// # Errors
144    ///
145    /// Returns [`ProtocolConversionError`] when a value cannot be represented in v1.
146    fn try_to_v1(self) -> Result<Self::Output>;
147}
148
149trait TryToV2 {
150    /// The corresponding v2 draft type.
151    type Output;
152
153    /// Attempts to convert this value into the corresponding v2 draft type.
154    ///
155    /// # Errors
156    ///
157    /// Returns [`ProtocolConversionError`] when a value cannot be represented in v2.
158    fn try_to_v2(self) -> Result<Self::Output>;
159}
160
161/// Attempts to convert a v2 draft value into the corresponding v1 value type.
162///
163/// Infallible [`From`] conversions also work with this helper through the
164/// standard library's blanket [`TryFrom`] implementation.
165///
166/// # Errors
167///
168/// Returns [`ProtocolConversionError`] when a value cannot be represented in v1.
169pub fn try_v2_to_v1<T, U>(value: T) -> Result<U>
170where
171    U: TryFrom<T>,
172    ProtocolConversionError: From<<U as TryFrom<T>>::Error>,
173{
174    U::try_from(value).map_err(ProtocolConversionError::from)
175}
176
177/// Attempts to convert a v2 draft value into one or more corresponding v1 values.
178///
179/// This is a readability wrapper around `Vec::<U>::try_from(value)`.
180///
181/// One-to-many conversions are stateless. When a v2 update's semantics depend
182/// on previously delivered updates, this helper can only reject cases that are
183/// visible in the value being converted. For example, a content-bearing whole
184/// message update can be emitted as v1 chunks, but v1 cannot represent the
185/// replacement semantics if the v1 side has already received content for that
186/// `messageId`.
187///
188/// # Errors
189///
190/// Returns [`ProtocolConversionError`] when a value cannot be represented in v1.
191pub fn try_v2_to_v1_many<T, U>(value: T) -> Result<Vec<U>>
192where
193    Vec<U>: TryFrom<T>,
194    ProtocolConversionError: From<<Vec<U> as TryFrom<T>>::Error>,
195{
196    Vec::<U>::try_from(value).map_err(ProtocolConversionError::from)
197}
198
199/// Attempts to convert a v1 value into the corresponding v2 draft value type.
200///
201/// Infallible [`From`] conversions also work with this helper through the
202/// standard library's blanket [`TryFrom`] implementation.
203///
204/// # Errors
205///
206/// Returns [`ProtocolConversionError`] when a value cannot be represented in v2.
207pub fn try_v1_to_v2<T, U>(value: T) -> Result<U>
208where
209    U: TryFrom<T>,
210    ProtocolConversionError: From<<U as TryFrom<T>>::Error>,
211{
212    U::try_from(value).map_err(ProtocolConversionError::from)
213}
214
215macro_rules! impl_from_tuple_newtype {
216    ($source:path => $target:path) => {
217        impl From<$source> for $target {
218            fn from(value: $source) -> Self {
219                $target(value.0)
220            }
221        }
222    };
223}
224
225macro_rules! impl_from_enum {
226    ($source:ty => $target:ty { $($variant:ident),+ $(,)? }) => {
227        impl From<$source> for $target {
228            fn from(value: $source) -> Self {
229                match value {
230                    $(<$source>::$variant => <$target>::$variant,)+
231                }
232            }
233        }
234    };
235}
236
237macro_rules! impl_try_from_v2_to_v1 {
238    ($source:ty => $target:ty) => {
239        impl TryFrom<$source> for $target {
240            type Error = ProtocolConversionError;
241
242            fn try_from(value: $source) -> Result<Self> {
243                value.try_to_v1()
244            }
245        }
246    };
247}
248
249macro_rules! impl_try_from_v1_to_v2 {
250    ($source:ty => $target:ty) => {
251        impl TryFrom<$source> for $target {
252            type Error = ProtocolConversionError;
253
254            fn try_from(value: $source) -> Result<Self> {
255                value.try_to_v2()
256            }
257        }
258    };
259}
260
261impl_from_tuple_newtype!(super::SessionId => crate::v1::SessionId);
262impl_from_tuple_newtype!(crate::v1::SessionId => super::SessionId);
263impl_from_tuple_newtype!(super::MessageId => crate::v1::MessageId);
264impl_from_tuple_newtype!(crate::v1::MessageId => super::MessageId);
265#[cfg(not(feature = "unstable_plan_operations"))]
266impl_try_from_v2_to_v1!(super::PlanUpdate => crate::v1::Plan);
267#[cfg(feature = "unstable_plan_operations")]
268impl_from_tuple_newtype!(super::PlanId => crate::v1::PlanId);
269#[cfg(feature = "unstable_plan_operations")]
270impl_from_tuple_newtype!(crate::v1::PlanId => super::PlanId);
271#[cfg(feature = "unstable_plan_operations")]
272impl_try_from_v2_to_v1!(super::PlanUpdate => crate::v1::PlanUpdate);
273#[cfg(feature = "unstable_plan_operations")]
274impl_try_from_v1_to_v2!(crate::v1::PlanUpdate => super::PlanUpdate);
275#[cfg(feature = "unstable_plan_operations")]
276impl_try_from_v2_to_v1!(super::PlanUpdateContent => crate::v1::PlanUpdateContent);
277#[cfg(feature = "unstable_plan_operations")]
278impl_try_from_v1_to_v2!(crate::v1::PlanUpdateContent => super::PlanUpdateContent);
279#[cfg(feature = "unstable_plan_operations")]
280impl_try_from_v2_to_v1!(super::PlanItems => crate::v1::PlanItems);
281#[cfg(feature = "unstable_plan_operations")]
282impl_try_from_v1_to_v2!(crate::v1::PlanItems => super::PlanItems);
283#[cfg(feature = "unstable_plan_operations")]
284impl_try_from_v2_to_v1!(super::PlanFile => crate::v1::PlanFile);
285#[cfg(feature = "unstable_plan_operations")]
286impl_try_from_v1_to_v2!(crate::v1::PlanFile => super::PlanFile);
287#[cfg(feature = "unstable_plan_operations")]
288impl_try_from_v2_to_v1!(super::PlanMarkdown => crate::v1::PlanMarkdown);
289#[cfg(feature = "unstable_plan_operations")]
290impl_try_from_v1_to_v2!(crate::v1::PlanMarkdown => super::PlanMarkdown);
291#[cfg(feature = "unstable_plan_operations")]
292impl_try_from_v2_to_v1!(super::PlanRemoved => crate::v1::PlanRemoved);
293#[cfg(feature = "unstable_plan_operations")]
294impl_try_from_v1_to_v2!(crate::v1::PlanRemoved => super::PlanRemoved);
295impl_try_from_v2_to_v1!(super::PlanEntry => crate::v1::PlanEntry);
296impl_try_from_v1_to_v2!(crate::v1::PlanEntry => super::PlanEntry);
297impl_try_from_v2_to_v1!(super::PlanEntryPriority => crate::v1::PlanEntryPriority);
298impl_from_enum!(crate::v1::PlanEntryPriority => super::PlanEntryPriority {
299    High,
300    Medium,
301    Low,
302});
303impl_try_from_v2_to_v1!(super::PlanEntryStatus => crate::v1::PlanEntryStatus);
304impl_from_enum!(crate::v1::PlanEntryStatus => super::PlanEntryStatus {
305    Pending,
306    InProgress,
307    Completed,
308});
309impl_try_from_v2_to_v1!(super::CancelRequestNotification => crate::v1::CancelRequestNotification);
310impl_try_from_v1_to_v2!(crate::v1::CancelRequestNotification => super::CancelRequestNotification);
311impl_try_from_v2_to_v1!(super::ProtocolLevelNotification => crate::v1::ProtocolLevelNotification);
312impl_try_from_v1_to_v2!(crate::v1::ProtocolLevelNotification => super::ProtocolLevelNotification);
313impl_try_from_v1_to_v2!(crate::v1::SessionNotification => super::UpdateSessionNotification);
314impl_try_from_v1_to_v2!(crate::v1::SessionUpdate => super::SessionUpdate);
315impl_try_from_v2_to_v1!(super::ConfigOptionUpdate => crate::v1::ConfigOptionUpdate);
316impl_try_from_v1_to_v2!(crate::v1::ConfigOptionUpdate => super::ConfigOptionUpdate);
317impl_try_from_v2_to_v1!(super::SessionInfoUpdate => crate::v1::SessionInfoUpdate);
318impl_try_from_v1_to_v2!(crate::v1::SessionInfoUpdate => super::SessionInfoUpdate);
319impl_try_from_v2_to_v1!(super::UsageUpdate => crate::v1::UsageUpdate);
320impl_try_from_v1_to_v2!(crate::v1::UsageUpdate => super::UsageUpdate);
321impl_try_from_v2_to_v1!(super::Cost => crate::v1::Cost);
322impl_try_from_v1_to_v2!(crate::v1::Cost => super::Cost);
323impl_try_from_v2_to_v1!(super::ContentChunk => crate::v1::ContentChunk);
324impl_try_from_v1_to_v2!(crate::v1::ContentChunk => super::ContentChunk);
325impl_try_from_v2_to_v1!(super::AvailableCommandsUpdate => crate::v1::AvailableCommandsUpdate);
326impl_try_from_v1_to_v2!(crate::v1::AvailableCommandsUpdate => super::AvailableCommandsUpdate);
327impl_try_from_v2_to_v1!(super::AvailableCommand => crate::v1::AvailableCommand);
328impl_try_from_v1_to_v2!(crate::v1::AvailableCommand => super::AvailableCommand);
329impl_try_from_v2_to_v1!(super::AvailableCommandInput => crate::v1::AvailableCommandInput);
330impl_try_from_v1_to_v2!(crate::v1::AvailableCommandInput => super::AvailableCommandInput);
331impl_try_from_v2_to_v1!(super::TextCommandInput => crate::v1::UnstructuredCommandInput);
332impl_try_from_v1_to_v2!(crate::v1::UnstructuredCommandInput => super::TextCommandInput);
333impl_try_from_v2_to_v1!(super::RequestPermissionRequest => crate::v1::RequestPermissionRequest);
334impl_try_from_v1_to_v2!(crate::v1::RequestPermissionRequest => super::RequestPermissionRequest);
335impl_try_from_v2_to_v1!(super::PermissionOption => crate::v1::PermissionOption);
336impl_try_from_v1_to_v2!(crate::v1::PermissionOption => super::PermissionOption);
337impl_from_tuple_newtype!(super::PermissionOptionId => crate::v1::PermissionOptionId);
338impl_from_tuple_newtype!(crate::v1::PermissionOptionId => super::PermissionOptionId);
339impl_try_from_v2_to_v1!(super::PermissionOptionKind => crate::v1::PermissionOptionKind);
340impl_from_enum!(crate::v1::PermissionOptionKind => super::PermissionOptionKind {
341    AllowOnce,
342    AllowAlways,
343    RejectOnce,
344    RejectAlways,
345});
346impl_try_from_v2_to_v1!(super::RequestPermissionResponse => crate::v1::RequestPermissionResponse);
347impl_try_from_v1_to_v2!(crate::v1::RequestPermissionResponse => super::RequestPermissionResponse);
348impl_try_from_v2_to_v1!(super::RequestPermissionOutcome => crate::v1::RequestPermissionOutcome);
349impl_try_from_v1_to_v2!(crate::v1::RequestPermissionOutcome => super::RequestPermissionOutcome);
350impl_try_from_v2_to_v1!(super::SelectedPermissionOutcome => crate::v1::SelectedPermissionOutcome);
351impl_try_from_v1_to_v2!(crate::v1::SelectedPermissionOutcome => super::SelectedPermissionOutcome);
352#[cfg(feature = "unstable_mcp_over_acp")]
353impl_try_from_v2_to_v1!(super::ConnectMcpRequest => crate::v1::ConnectMcpRequest);
354#[cfg(feature = "unstable_mcp_over_acp")]
355impl_try_from_v1_to_v2!(crate::v1::ConnectMcpRequest => super::ConnectMcpRequest);
356#[cfg(feature = "unstable_mcp_over_acp")]
357impl_try_from_v2_to_v1!(super::ConnectMcpResponse => crate::v1::ConnectMcpResponse);
358#[cfg(feature = "unstable_mcp_over_acp")]
359impl_try_from_v1_to_v2!(crate::v1::ConnectMcpResponse => super::ConnectMcpResponse);
360#[cfg(feature = "unstable_mcp_over_acp")]
361impl_try_from_v2_to_v1!(super::MessageMcpRequest => crate::v1::MessageMcpRequest);
362#[cfg(feature = "unstable_mcp_over_acp")]
363impl_try_from_v1_to_v2!(crate::v1::MessageMcpRequest => super::MessageMcpRequest);
364#[cfg(feature = "unstable_mcp_over_acp")]
365impl_try_from_v2_to_v1!(super::MessageMcpNotification => crate::v1::MessageMcpNotification);
366#[cfg(feature = "unstable_mcp_over_acp")]
367impl_try_from_v1_to_v2!(crate::v1::MessageMcpNotification => super::MessageMcpNotification);
368#[cfg(feature = "unstable_mcp_over_acp")]
369impl_try_from_v2_to_v1!(super::MessageMcpResponse => crate::v1::MessageMcpResponse);
370#[cfg(feature = "unstable_mcp_over_acp")]
371impl_try_from_v1_to_v2!(crate::v1::MessageMcpResponse => super::MessageMcpResponse);
372#[cfg(feature = "unstable_mcp_over_acp")]
373impl_try_from_v2_to_v1!(super::DisconnectMcpRequest => crate::v1::DisconnectMcpRequest);
374#[cfg(feature = "unstable_mcp_over_acp")]
375impl_try_from_v1_to_v2!(crate::v1::DisconnectMcpRequest => super::DisconnectMcpRequest);
376#[cfg(feature = "unstable_mcp_over_acp")]
377impl_try_from_v2_to_v1!(super::DisconnectMcpResponse => crate::v1::DisconnectMcpResponse);
378#[cfg(feature = "unstable_mcp_over_acp")]
379impl_try_from_v1_to_v2!(crate::v1::DisconnectMcpResponse => super::DisconnectMcpResponse);
380impl_try_from_v2_to_v1!(super::ClientCapabilities => crate::v1::ClientCapabilities);
381impl_try_from_v1_to_v2!(crate::v1::ClientCapabilities => super::ClientCapabilities);
382#[cfg(feature = "unstable_auth_methods")]
383impl_try_from_v2_to_v1!(super::AuthCapabilities => crate::v1::AuthCapabilities);
384#[cfg(feature = "unstable_auth_methods")]
385impl_try_from_v1_to_v2!(crate::v1::AuthCapabilities => super::AuthCapabilities);
386impl_try_from_v2_to_v1!(super::Error => crate::v1::Error);
387impl_try_from_v1_to_v2!(crate::v1::Error => super::Error);
388impl From<super::ErrorCode> for crate::v1::ErrorCode {
389    fn from(value: super::ErrorCode) -> Self {
390        i32::from(value).into()
391    }
392}
393
394impl From<crate::v1::ErrorCode> for super::ErrorCode {
395    fn from(value: crate::v1::ErrorCode) -> Self {
396        i32::from(value).into()
397    }
398}
399
400impl_try_from_v2_to_v1!(super::ExtRequest => crate::v1::ExtRequest);
401impl_try_from_v1_to_v2!(crate::v1::ExtRequest => super::ExtRequest);
402impl_try_from_v2_to_v1!(super::ExtResponse => crate::v1::ExtResponse);
403impl_try_from_v1_to_v2!(crate::v1::ExtResponse => super::ExtResponse);
404impl_try_from_v2_to_v1!(super::ExtNotification => crate::v1::ExtNotification);
405impl_try_from_v1_to_v2!(crate::v1::ExtNotification => super::ExtNotification);
406impl_try_from_v2_to_v1!(super::ToolCallUpdate => crate::v1::ToolCallUpdate);
407impl_try_from_v1_to_v2!(crate::v1::ToolCall => super::ToolCallUpdate);
408impl_try_from_v1_to_v2!(crate::v1::ToolCallUpdate => super::ToolCallUpdate);
409impl_from_tuple_newtype!(super::ToolCallId => crate::v1::ToolCallId);
410impl_from_tuple_newtype!(crate::v1::ToolCallId => super::ToolCallId);
411impl_try_from_v2_to_v1!(super::ToolKind => crate::v1::ToolKind);
412impl_from_enum!(crate::v1::ToolKind => super::ToolKind {
413    Read,
414    Edit,
415    Delete,
416    Move,
417    Search,
418    Execute,
419    Think,
420    Fetch,
421    SwitchMode,
422    Other,
423});
424impl_try_from_v2_to_v1!(super::ToolCallStatus => crate::v1::ToolCallStatus);
425impl_from_enum!(crate::v1::ToolCallStatus => super::ToolCallStatus {
426    Pending,
427    InProgress,
428    Completed,
429    Failed,
430});
431impl_try_from_v2_to_v1!(super::ToolCallContent => crate::v1::ToolCallContent);
432impl_try_from_v1_to_v2!(crate::v1::ToolCallContent => super::ToolCallContent);
433impl_try_from_v2_to_v1!(super::Content => crate::v1::Content);
434impl_try_from_v1_to_v2!(crate::v1::Content => super::Content);
435impl_try_from_v2_to_v1!(super::Diff => crate::v1::Diff);
436impl_try_from_v1_to_v2!(crate::v1::Diff => super::Diff);
437impl_try_from_v2_to_v1!(super::ToolCallLocation => crate::v1::ToolCallLocation);
438impl_try_from_v1_to_v2!(crate::v1::ToolCallLocation => super::ToolCallLocation);
439impl_try_from_v2_to_v1!(super::InitializeRequest => crate::v1::InitializeRequest);
440impl_try_from_v1_to_v2!(crate::v1::InitializeRequest => super::InitializeRequest);
441impl_try_from_v2_to_v1!(super::InitializeResponse => crate::v1::InitializeResponse);
442impl_try_from_v1_to_v2!(crate::v1::InitializeResponse => super::InitializeResponse);
443impl_try_from_v2_to_v1!(super::Implementation => crate::v1::Implementation);
444impl_try_from_v1_to_v2!(crate::v1::Implementation => super::Implementation);
445impl_try_from_v2_to_v1!(super::LoginAuthRequest => crate::v1::AuthenticateRequest);
446impl_try_from_v1_to_v2!(crate::v1::AuthenticateRequest => super::LoginAuthRequest);
447impl_try_from_v2_to_v1!(super::LoginAuthResponse => crate::v1::AuthenticateResponse);
448impl_try_from_v1_to_v2!(crate::v1::AuthenticateResponse => super::LoginAuthResponse);
449impl_try_from_v2_to_v1!(super::LogoutAuthRequest => crate::v1::LogoutRequest);
450impl_try_from_v1_to_v2!(crate::v1::LogoutRequest => super::LogoutAuthRequest);
451impl_try_from_v2_to_v1!(super::LogoutAuthResponse => crate::v1::LogoutResponse);
452impl_try_from_v1_to_v2!(crate::v1::LogoutResponse => super::LogoutAuthResponse);
453impl_try_from_v2_to_v1!(super::AgentAuthCapabilities => crate::v1::AgentAuthCapabilities);
454impl_try_from_v1_to_v2!(crate::v1::AgentAuthCapabilities => super::AgentAuthCapabilities);
455impl_from_tuple_newtype!(super::AuthMethodId => crate::v1::AuthMethodId);
456impl_from_tuple_newtype!(crate::v1::AuthMethodId => super::AuthMethodId);
457impl_try_from_v2_to_v1!(super::AuthMethod => crate::v1::AuthMethod);
458impl_try_from_v1_to_v2!(crate::v1::AuthMethod => super::AuthMethod);
459impl_try_from_v2_to_v1!(super::AuthMethodAgent => crate::v1::AuthMethodAgent);
460impl_try_from_v1_to_v2!(crate::v1::AuthMethodAgent => super::AuthMethodAgent);
461#[cfg(feature = "unstable_auth_methods")]
462impl_try_from_v2_to_v1!(super::AuthMethodEnvVar => crate::v1::AuthMethodEnvVar);
463#[cfg(feature = "unstable_auth_methods")]
464impl_try_from_v1_to_v2!(crate::v1::AuthMethodEnvVar => super::AuthMethodEnvVar);
465#[cfg(feature = "unstable_auth_methods")]
466impl_try_from_v2_to_v1!(super::AuthEnvVar => crate::v1::AuthEnvVar);
467#[cfg(feature = "unstable_auth_methods")]
468impl_try_from_v1_to_v2!(crate::v1::AuthEnvVar => super::AuthEnvVar);
469#[cfg(feature = "unstable_auth_methods")]
470impl_try_from_v2_to_v1!(super::AuthMethodTerminal => crate::v1::AuthMethodTerminal);
471#[cfg(feature = "unstable_auth_methods")]
472impl_try_from_v1_to_v2!(crate::v1::AuthMethodTerminal => super::AuthMethodTerminal);
473impl_try_from_v2_to_v1!(super::NewSessionRequest => crate::v1::NewSessionRequest);
474impl_try_from_v1_to_v2!(crate::v1::NewSessionRequest => super::NewSessionRequest);
475impl_try_from_v2_to_v1!(super::NewSessionResponse => crate::v1::NewSessionResponse);
476impl_try_from_v1_to_v2!(crate::v1::NewSessionResponse => super::NewSessionResponse);
477impl_try_from_v1_to_v2!(crate::v1::LoadSessionRequest => super::ResumeSessionRequest);
478impl_try_from_v1_to_v2!(crate::v1::LoadSessionResponse => super::ResumeSessionResponse);
479#[cfg(feature = "unstable_session_fork")]
480impl_try_from_v2_to_v1!(super::ForkSessionRequest => crate::v1::ForkSessionRequest);
481#[cfg(feature = "unstable_session_fork")]
482impl_try_from_v1_to_v2!(crate::v1::ForkSessionRequest => super::ForkSessionRequest);
483#[cfg(feature = "unstable_session_fork")]
484impl_try_from_v2_to_v1!(super::ForkSessionResponse => crate::v1::ForkSessionResponse);
485#[cfg(feature = "unstable_session_fork")]
486impl_try_from_v1_to_v2!(crate::v1::ForkSessionResponse => super::ForkSessionResponse);
487impl_try_from_v2_to_v1!(super::ResumeSessionRequest => crate::v1::ResumeSessionRequest);
488impl_try_from_v1_to_v2!(crate::v1::ResumeSessionRequest => super::ResumeSessionRequest);
489impl TryFrom<super::ResumeSessionRequest> for crate::v1::LoadSessionRequest {
490    type Error = ProtocolConversionError;
491
492    fn try_from(value: super::ResumeSessionRequest) -> Result<Self> {
493        v2_resume_session_request_into_v1_load(value)
494    }
495}
496impl_try_from_v2_to_v1!(super::ResumeSessionResponse => crate::v1::ResumeSessionResponse);
497impl_try_from_v1_to_v2!(crate::v1::ResumeSessionResponse => super::ResumeSessionResponse);
498impl_try_from_v2_to_v1!(super::CloseSessionRequest => crate::v1::CloseSessionRequest);
499impl_try_from_v1_to_v2!(crate::v1::CloseSessionRequest => super::CloseSessionRequest);
500impl_try_from_v2_to_v1!(super::CloseSessionResponse => crate::v1::CloseSessionResponse);
501impl_try_from_v1_to_v2!(crate::v1::CloseSessionResponse => super::CloseSessionResponse);
502impl_try_from_v2_to_v1!(super::DeleteSessionRequest => crate::v1::DeleteSessionRequest);
503impl_try_from_v1_to_v2!(crate::v1::DeleteSessionRequest => super::DeleteSessionRequest);
504impl_try_from_v2_to_v1!(super::DeleteSessionResponse => crate::v1::DeleteSessionResponse);
505impl_try_from_v1_to_v2!(crate::v1::DeleteSessionResponse => super::DeleteSessionResponse);
506impl_try_from_v2_to_v1!(super::ListSessionsRequest => crate::v1::ListSessionsRequest);
507impl_try_from_v1_to_v2!(crate::v1::ListSessionsRequest => super::ListSessionsRequest);
508impl_try_from_v2_to_v1!(super::ListSessionsResponse => crate::v1::ListSessionsResponse);
509impl_try_from_v1_to_v2!(crate::v1::ListSessionsResponse => super::ListSessionsResponse);
510impl_try_from_v2_to_v1!(super::SessionInfo => crate::v1::SessionInfo);
511impl_try_from_v1_to_v2!(crate::v1::SessionInfo => super::SessionInfo);
512impl_from_tuple_newtype!(super::SessionConfigId => crate::v1::SessionConfigId);
513impl_from_tuple_newtype!(crate::v1::SessionConfigId => super::SessionConfigId);
514impl_from_tuple_newtype!(super::SessionConfigValueId => crate::v1::SessionConfigValueId);
515impl_from_tuple_newtype!(crate::v1::SessionConfigValueId => super::SessionConfigValueId);
516impl_from_tuple_newtype!(super::SessionConfigGroupId => crate::v1::SessionConfigGroupId);
517impl_from_tuple_newtype!(crate::v1::SessionConfigGroupId => super::SessionConfigGroupId);
518impl_try_from_v2_to_v1!(super::SessionConfigSelectOption => crate::v1::SessionConfigSelectOption);
519impl_try_from_v1_to_v2!(crate::v1::SessionConfigSelectOption => super::SessionConfigSelectOption);
520impl_try_from_v2_to_v1!(super::SessionConfigSelectGroup => crate::v1::SessionConfigSelectGroup);
521impl_try_from_v1_to_v2!(crate::v1::SessionConfigSelectGroup => super::SessionConfigSelectGroup);
522impl_try_from_v2_to_v1!(super::SessionConfigSelectOptions => crate::v1::SessionConfigSelectOptions);
523impl_try_from_v1_to_v2!(crate::v1::SessionConfigSelectOptions => super::SessionConfigSelectOptions);
524impl_try_from_v2_to_v1!(super::SessionConfigSelect => crate::v1::SessionConfigSelect);
525impl_try_from_v1_to_v2!(crate::v1::SessionConfigSelect => super::SessionConfigSelect);
526impl_try_from_v2_to_v1!(super::SessionConfigBoolean => crate::v1::SessionConfigBoolean);
527impl_try_from_v1_to_v2!(crate::v1::SessionConfigBoolean => super::SessionConfigBoolean);
528impl_try_from_v2_to_v1!(super::SessionConfigOptionCategory => crate::v1::SessionConfigOptionCategory);
529impl_try_from_v1_to_v2!(crate::v1::SessionConfigOptionCategory => super::SessionConfigOptionCategory);
530impl_try_from_v2_to_v1!(super::SessionConfigKind => crate::v1::SessionConfigKind);
531impl_try_from_v1_to_v2!(crate::v1::SessionConfigKind => super::SessionConfigKind);
532impl_try_from_v2_to_v1!(super::SessionConfigOption => crate::v1::SessionConfigOption);
533impl_try_from_v1_to_v2!(crate::v1::SessionConfigOption => super::SessionConfigOption);
534impl_try_from_v2_to_v1!(super::SessionConfigOptionValue => crate::v1::SessionConfigOptionValue);
535impl_try_from_v1_to_v2!(crate::v1::SessionConfigOptionValue => super::SessionConfigOptionValue);
536impl_try_from_v2_to_v1!(super::SetSessionConfigOptionRequest => crate::v1::SetSessionConfigOptionRequest);
537impl_try_from_v1_to_v2!(crate::v1::SetSessionConfigOptionRequest => super::SetSessionConfigOptionRequest);
538impl_try_from_v2_to_v1!(super::SetSessionConfigOptionResponse => crate::v1::SetSessionConfigOptionResponse);
539impl_try_from_v1_to_v2!(crate::v1::SetSessionConfigOptionResponse => super::SetSessionConfigOptionResponse);
540impl_try_from_v2_to_v1!(super::McpServer => crate::v1::McpServer);
541impl_try_from_v1_to_v2!(crate::v1::McpServer => super::McpServer);
542impl_try_from_v2_to_v1!(super::McpServerHttp => crate::v1::McpServerHttp);
543impl_try_from_v1_to_v2!(crate::v1::McpServerHttp => super::McpServerHttp);
544#[cfg(feature = "unstable_mcp_over_acp")]
545impl_from_tuple_newtype!(super::McpServerAcpId => crate::v1::McpServerAcpId);
546#[cfg(feature = "unstable_mcp_over_acp")]
547impl_from_tuple_newtype!(crate::v1::McpServerAcpId => super::McpServerAcpId);
548#[cfg(feature = "unstable_mcp_over_acp")]
549impl_from_tuple_newtype!(super::McpConnectionId => crate::v1::McpConnectionId);
550#[cfg(feature = "unstable_mcp_over_acp")]
551impl_from_tuple_newtype!(crate::v1::McpConnectionId => super::McpConnectionId);
552#[cfg(feature = "unstable_mcp_over_acp")]
553impl_try_from_v2_to_v1!(super::McpServerAcp => crate::v1::McpServerAcp);
554#[cfg(feature = "unstable_mcp_over_acp")]
555impl_try_from_v1_to_v2!(crate::v1::McpServerAcp => super::McpServerAcp);
556impl_try_from_v2_to_v1!(super::McpServerStdio => crate::v1::McpServerStdio);
557impl_try_from_v1_to_v2!(crate::v1::McpServerStdio => super::McpServerStdio);
558impl_try_from_v2_to_v1!(super::EnvVariable => crate::v1::EnvVariable);
559impl_try_from_v1_to_v2!(crate::v1::EnvVariable => super::EnvVariable);
560impl_try_from_v2_to_v1!(super::HttpHeader => crate::v1::HttpHeader);
561impl_try_from_v1_to_v2!(crate::v1::HttpHeader => super::HttpHeader);
562impl_try_from_v2_to_v1!(super::PromptRequest => crate::v1::PromptRequest);
563impl_try_from_v1_to_v2!(crate::v1::PromptRequest => super::PromptRequest);
564impl_try_from_v2_to_v1!(super::PromptResponse => crate::v1::PromptResponse);
565impl_try_from_v1_to_v2!(crate::v1::PromptResponse => super::PromptResponse);
566impl_try_from_v2_to_v1!(super::StopReason => crate::v1::StopReason);
567impl_from_enum!(crate::v1::StopReason => super::StopReason {
568    EndTurn,
569    MaxTokens,
570    MaxTurnRequests,
571    Refusal,
572    Cancelled,
573});
574#[cfg(feature = "unstable_end_turn_token_usage")]
575impl_try_from_v2_to_v1!(super::Usage => crate::v1::Usage);
576#[cfg(feature = "unstable_end_turn_token_usage")]
577impl_try_from_v1_to_v2!(crate::v1::Usage => super::Usage);
578#[cfg(feature = "unstable_llm_providers")]
579impl_try_from_v2_to_v1!(super::LlmProtocol => crate::v1::LlmProtocol);
580#[cfg(feature = "unstable_llm_providers")]
581impl_try_from_v1_to_v2!(crate::v1::LlmProtocol => super::LlmProtocol);
582#[cfg(feature = "unstable_llm_providers")]
583impl_try_from_v2_to_v1!(super::ProviderCurrentConfig => crate::v1::ProviderCurrentConfig);
584#[cfg(feature = "unstable_llm_providers")]
585impl_try_from_v1_to_v2!(crate::v1::ProviderCurrentConfig => super::ProviderCurrentConfig);
586#[cfg(feature = "unstable_llm_providers")]
587impl_from_tuple_newtype!(super::ProviderId => crate::v1::ProviderId);
588#[cfg(feature = "unstable_llm_providers")]
589impl_from_tuple_newtype!(crate::v1::ProviderId => super::ProviderId);
590#[cfg(feature = "unstable_llm_providers")]
591impl_try_from_v2_to_v1!(super::ProviderInfo => crate::v1::ProviderInfo);
592#[cfg(feature = "unstable_llm_providers")]
593impl_try_from_v1_to_v2!(crate::v1::ProviderInfo => super::ProviderInfo);
594#[cfg(feature = "unstable_llm_providers")]
595impl_try_from_v2_to_v1!(super::ListProvidersRequest => crate::v1::ListProvidersRequest);
596#[cfg(feature = "unstable_llm_providers")]
597impl_try_from_v1_to_v2!(crate::v1::ListProvidersRequest => super::ListProvidersRequest);
598#[cfg(feature = "unstable_llm_providers")]
599impl_try_from_v2_to_v1!(super::ListProvidersResponse => crate::v1::ListProvidersResponse);
600#[cfg(feature = "unstable_llm_providers")]
601impl_try_from_v1_to_v2!(crate::v1::ListProvidersResponse => super::ListProvidersResponse);
602#[cfg(feature = "unstable_llm_providers")]
603impl_try_from_v2_to_v1!(super::SetProviderRequest => crate::v1::SetProviderRequest);
604#[cfg(feature = "unstable_llm_providers")]
605impl_try_from_v1_to_v2!(crate::v1::SetProviderRequest => super::SetProviderRequest);
606#[cfg(feature = "unstable_llm_providers")]
607impl_try_from_v2_to_v1!(super::SetProviderResponse => crate::v1::SetProviderResponse);
608#[cfg(feature = "unstable_llm_providers")]
609impl_try_from_v1_to_v2!(crate::v1::SetProviderResponse => super::SetProviderResponse);
610#[cfg(feature = "unstable_llm_providers")]
611impl_try_from_v2_to_v1!(super::DisableProviderRequest => crate::v1::DisableProviderRequest);
612#[cfg(feature = "unstable_llm_providers")]
613impl_try_from_v1_to_v2!(crate::v1::DisableProviderRequest => super::DisableProviderRequest);
614#[cfg(feature = "unstable_llm_providers")]
615impl_try_from_v2_to_v1!(super::DisableProviderResponse => crate::v1::DisableProviderResponse);
616#[cfg(feature = "unstable_llm_providers")]
617impl_try_from_v1_to_v2!(crate::v1::DisableProviderResponse => super::DisableProviderResponse);
618impl_try_from_v2_to_v1!(super::AgentCapabilities => crate::v1::AgentCapabilities);
619impl_try_from_v1_to_v2!(crate::v1::AgentCapabilities => super::AgentCapabilities);
620#[cfg(feature = "unstable_llm_providers")]
621impl_try_from_v2_to_v1!(super::ProvidersCapabilities => crate::v1::ProvidersCapabilities);
622#[cfg(feature = "unstable_llm_providers")]
623impl_try_from_v1_to_v2!(crate::v1::ProvidersCapabilities => super::ProvidersCapabilities);
624impl_try_from_v2_to_v1!(super::SessionDeleteCapabilities => crate::v1::SessionDeleteCapabilities);
625impl_try_from_v1_to_v2!(crate::v1::SessionDeleteCapabilities => super::SessionDeleteCapabilities);
626impl_try_from_v2_to_v1!(super::SessionAdditionalDirectoriesCapabilities => crate::v1::SessionAdditionalDirectoriesCapabilities);
627impl_try_from_v1_to_v2!(crate::v1::SessionAdditionalDirectoriesCapabilities => super::SessionAdditionalDirectoriesCapabilities);
628#[cfg(feature = "unstable_session_fork")]
629impl_try_from_v2_to_v1!(super::SessionForkCapabilities => crate::v1::SessionForkCapabilities);
630#[cfg(feature = "unstable_session_fork")]
631impl_try_from_v1_to_v2!(crate::v1::SessionForkCapabilities => super::SessionForkCapabilities);
632impl_try_from_v2_to_v1!(super::PromptCapabilities => crate::v1::PromptCapabilities);
633impl_try_from_v1_to_v2!(crate::v1::PromptCapabilities => super::PromptCapabilities);
634impl_try_from_v2_to_v1!(super::McpCapabilities => crate::v1::McpCapabilities);
635impl_try_from_v1_to_v2!(crate::v1::McpCapabilities => super::McpCapabilities);
636impl_try_from_v2_to_v1!(super::CancelSessionNotification => crate::v1::CancelNotification);
637impl_try_from_v1_to_v2!(crate::v1::CancelNotification => super::CancelSessionNotification);
638#[cfg(feature = "unstable_nes")]
639impl_from_enum!(super::PositionEncodingKind => crate::v1::PositionEncodingKind {
640    Utf16,
641    Utf32,
642    Utf8,
643});
644#[cfg(feature = "unstable_nes")]
645impl_from_enum!(crate::v1::PositionEncodingKind => super::PositionEncodingKind {
646    Utf16,
647    Utf32,
648    Utf8,
649});
650#[cfg(feature = "unstable_nes")]
651impl_try_from_v2_to_v1!(super::Position => crate::v1::Position);
652#[cfg(feature = "unstable_nes")]
653impl_try_from_v1_to_v2!(crate::v1::Position => super::Position);
654#[cfg(feature = "unstable_nes")]
655impl_try_from_v2_to_v1!(super::Range => crate::v1::Range);
656#[cfg(feature = "unstable_nes")]
657impl_try_from_v1_to_v2!(crate::v1::Range => super::Range);
658#[cfg(feature = "unstable_nes")]
659impl_try_from_v2_to_v1!(super::NesCapabilities => crate::v1::NesCapabilities);
660#[cfg(feature = "unstable_nes")]
661impl_try_from_v1_to_v2!(crate::v1::NesCapabilities => super::NesCapabilities);
662#[cfg(feature = "unstable_nes")]
663impl_try_from_v2_to_v1!(super::NesEventCapabilities => crate::v1::NesEventCapabilities);
664#[cfg(feature = "unstable_nes")]
665impl_try_from_v1_to_v2!(crate::v1::NesEventCapabilities => super::NesEventCapabilities);
666#[cfg(feature = "unstable_nes")]
667impl_try_from_v2_to_v1!(super::NesDocumentEventCapabilities => crate::v1::NesDocumentEventCapabilities);
668#[cfg(feature = "unstable_nes")]
669impl_try_from_v1_to_v2!(crate::v1::NesDocumentEventCapabilities => super::NesDocumentEventCapabilities);
670#[cfg(feature = "unstable_nes")]
671impl_try_from_v2_to_v1!(super::NesDocumentDidOpenCapabilities => crate::v1::NesDocumentDidOpenCapabilities);
672#[cfg(feature = "unstable_nes")]
673impl_try_from_v1_to_v2!(crate::v1::NesDocumentDidOpenCapabilities => super::NesDocumentDidOpenCapabilities);
674#[cfg(feature = "unstable_nes")]
675impl_try_from_v2_to_v1!(super::NesDocumentDidChangeCapabilities => crate::v1::NesDocumentDidChangeCapabilities);
676#[cfg(feature = "unstable_nes")]
677impl_try_from_v1_to_v2!(crate::v1::NesDocumentDidChangeCapabilities => super::NesDocumentDidChangeCapabilities);
678#[cfg(feature = "unstable_nes")]
679impl_from_enum!(super::TextDocumentSyncKind => crate::v1::TextDocumentSyncKind {
680    Full,
681    Incremental,
682});
683#[cfg(feature = "unstable_nes")]
684impl_from_enum!(crate::v1::TextDocumentSyncKind => super::TextDocumentSyncKind {
685    Full,
686    Incremental,
687});
688#[cfg(feature = "unstable_nes")]
689impl_try_from_v2_to_v1!(super::NesDocumentDidCloseCapabilities => crate::v1::NesDocumentDidCloseCapabilities);
690#[cfg(feature = "unstable_nes")]
691impl_try_from_v1_to_v2!(crate::v1::NesDocumentDidCloseCapabilities => super::NesDocumentDidCloseCapabilities);
692#[cfg(feature = "unstable_nes")]
693impl_try_from_v2_to_v1!(super::NesDocumentDidSaveCapabilities => crate::v1::NesDocumentDidSaveCapabilities);
694#[cfg(feature = "unstable_nes")]
695impl_try_from_v1_to_v2!(crate::v1::NesDocumentDidSaveCapabilities => super::NesDocumentDidSaveCapabilities);
696#[cfg(feature = "unstable_nes")]
697impl_try_from_v2_to_v1!(super::NesDocumentDidFocusCapabilities => crate::v1::NesDocumentDidFocusCapabilities);
698#[cfg(feature = "unstable_nes")]
699impl_try_from_v1_to_v2!(crate::v1::NesDocumentDidFocusCapabilities => super::NesDocumentDidFocusCapabilities);
700#[cfg(feature = "unstable_nes")]
701impl_try_from_v2_to_v1!(super::NesContextCapabilities => crate::v1::NesContextCapabilities);
702#[cfg(feature = "unstable_nes")]
703impl_try_from_v1_to_v2!(crate::v1::NesContextCapabilities => super::NesContextCapabilities);
704#[cfg(feature = "unstable_nes")]
705impl_try_from_v2_to_v1!(super::NesRecentFilesCapabilities => crate::v1::NesRecentFilesCapabilities);
706#[cfg(feature = "unstable_nes")]
707impl_try_from_v1_to_v2!(crate::v1::NesRecentFilesCapabilities => super::NesRecentFilesCapabilities);
708#[cfg(feature = "unstable_nes")]
709impl_try_from_v2_to_v1!(super::NesRelatedSnippetsCapabilities => crate::v1::NesRelatedSnippetsCapabilities);
710#[cfg(feature = "unstable_nes")]
711impl_try_from_v1_to_v2!(crate::v1::NesRelatedSnippetsCapabilities => super::NesRelatedSnippetsCapabilities);
712#[cfg(feature = "unstable_nes")]
713impl_try_from_v2_to_v1!(super::NesEditHistoryCapabilities => crate::v1::NesEditHistoryCapabilities);
714#[cfg(feature = "unstable_nes")]
715impl_try_from_v1_to_v2!(crate::v1::NesEditHistoryCapabilities => super::NesEditHistoryCapabilities);
716#[cfg(feature = "unstable_nes")]
717impl_try_from_v2_to_v1!(super::NesUserActionsCapabilities => crate::v1::NesUserActionsCapabilities);
718#[cfg(feature = "unstable_nes")]
719impl_try_from_v1_to_v2!(crate::v1::NesUserActionsCapabilities => super::NesUserActionsCapabilities);
720#[cfg(feature = "unstable_nes")]
721impl_try_from_v2_to_v1!(super::NesOpenFilesCapabilities => crate::v1::NesOpenFilesCapabilities);
722#[cfg(feature = "unstable_nes")]
723impl_try_from_v1_to_v2!(crate::v1::NesOpenFilesCapabilities => super::NesOpenFilesCapabilities);
724#[cfg(feature = "unstable_nes")]
725impl_try_from_v2_to_v1!(super::NesDiagnosticsCapabilities => crate::v1::NesDiagnosticsCapabilities);
726#[cfg(feature = "unstable_nes")]
727impl_try_from_v1_to_v2!(crate::v1::NesDiagnosticsCapabilities => super::NesDiagnosticsCapabilities);
728#[cfg(feature = "unstable_nes")]
729impl_try_from_v2_to_v1!(super::ClientNesCapabilities => crate::v1::ClientNesCapabilities);
730#[cfg(feature = "unstable_nes")]
731impl_try_from_v1_to_v2!(crate::v1::ClientNesCapabilities => super::ClientNesCapabilities);
732#[cfg(feature = "unstable_nes")]
733impl_try_from_v2_to_v1!(super::NesJumpCapabilities => crate::v1::NesJumpCapabilities);
734#[cfg(feature = "unstable_nes")]
735impl_try_from_v1_to_v2!(crate::v1::NesJumpCapabilities => super::NesJumpCapabilities);
736#[cfg(feature = "unstable_nes")]
737impl_try_from_v2_to_v1!(super::NesRenameCapabilities => crate::v1::NesRenameCapabilities);
738#[cfg(feature = "unstable_nes")]
739impl_try_from_v1_to_v2!(crate::v1::NesRenameCapabilities => super::NesRenameCapabilities);
740#[cfg(feature = "unstable_nes")]
741impl_try_from_v2_to_v1!(super::NesSearchAndReplaceCapabilities => crate::v1::NesSearchAndReplaceCapabilities);
742#[cfg(feature = "unstable_nes")]
743impl_try_from_v1_to_v2!(crate::v1::NesSearchAndReplaceCapabilities => super::NesSearchAndReplaceCapabilities);
744#[cfg(feature = "unstable_nes")]
745impl_try_from_v2_to_v1!(super::DidOpenDocumentNotification => crate::v1::DidOpenDocumentNotification);
746#[cfg(feature = "unstable_nes")]
747impl_try_from_v1_to_v2!(crate::v1::DidOpenDocumentNotification => super::DidOpenDocumentNotification);
748#[cfg(feature = "unstable_nes")]
749impl_try_from_v2_to_v1!(super::DidChangeDocumentNotification => crate::v1::DidChangeDocumentNotification);
750#[cfg(feature = "unstable_nes")]
751impl_try_from_v1_to_v2!(crate::v1::DidChangeDocumentNotification => super::DidChangeDocumentNotification);
752#[cfg(feature = "unstable_nes")]
753impl_try_from_v2_to_v1!(super::TextDocumentContentChangeEvent => crate::v1::TextDocumentContentChangeEvent);
754#[cfg(feature = "unstable_nes")]
755impl_try_from_v1_to_v2!(crate::v1::TextDocumentContentChangeEvent => super::TextDocumentContentChangeEvent);
756#[cfg(feature = "unstable_nes")]
757impl_try_from_v2_to_v1!(super::DidCloseDocumentNotification => crate::v1::DidCloseDocumentNotification);
758#[cfg(feature = "unstable_nes")]
759impl_try_from_v1_to_v2!(crate::v1::DidCloseDocumentNotification => super::DidCloseDocumentNotification);
760#[cfg(feature = "unstable_nes")]
761impl_try_from_v2_to_v1!(super::DidSaveDocumentNotification => crate::v1::DidSaveDocumentNotification);
762#[cfg(feature = "unstable_nes")]
763impl_try_from_v1_to_v2!(crate::v1::DidSaveDocumentNotification => super::DidSaveDocumentNotification);
764#[cfg(feature = "unstable_nes")]
765impl_try_from_v2_to_v1!(super::DidFocusDocumentNotification => crate::v1::DidFocusDocumentNotification);
766#[cfg(feature = "unstable_nes")]
767impl_try_from_v1_to_v2!(crate::v1::DidFocusDocumentNotification => super::DidFocusDocumentNotification);
768#[cfg(feature = "unstable_nes")]
769impl_try_from_v2_to_v1!(super::StartNesRequest => crate::v1::StartNesRequest);
770#[cfg(feature = "unstable_nes")]
771impl_try_from_v1_to_v2!(crate::v1::StartNesRequest => super::StartNesRequest);
772#[cfg(feature = "unstable_nes")]
773impl_try_from_v2_to_v1!(super::WorkspaceFolder => crate::v1::WorkspaceFolder);
774#[cfg(feature = "unstable_nes")]
775impl_try_from_v1_to_v2!(crate::v1::WorkspaceFolder => super::WorkspaceFolder);
776#[cfg(feature = "unstable_nes")]
777impl_try_from_v2_to_v1!(super::NesRepository => crate::v1::NesRepository);
778#[cfg(feature = "unstable_nes")]
779impl_try_from_v1_to_v2!(crate::v1::NesRepository => super::NesRepository);
780#[cfg(feature = "unstable_nes")]
781impl_try_from_v2_to_v1!(super::StartNesResponse => crate::v1::StartNesResponse);
782#[cfg(feature = "unstable_nes")]
783impl_try_from_v1_to_v2!(crate::v1::StartNesResponse => super::StartNesResponse);
784#[cfg(feature = "unstable_nes")]
785impl_try_from_v2_to_v1!(super::CloseNesRequest => crate::v1::CloseNesRequest);
786#[cfg(feature = "unstable_nes")]
787impl_try_from_v1_to_v2!(crate::v1::CloseNesRequest => super::CloseNesRequest);
788#[cfg(feature = "unstable_nes")]
789impl_try_from_v2_to_v1!(super::CloseNesResponse => crate::v1::CloseNesResponse);
790#[cfg(feature = "unstable_nes")]
791impl_try_from_v1_to_v2!(crate::v1::CloseNesResponse => super::CloseNesResponse);
792#[cfg(feature = "unstable_nes")]
793impl_try_from_v2_to_v1!(super::NesTriggerKind => crate::v1::NesTriggerKind);
794#[cfg(feature = "unstable_nes")]
795impl_from_enum!(crate::v1::NesTriggerKind => super::NesTriggerKind {
796    Automatic,
797    Diagnostic,
798    Manual,
799});
800#[cfg(feature = "unstable_nes")]
801impl_try_from_v2_to_v1!(super::SuggestNesRequest => crate::v1::SuggestNesRequest);
802#[cfg(feature = "unstable_nes")]
803impl_try_from_v1_to_v2!(crate::v1::SuggestNesRequest => super::SuggestNesRequest);
804#[cfg(feature = "unstable_nes")]
805impl_try_from_v2_to_v1!(super::NesSuggestContext => crate::v1::NesSuggestContext);
806#[cfg(feature = "unstable_nes")]
807impl_try_from_v1_to_v2!(crate::v1::NesSuggestContext => super::NesSuggestContext);
808#[cfg(feature = "unstable_nes")]
809impl_try_from_v2_to_v1!(super::NesRecentFile => crate::v1::NesRecentFile);
810#[cfg(feature = "unstable_nes")]
811impl_try_from_v1_to_v2!(crate::v1::NesRecentFile => super::NesRecentFile);
812#[cfg(feature = "unstable_nes")]
813impl_try_from_v2_to_v1!(super::NesRelatedSnippet => crate::v1::NesRelatedSnippet);
814#[cfg(feature = "unstable_nes")]
815impl_try_from_v1_to_v2!(crate::v1::NesRelatedSnippet => super::NesRelatedSnippet);
816#[cfg(feature = "unstable_nes")]
817impl_try_from_v2_to_v1!(super::NesExcerpt => crate::v1::NesExcerpt);
818#[cfg(feature = "unstable_nes")]
819impl_try_from_v1_to_v2!(crate::v1::NesExcerpt => super::NesExcerpt);
820#[cfg(feature = "unstable_nes")]
821impl_try_from_v2_to_v1!(super::NesEditHistoryEntry => crate::v1::NesEditHistoryEntry);
822#[cfg(feature = "unstable_nes")]
823impl_try_from_v1_to_v2!(crate::v1::NesEditHistoryEntry => super::NesEditHistoryEntry);
824#[cfg(feature = "unstable_nes")]
825impl_try_from_v2_to_v1!(super::NesUserAction => crate::v1::NesUserAction);
826#[cfg(feature = "unstable_nes")]
827impl_try_from_v1_to_v2!(crate::v1::NesUserAction => super::NesUserAction);
828#[cfg(feature = "unstable_nes")]
829impl_try_from_v2_to_v1!(super::NesOpenFile => crate::v1::NesOpenFile);
830#[cfg(feature = "unstable_nes")]
831impl_try_from_v1_to_v2!(crate::v1::NesOpenFile => super::NesOpenFile);
832#[cfg(feature = "unstable_nes")]
833impl_try_from_v2_to_v1!(super::NesDiagnostic => crate::v1::NesDiagnostic);
834#[cfg(feature = "unstable_nes")]
835impl_try_from_v1_to_v2!(crate::v1::NesDiagnostic => super::NesDiagnostic);
836#[cfg(feature = "unstable_nes")]
837impl_try_from_v2_to_v1!(super::NesDiagnosticSeverity => crate::v1::NesDiagnosticSeverity);
838#[cfg(feature = "unstable_nes")]
839impl_from_enum!(crate::v1::NesDiagnosticSeverity => super::NesDiagnosticSeverity {
840    Error,
841    Warning,
842    Information,
843    Hint,
844});
845#[cfg(feature = "unstable_nes")]
846impl_try_from_v2_to_v1!(super::SuggestNesResponse => crate::v1::SuggestNesResponse);
847#[cfg(feature = "unstable_nes")]
848impl_try_from_v1_to_v2!(crate::v1::SuggestNesResponse => super::SuggestNesResponse);
849#[cfg(feature = "unstable_nes")]
850impl_try_from_v2_to_v1!(super::NesSuggestion => crate::v1::NesSuggestion);
851#[cfg(feature = "unstable_nes")]
852impl_try_from_v1_to_v2!(crate::v1::NesSuggestion => super::NesSuggestion);
853#[cfg(feature = "unstable_nes")]
854impl_from_tuple_newtype!(super::NesSuggestionId => crate::v1::NesSuggestionId);
855#[cfg(feature = "unstable_nes")]
856impl_from_tuple_newtype!(crate::v1::NesSuggestionId => super::NesSuggestionId);
857#[cfg(feature = "unstable_nes")]
858impl_try_from_v2_to_v1!(super::NesEditSuggestion => crate::v1::NesEditSuggestion);
859#[cfg(feature = "unstable_nes")]
860impl_try_from_v1_to_v2!(crate::v1::NesEditSuggestion => super::NesEditSuggestion);
861#[cfg(feature = "unstable_nes")]
862impl_try_from_v2_to_v1!(super::NesTextEdit => crate::v1::NesTextEdit);
863#[cfg(feature = "unstable_nes")]
864impl_try_from_v1_to_v2!(crate::v1::NesTextEdit => super::NesTextEdit);
865#[cfg(feature = "unstable_nes")]
866impl_try_from_v2_to_v1!(super::NesJumpSuggestion => crate::v1::NesJumpSuggestion);
867#[cfg(feature = "unstable_nes")]
868impl_try_from_v1_to_v2!(crate::v1::NesJumpSuggestion => super::NesJumpSuggestion);
869#[cfg(feature = "unstable_nes")]
870impl_try_from_v2_to_v1!(super::NesRenameSuggestion => crate::v1::NesRenameSuggestion);
871#[cfg(feature = "unstable_nes")]
872impl_try_from_v1_to_v2!(crate::v1::NesRenameSuggestion => super::NesRenameSuggestion);
873#[cfg(feature = "unstable_nes")]
874impl_try_from_v2_to_v1!(super::NesSearchAndReplaceSuggestion => crate::v1::NesSearchAndReplaceSuggestion);
875#[cfg(feature = "unstable_nes")]
876impl_try_from_v1_to_v2!(crate::v1::NesSearchAndReplaceSuggestion => super::NesSearchAndReplaceSuggestion);
877#[cfg(feature = "unstable_nes")]
878impl_try_from_v2_to_v1!(super::AcceptNesNotification => crate::v1::AcceptNesNotification);
879#[cfg(feature = "unstable_nes")]
880impl_try_from_v1_to_v2!(crate::v1::AcceptNesNotification => super::AcceptNesNotification);
881#[cfg(feature = "unstable_nes")]
882impl_try_from_v2_to_v1!(super::RejectNesNotification => crate::v1::RejectNesNotification);
883#[cfg(feature = "unstable_nes")]
884impl_try_from_v1_to_v2!(crate::v1::RejectNesNotification => super::RejectNesNotification);
885#[cfg(feature = "unstable_nes")]
886impl_try_from_v2_to_v1!(super::NesRejectReason => crate::v1::NesRejectReason);
887#[cfg(feature = "unstable_nes")]
888impl_from_enum!(crate::v1::NesRejectReason => super::NesRejectReason {
889    Rejected,
890    Ignored,
891    Replaced,
892    Cancelled,
893});
894#[cfg(feature = "unstable_elicitation")]
895impl_from_tuple_newtype!(super::ElicitationId => crate::v1::ElicitationId);
896#[cfg(feature = "unstable_elicitation")]
897impl_from_tuple_newtype!(crate::v1::ElicitationId => super::ElicitationId);
898#[cfg(feature = "unstable_elicitation")]
899impl_try_from_v2_to_v1!(super::StringFormat => crate::v1::StringFormat);
900#[cfg(feature = "unstable_elicitation")]
901impl_from_enum!(crate::v1::StringFormat => super::StringFormat {
902    Email,
903    Uri,
904    Date,
905    DateTime,
906});
907#[cfg(feature = "unstable_elicitation")]
908impl_from_enum!(super::ElicitationSchemaType => crate::v1::ElicitationSchemaType {
909    Object,
910});
911#[cfg(feature = "unstable_elicitation")]
912impl_from_enum!(crate::v1::ElicitationSchemaType => super::ElicitationSchemaType {
913    Object,
914});
915#[cfg(feature = "unstable_elicitation")]
916impl_try_from_v2_to_v1!(super::EnumOption => crate::v1::EnumOption);
917#[cfg(feature = "unstable_elicitation")]
918impl_try_from_v1_to_v2!(crate::v1::EnumOption => super::EnumOption);
919#[cfg(feature = "unstable_elicitation")]
920impl_try_from_v2_to_v1!(super::StringPropertySchema => crate::v1::StringPropertySchema);
921#[cfg(feature = "unstable_elicitation")]
922impl_try_from_v1_to_v2!(crate::v1::StringPropertySchema => super::StringPropertySchema);
923#[cfg(feature = "unstable_elicitation")]
924impl_try_from_v2_to_v1!(super::NumberPropertySchema => crate::v1::NumberPropertySchema);
925#[cfg(feature = "unstable_elicitation")]
926impl_try_from_v1_to_v2!(crate::v1::NumberPropertySchema => super::NumberPropertySchema);
927#[cfg(feature = "unstable_elicitation")]
928impl_try_from_v2_to_v1!(super::IntegerPropertySchema => crate::v1::IntegerPropertySchema);
929#[cfg(feature = "unstable_elicitation")]
930impl_try_from_v1_to_v2!(crate::v1::IntegerPropertySchema => super::IntegerPropertySchema);
931#[cfg(feature = "unstable_elicitation")]
932impl_try_from_v2_to_v1!(super::BooleanPropertySchema => crate::v1::BooleanPropertySchema);
933#[cfg(feature = "unstable_elicitation")]
934impl_try_from_v1_to_v2!(crate::v1::BooleanPropertySchema => super::BooleanPropertySchema);
935#[cfg(feature = "unstable_elicitation")]
936impl_try_from_v2_to_v1!(super::StringMultiSelectItems => crate::v1::StringMultiSelectItems);
937#[cfg(feature = "unstable_elicitation")]
938impl_try_from_v1_to_v2!(crate::v1::StringMultiSelectItems => super::StringMultiSelectItems);
939#[cfg(feature = "unstable_elicitation")]
940impl_try_from_v2_to_v1!(super::OtherMultiSelectItems => crate::v1::OtherMultiSelectItems);
941#[cfg(feature = "unstable_elicitation")]
942impl_try_from_v1_to_v2!(crate::v1::OtherMultiSelectItems => super::OtherMultiSelectItems);
943#[cfg(feature = "unstable_elicitation")]
944impl_try_from_v2_to_v1!(super::TitledMultiSelectItems => crate::v1::TitledMultiSelectItems);
945#[cfg(feature = "unstable_elicitation")]
946impl_try_from_v1_to_v2!(crate::v1::TitledMultiSelectItems => super::TitledMultiSelectItems);
947#[cfg(feature = "unstable_elicitation")]
948impl_try_from_v2_to_v1!(super::MultiSelectItems => crate::v1::MultiSelectItems);
949#[cfg(feature = "unstable_elicitation")]
950impl_try_from_v1_to_v2!(crate::v1::MultiSelectItems => super::MultiSelectItems);
951#[cfg(feature = "unstable_elicitation")]
952impl_try_from_v2_to_v1!(super::MultiSelectPropertySchema => crate::v1::MultiSelectPropertySchema);
953#[cfg(feature = "unstable_elicitation")]
954impl_try_from_v1_to_v2!(crate::v1::MultiSelectPropertySchema => super::MultiSelectPropertySchema);
955#[cfg(feature = "unstable_elicitation")]
956impl_try_from_v2_to_v1!(super::ElicitationPropertySchema => crate::v1::ElicitationPropertySchema);
957#[cfg(feature = "unstable_elicitation")]
958impl_try_from_v1_to_v2!(crate::v1::ElicitationPropertySchema => super::ElicitationPropertySchema);
959#[cfg(feature = "unstable_elicitation")]
960impl_try_from_v2_to_v1!(super::OtherElicitationPropertySchema => crate::v1::OtherElicitationPropertySchema);
961#[cfg(feature = "unstable_elicitation")]
962impl_try_from_v1_to_v2!(crate::v1::OtherElicitationPropertySchema => super::OtherElicitationPropertySchema);
963#[cfg(feature = "unstable_elicitation")]
964impl_try_from_v2_to_v1!(super::ElicitationSchema => crate::v1::ElicitationSchema);
965#[cfg(feature = "unstable_elicitation")]
966impl_try_from_v1_to_v2!(crate::v1::ElicitationSchema => super::ElicitationSchema);
967#[cfg(feature = "unstable_elicitation")]
968impl_try_from_v2_to_v1!(super::ElicitationCapabilities => crate::v1::ElicitationCapabilities);
969#[cfg(feature = "unstable_elicitation")]
970impl_try_from_v1_to_v2!(crate::v1::ElicitationCapabilities => super::ElicitationCapabilities);
971#[cfg(feature = "unstable_elicitation")]
972impl_try_from_v2_to_v1!(super::ElicitationFormCapabilities => crate::v1::ElicitationFormCapabilities);
973#[cfg(feature = "unstable_elicitation")]
974impl_try_from_v1_to_v2!(crate::v1::ElicitationFormCapabilities => super::ElicitationFormCapabilities);
975#[cfg(feature = "unstable_elicitation")]
976impl_try_from_v2_to_v1!(super::ElicitationUrlCapabilities => crate::v1::ElicitationUrlCapabilities);
977#[cfg(feature = "unstable_elicitation")]
978impl_try_from_v1_to_v2!(crate::v1::ElicitationUrlCapabilities => super::ElicitationUrlCapabilities);
979#[cfg(feature = "unstable_elicitation")]
980impl_try_from_v2_to_v1!(super::ElicitationScope => crate::v1::ElicitationScope);
981#[cfg(feature = "unstable_elicitation")]
982impl_try_from_v1_to_v2!(crate::v1::ElicitationScope => super::ElicitationScope);
983#[cfg(feature = "unstable_elicitation")]
984impl_try_from_v2_to_v1!(super::ElicitationSessionScope => crate::v1::ElicitationSessionScope);
985#[cfg(feature = "unstable_elicitation")]
986impl_try_from_v1_to_v2!(crate::v1::ElicitationSessionScope => super::ElicitationSessionScope);
987#[cfg(feature = "unstable_elicitation")]
988impl_try_from_v2_to_v1!(super::ElicitationRequestScope => crate::v1::ElicitationRequestScope);
989#[cfg(feature = "unstable_elicitation")]
990impl_try_from_v1_to_v2!(crate::v1::ElicitationRequestScope => super::ElicitationRequestScope);
991#[cfg(feature = "unstable_elicitation")]
992impl_try_from_v2_to_v1!(super::CreateElicitationRequest => crate::v1::CreateElicitationRequest);
993#[cfg(feature = "unstable_elicitation")]
994impl_try_from_v1_to_v2!(crate::v1::CreateElicitationRequest => super::CreateElicitationRequest);
995#[cfg(feature = "unstable_elicitation")]
996impl_try_from_v2_to_v1!(super::ElicitationMode => crate::v1::ElicitationMode);
997#[cfg(feature = "unstable_elicitation")]
998impl_try_from_v1_to_v2!(crate::v1::ElicitationMode => super::ElicitationMode);
999#[cfg(feature = "unstable_elicitation")]
1000impl_try_from_v2_to_v1!(super::OtherElicitationMode => crate::v1::OtherElicitationMode);
1001#[cfg(feature = "unstable_elicitation")]
1002impl_try_from_v1_to_v2!(crate::v1::OtherElicitationMode => super::OtherElicitationMode);
1003#[cfg(feature = "unstable_elicitation")]
1004impl_try_from_v2_to_v1!(super::ElicitationFormMode => crate::v1::ElicitationFormMode);
1005#[cfg(feature = "unstable_elicitation")]
1006impl_try_from_v1_to_v2!(crate::v1::ElicitationFormMode => super::ElicitationFormMode);
1007#[cfg(feature = "unstable_elicitation")]
1008impl_try_from_v2_to_v1!(super::ElicitationUrlMode => crate::v1::ElicitationUrlMode);
1009#[cfg(feature = "unstable_elicitation")]
1010impl_try_from_v1_to_v2!(crate::v1::ElicitationUrlMode => super::ElicitationUrlMode);
1011#[cfg(feature = "unstable_elicitation")]
1012impl_try_from_v2_to_v1!(super::CreateElicitationResponse => crate::v1::CreateElicitationResponse);
1013#[cfg(feature = "unstable_elicitation")]
1014impl_try_from_v1_to_v2!(crate::v1::CreateElicitationResponse => super::CreateElicitationResponse);
1015#[cfg(feature = "unstable_elicitation")]
1016impl_try_from_v2_to_v1!(super::ElicitationAction => crate::v1::ElicitationAction);
1017#[cfg(feature = "unstable_elicitation")]
1018impl_try_from_v1_to_v2!(crate::v1::ElicitationAction => super::ElicitationAction);
1019#[cfg(feature = "unstable_elicitation")]
1020impl_try_from_v2_to_v1!(super::OtherElicitationAction => crate::v1::OtherElicitationAction);
1021#[cfg(feature = "unstable_elicitation")]
1022impl_try_from_v1_to_v2!(crate::v1::OtherElicitationAction => super::OtherElicitationAction);
1023#[cfg(feature = "unstable_elicitation")]
1024impl_try_from_v2_to_v1!(super::ElicitationAcceptAction => crate::v1::ElicitationAcceptAction);
1025#[cfg(feature = "unstable_elicitation")]
1026impl_try_from_v1_to_v2!(crate::v1::ElicitationAcceptAction => super::ElicitationAcceptAction);
1027#[cfg(feature = "unstable_elicitation")]
1028impl_try_from_v2_to_v1!(super::ElicitationContentValue => crate::v1::ElicitationContentValue);
1029#[cfg(feature = "unstable_elicitation")]
1030impl_try_from_v1_to_v2!(crate::v1::ElicitationContentValue => super::ElicitationContentValue);
1031#[cfg(feature = "unstable_elicitation")]
1032impl_try_from_v2_to_v1!(super::CompleteElicitationNotification => crate::v1::CompleteElicitationNotification);
1033#[cfg(feature = "unstable_elicitation")]
1034impl_try_from_v1_to_v2!(crate::v1::CompleteElicitationNotification => super::CompleteElicitationNotification);
1035impl_try_from_v2_to_v1!(super::ContentBlock => crate::v1::ContentBlock);
1036impl_try_from_v1_to_v2!(crate::v1::ContentBlock => super::ContentBlock);
1037impl_try_from_v2_to_v1!(super::TextContent => crate::v1::TextContent);
1038impl_try_from_v1_to_v2!(crate::v1::TextContent => super::TextContent);
1039impl_try_from_v2_to_v1!(super::ImageContent => crate::v1::ImageContent);
1040impl_try_from_v1_to_v2!(crate::v1::ImageContent => super::ImageContent);
1041impl_try_from_v2_to_v1!(super::AudioContent => crate::v1::AudioContent);
1042impl_try_from_v1_to_v2!(crate::v1::AudioContent => super::AudioContent);
1043impl_try_from_v2_to_v1!(super::EmbeddedResource => crate::v1::EmbeddedResource);
1044impl_try_from_v1_to_v2!(crate::v1::EmbeddedResource => super::EmbeddedResource);
1045impl_try_from_v2_to_v1!(super::EmbeddedResourceResource => crate::v1::EmbeddedResourceResource);
1046impl_try_from_v1_to_v2!(crate::v1::EmbeddedResourceResource => super::EmbeddedResourceResource);
1047impl_try_from_v2_to_v1!(super::TextResourceContents => crate::v1::TextResourceContents);
1048impl_try_from_v1_to_v2!(crate::v1::TextResourceContents => super::TextResourceContents);
1049impl_try_from_v2_to_v1!(super::BlobResourceContents => crate::v1::BlobResourceContents);
1050impl_try_from_v1_to_v2!(crate::v1::BlobResourceContents => super::BlobResourceContents);
1051impl_try_from_v2_to_v1!(super::ResourceLink => crate::v1::ResourceLink);
1052impl_try_from_v1_to_v2!(crate::v1::ResourceLink => super::ResourceLink);
1053impl_try_from_v2_to_v1!(super::Annotations => crate::v1::Annotations);
1054impl_try_from_v1_to_v2!(crate::v1::Annotations => super::Annotations);
1055impl_try_from_v2_to_v1!(super::Role => crate::v1::Role);
1056impl_from_enum!(crate::v1::Role => super::Role {
1057    Assistant,
1058    User,
1059});
1060
1061macro_rules! identity_conversion {
1062    ($($ty:ty),* $(,)?) => {
1063        $(
1064            impl TryToV1 for $ty {
1065                type Output = Self;
1066
1067                fn try_to_v1(self) -> Result<Self::Output> {
1068                    Ok(self)
1069                }
1070            }
1071
1072            impl TryToV2 for $ty {
1073                type Output = Self;
1074
1075                fn try_to_v2(self) -> Result<Self::Output> {
1076                    Ok(self)
1077                }
1078            }
1079        )*
1080    };
1081}
1082
1083identity_conversion!(
1084    bool,
1085    f32,
1086    f64,
1087    i16,
1088    i32,
1089    i64,
1090    i8,
1091    isize,
1092    String,
1093    u16,
1094    u32,
1095    u64,
1096    u8,
1097    usize,
1098    &'static str,
1099    Arc<RawValue>,
1100    Arc<str>,
1101    PathBuf,
1102    ProtocolVersion,
1103    super::RequestId,
1104    serde_json::Map<String, serde_json::Value>,
1105    serde_json::Value,
1106);
1107
1108impl<T> TryToV1 for Option<T>
1109where
1110    T: TryToV1,
1111{
1112    type Output = Option<T::Output>;
1113    fn try_to_v1(self) -> Result<Self::Output> {
1114        self.map(TryToV1::try_to_v1).transpose()
1115    }
1116}
1117
1118impl<T> TryToV2 for Option<T>
1119where
1120    T: TryToV2,
1121{
1122    type Output = Option<T::Output>;
1123    fn try_to_v2(self) -> Result<Self::Output> {
1124        self.map(TryToV2::try_to_v2).transpose()
1125    }
1126}
1127
1128impl<T> TryToV1 for Vec<T>
1129where
1130    T: TryToV1,
1131{
1132    type Output = Vec<T::Output>;
1133    fn try_to_v1(self) -> Result<Self::Output> {
1134        self.into_iter().map(TryToV1::try_to_v1).collect()
1135    }
1136}
1137
1138fn option_vec_into_v2_default<T>(value: Option<Vec<T>>) -> Result<Vec<T::Output>>
1139where
1140    T: TryToV2,
1141{
1142    value.unwrap_or_default().try_to_v2()
1143}
1144
1145impl<T> TryToV2 for Vec<T>
1146where
1147    T: TryToV2,
1148{
1149    type Output = Vec<T::Output>;
1150    fn try_to_v2(self) -> Result<Self::Output> {
1151        self.into_iter().map(TryToV2::try_to_v2).collect()
1152    }
1153}
1154
1155impl<K, V> TryToV1 for BTreeMap<K, V>
1156where
1157    K: TryToV1,
1158    K::Output: Ord,
1159    V: TryToV1,
1160{
1161    type Output = BTreeMap<K::Output, V::Output>;
1162    fn try_to_v1(self) -> Result<Self::Output> {
1163        self.into_iter()
1164            .map(|(key, value)| Ok((key.try_to_v1()?, value.try_to_v1()?)))
1165            .collect()
1166    }
1167}
1168
1169impl<K, V> TryToV2 for BTreeMap<K, V>
1170where
1171    K: TryToV2,
1172    K::Output: Ord,
1173    V: TryToV2,
1174{
1175    type Output = BTreeMap<K::Output, V::Output>;
1176    fn try_to_v2(self) -> Result<Self::Output> {
1177        self.into_iter()
1178            .map(|(key, value)| Ok((key.try_to_v2()?, value.try_to_v2()?)))
1179            .collect()
1180    }
1181}
1182
1183impl<K, V, S> TryToV1 for HashMap<K, V, S>
1184where
1185    K: TryToV1,
1186    K::Output: Eq + Hash,
1187    V: TryToV1,
1188    S: BuildHasher,
1189{
1190    type Output = HashMap<K::Output, V::Output>;
1191    fn try_to_v1(self) -> Result<Self::Output> {
1192        self.into_iter()
1193            .map(|(key, value)| Ok((key.try_to_v1()?, value.try_to_v1()?)))
1194            .collect()
1195    }
1196}
1197
1198impl<K, V, S> TryToV2 for HashMap<K, V, S>
1199where
1200    K: TryToV2,
1201    K::Output: Eq + Hash,
1202    V: TryToV2,
1203    S: BuildHasher,
1204{
1205    type Output = HashMap<K::Output, V::Output>;
1206    fn try_to_v2(self) -> Result<Self::Output> {
1207        self.into_iter()
1208            .map(|(key, value)| Ok((key.try_to_v2()?, value.try_to_v2()?)))
1209            .collect()
1210    }
1211}
1212
1213impl<T> TryToV1 for crate::MaybeUndefined<T>
1214where
1215    T: TryToV1,
1216{
1217    type Output = crate::MaybeUndefined<T::Output>;
1218    fn try_to_v1(self) -> Result<Self::Output> {
1219        Ok(match self {
1220            Self::Undefined => crate::MaybeUndefined::Undefined,
1221            Self::Null => crate::MaybeUndefined::Null,
1222            Self::Value(value) => crate::MaybeUndefined::Value(value.try_to_v1()?),
1223        })
1224    }
1225}
1226
1227impl<T> TryToV2 for crate::MaybeUndefined<T>
1228where
1229    T: TryToV2,
1230{
1231    type Output = crate::MaybeUndefined<T::Output>;
1232    fn try_to_v2(self) -> Result<Self::Output> {
1233        Ok(match self {
1234            Self::Undefined => crate::MaybeUndefined::Undefined,
1235            Self::Null => crate::MaybeUndefined::Null,
1236            Self::Value(value) => crate::MaybeUndefined::Value(value.try_to_v2()?),
1237        })
1238    }
1239}
1240
1241impl TryToV1 for super::SessionId {
1242    type Output = crate::v1::SessionId;
1243
1244    fn try_to_v1(self) -> Result<Self::Output> {
1245        Ok(crate::v1::SessionId(self.0.try_to_v1()?))
1246    }
1247}
1248
1249impl TryToV2 for crate::v1::SessionId {
1250    type Output = super::SessionId;
1251
1252    fn try_to_v2(self) -> Result<Self::Output> {
1253        Ok(super::SessionId(self.0.try_to_v2()?))
1254    }
1255}
1256
1257impl TryToV1 for super::AbsolutePath {
1258    type Output = PathBuf;
1259
1260    fn try_to_v1(self) -> Result<Self::Output> {
1261        Ok(self.into_inner())
1262    }
1263}
1264
1265impl TryToV1 for super::SessionListCursor {
1266    type Output = String;
1267
1268    fn try_to_v1(self) -> Result<Self::Output> {
1269        Ok(self.0.to_string())
1270    }
1271}
1272
1273impl TryToV1 for super::MediaType {
1274    type Output = String;
1275
1276    fn try_to_v1(self) -> Result<Self::Output> {
1277        Ok(self.0.to_string())
1278    }
1279}
1280
1281impl TryToV1 for super::MessageId {
1282    type Output = crate::v1::MessageId;
1283
1284    fn try_to_v1(self) -> Result<Self::Output> {
1285        Ok(crate::v1::MessageId(self.0.try_to_v1()?))
1286    }
1287}
1288
1289impl TryToV2 for crate::v1::MessageId {
1290    type Output = super::MessageId;
1291
1292    fn try_to_v2(self) -> Result<Self::Output> {
1293        Ok(super::MessageId(self.0.try_to_v2()?))
1294    }
1295}
1296
1297#[cfg(not(feature = "unstable_plan_operations"))]
1298impl TryToV1 for super::PlanUpdate {
1299    type Output = crate::v1::Plan;
1300
1301    fn try_to_v1(self) -> Result<Self::Output> {
1302        let Self { plan, meta } = self;
1303        Ok(match plan {
1304            super::PlanUpdateContent::Items(items) => {
1305                let super::PlanItems {
1306                    plan_id,
1307                    entries,
1308                    meta: items_meta,
1309                } = items;
1310                if plan_id.0.as_ref() != LEGACY_V1_PLAN_ID {
1311                    return Err(unrepresentable_v2_field("PlanItems", "planId"));
1312                }
1313                let meta = match (meta, items_meta) {
1314                    (Some(update_meta), Some(items_meta)) if update_meta != items_meta => {
1315                        return Err(ProtocolConversionError::new(
1316                            "v2 PlanUpdate and PlanItems metadata cannot both be represented in v1 Plan",
1317                        ));
1318                    }
1319                    (Some(meta), _) | (_, Some(meta)) => Some(meta),
1320                    (None, None) => None,
1321                };
1322                crate::v1::Plan {
1323                    entries: entries.try_to_v1()?,
1324                    meta: meta.try_to_v1()?,
1325                }
1326            }
1327            super::PlanUpdateContent::Other(value) => {
1328                return Err(unknown_v2_enum_variant("PlanUpdateContent", &value.type_));
1329            }
1330        })
1331    }
1332}
1333
1334#[cfg(feature = "unstable_plan_operations")]
1335impl TryToV1 for super::PlanId {
1336    type Output = crate::v1::PlanId;
1337
1338    fn try_to_v1(self) -> Result<Self::Output> {
1339        Ok(crate::v1::PlanId(self.0.try_to_v1()?))
1340    }
1341}
1342
1343#[cfg(feature = "unstable_plan_operations")]
1344impl TryToV2 for crate::v1::PlanId {
1345    type Output = super::PlanId;
1346
1347    fn try_to_v2(self) -> Result<Self::Output> {
1348        Ok(super::PlanId(self.0.try_to_v2()?))
1349    }
1350}
1351
1352#[cfg(feature = "unstable_plan_operations")]
1353impl TryToV1 for super::PlanUpdate {
1354    type Output = crate::v1::PlanUpdate;
1355
1356    fn try_to_v1(self) -> Result<Self::Output> {
1357        let Self { plan, meta } = self;
1358        Ok(crate::v1::PlanUpdate {
1359            plan: plan.try_to_v1()?,
1360            meta: meta.try_to_v1()?,
1361        })
1362    }
1363}
1364
1365#[cfg(feature = "unstable_plan_operations")]
1366impl TryToV2 for crate::v1::PlanUpdate {
1367    type Output = super::PlanUpdate;
1368
1369    fn try_to_v2(self) -> Result<Self::Output> {
1370        let Self { plan, meta } = self;
1371        Ok(super::PlanUpdate {
1372            plan: plan.try_to_v2()?,
1373            meta: meta.try_to_v2()?,
1374        })
1375    }
1376}
1377
1378#[cfg(feature = "unstable_plan_operations")]
1379impl TryToV1 for super::PlanUpdateContent {
1380    type Output = crate::v1::PlanUpdateContent;
1381
1382    fn try_to_v1(self) -> Result<Self::Output> {
1383        Ok(match self {
1384            Self::Items(value) => crate::v1::PlanUpdateContent::Items(value.try_to_v1()?),
1385            Self::File(value) => crate::v1::PlanUpdateContent::File(value.try_to_v1()?),
1386            Self::Markdown(value) => crate::v1::PlanUpdateContent::Markdown(value.try_to_v1()?),
1387            Self::Other(value) => {
1388                return Err(unknown_v2_enum_variant("PlanUpdateContent", &value.type_));
1389            }
1390        })
1391    }
1392}
1393
1394#[cfg(feature = "unstable_plan_operations")]
1395impl TryToV2 for crate::v1::PlanUpdateContent {
1396    type Output = super::PlanUpdateContent;
1397
1398    fn try_to_v2(self) -> Result<Self::Output> {
1399        Ok(match self {
1400            Self::Items(value) => super::PlanUpdateContent::Items(value.try_to_v2()?),
1401            Self::File(value) => super::PlanUpdateContent::File(value.try_to_v2()?),
1402            Self::Markdown(value) => super::PlanUpdateContent::Markdown(value.try_to_v2()?),
1403        })
1404    }
1405}
1406
1407#[cfg(feature = "unstable_plan_operations")]
1408impl TryToV1 for super::PlanItems {
1409    type Output = crate::v1::PlanItems;
1410
1411    fn try_to_v1(self) -> Result<Self::Output> {
1412        let Self {
1413            plan_id,
1414            entries,
1415            meta,
1416        } = self;
1417        Ok(crate::v1::PlanItems {
1418            plan_id: plan_id.try_to_v1()?,
1419            entries: entries.try_to_v1()?,
1420            meta: meta.try_to_v1()?,
1421        })
1422    }
1423}
1424
1425#[cfg(feature = "unstable_plan_operations")]
1426impl TryToV2 for crate::v1::PlanItems {
1427    type Output = super::PlanItems;
1428
1429    fn try_to_v2(self) -> Result<Self::Output> {
1430        let Self {
1431            plan_id,
1432            entries,
1433            meta,
1434        } = self;
1435        Ok(super::PlanItems {
1436            plan_id: plan_id.try_to_v2()?,
1437            entries: entries.try_to_v2()?,
1438            meta: meta.try_to_v2()?,
1439        })
1440    }
1441}
1442
1443#[cfg(feature = "unstable_plan_operations")]
1444impl TryToV1 for super::PlanFile {
1445    type Output = crate::v1::PlanFile;
1446
1447    fn try_to_v1(self) -> Result<Self::Output> {
1448        let Self { plan_id, uri, meta } = self;
1449        Ok(crate::v1::PlanFile {
1450            plan_id: plan_id.try_to_v1()?,
1451            uri: uri.try_to_v1()?,
1452            meta: meta.try_to_v1()?,
1453        })
1454    }
1455}
1456
1457#[cfg(feature = "unstable_plan_operations")]
1458impl TryToV2 for crate::v1::PlanFile {
1459    type Output = super::PlanFile;
1460
1461    fn try_to_v2(self) -> Result<Self::Output> {
1462        let Self { plan_id, uri, meta } = self;
1463        Ok(super::PlanFile {
1464            plan_id: plan_id.try_to_v2()?,
1465            uri: uri.try_to_v2()?,
1466            meta: meta.try_to_v2()?,
1467        })
1468    }
1469}
1470
1471#[cfg(feature = "unstable_plan_operations")]
1472impl TryToV1 for super::PlanMarkdown {
1473    type Output = crate::v1::PlanMarkdown;
1474
1475    fn try_to_v1(self) -> Result<Self::Output> {
1476        let Self {
1477            plan_id,
1478            content,
1479            meta,
1480        } = self;
1481        Ok(crate::v1::PlanMarkdown {
1482            plan_id: plan_id.try_to_v1()?,
1483            content: content.try_to_v1()?,
1484            meta: meta.try_to_v1()?,
1485        })
1486    }
1487}
1488
1489#[cfg(feature = "unstable_plan_operations")]
1490impl TryToV2 for crate::v1::PlanMarkdown {
1491    type Output = super::PlanMarkdown;
1492
1493    fn try_to_v2(self) -> Result<Self::Output> {
1494        let Self {
1495            plan_id,
1496            content,
1497            meta,
1498        } = self;
1499        Ok(super::PlanMarkdown {
1500            plan_id: plan_id.try_to_v2()?,
1501            content: content.try_to_v2()?,
1502            meta: meta.try_to_v2()?,
1503        })
1504    }
1505}
1506
1507#[cfg(feature = "unstable_plan_operations")]
1508impl TryToV1 for super::PlanRemoved {
1509    type Output = crate::v1::PlanRemoved;
1510
1511    fn try_to_v1(self) -> Result<Self::Output> {
1512        let Self { plan_id, meta } = self;
1513        Ok(crate::v1::PlanRemoved {
1514            plan_id: plan_id.try_to_v1()?,
1515            meta: meta.try_to_v1()?,
1516        })
1517    }
1518}
1519
1520#[cfg(feature = "unstable_plan_operations")]
1521impl TryToV2 for crate::v1::PlanRemoved {
1522    type Output = super::PlanRemoved;
1523
1524    fn try_to_v2(self) -> Result<Self::Output> {
1525        let Self { plan_id, meta } = self;
1526        Ok(super::PlanRemoved {
1527            plan_id: plan_id.try_to_v2()?,
1528            meta: meta.try_to_v2()?,
1529        })
1530    }
1531}
1532
1533impl TryToV1 for super::PlanEntry {
1534    type Output = crate::v1::PlanEntry;
1535
1536    fn try_to_v1(self) -> Result<Self::Output> {
1537        let Self {
1538            content,
1539            priority,
1540            status,
1541            meta,
1542        } = self;
1543        Ok(crate::v1::PlanEntry {
1544            content: content.try_to_v1()?,
1545            priority: priority.try_to_v1()?,
1546            status: status.try_to_v1()?,
1547            meta: meta.try_to_v1()?,
1548        })
1549    }
1550}
1551
1552impl TryToV2 for crate::v1::PlanEntry {
1553    type Output = super::PlanEntry;
1554
1555    fn try_to_v2(self) -> Result<Self::Output> {
1556        let Self {
1557            content,
1558            priority,
1559            status,
1560            meta,
1561        } = self;
1562        Ok(super::PlanEntry {
1563            content: content.try_to_v2()?,
1564            priority: priority.try_to_v2()?,
1565            status: status.try_to_v2()?,
1566            meta: meta.try_to_v2()?,
1567        })
1568    }
1569}
1570
1571impl TryToV1 for super::PlanEntryPriority {
1572    type Output = crate::v1::PlanEntryPriority;
1573
1574    fn try_to_v1(self) -> Result<Self::Output> {
1575        Ok(match self {
1576            Self::High => crate::v1::PlanEntryPriority::High,
1577            Self::Medium => crate::v1::PlanEntryPriority::Medium,
1578            Self::Low => crate::v1::PlanEntryPriority::Low,
1579            Self::Other(value) => {
1580                return Err(unknown_v2_enum_variant("PlanEntryPriority", &value));
1581            }
1582        })
1583    }
1584}
1585
1586impl TryToV2 for crate::v1::PlanEntryPriority {
1587    type Output = super::PlanEntryPriority;
1588
1589    fn try_to_v2(self) -> Result<Self::Output> {
1590        Ok(match self {
1591            Self::High => super::PlanEntryPriority::High,
1592            Self::Medium => super::PlanEntryPriority::Medium,
1593            Self::Low => super::PlanEntryPriority::Low,
1594        })
1595    }
1596}
1597
1598impl TryToV1 for super::PlanEntryStatus {
1599    type Output = crate::v1::PlanEntryStatus;
1600
1601    fn try_to_v1(self) -> Result<Self::Output> {
1602        Ok(match self {
1603            Self::Pending => crate::v1::PlanEntryStatus::Pending,
1604            Self::InProgress => crate::v1::PlanEntryStatus::InProgress,
1605            Self::Completed => crate::v1::PlanEntryStatus::Completed,
1606            Self::Other(value) => return Err(unknown_v2_enum_variant("PlanEntryStatus", &value)),
1607        })
1608    }
1609}
1610
1611impl TryToV2 for crate::v1::PlanEntryStatus {
1612    type Output = super::PlanEntryStatus;
1613
1614    fn try_to_v2(self) -> Result<Self::Output> {
1615        Ok(match self {
1616            Self::Pending => super::PlanEntryStatus::Pending,
1617            Self::InProgress => super::PlanEntryStatus::InProgress,
1618            Self::Completed => super::PlanEntryStatus::Completed,
1619        })
1620    }
1621}
1622
1623impl TryToV1 for super::CancelRequestNotification {
1624    type Output = crate::v1::CancelRequestNotification;
1625
1626    fn try_to_v1(self) -> Result<Self::Output> {
1627        let Self { request_id, meta } = self;
1628        Ok(crate::v1::CancelRequestNotification {
1629            request_id: request_id.try_to_v1()?,
1630            meta: meta.try_to_v1()?,
1631        })
1632    }
1633}
1634
1635impl TryToV2 for crate::v1::CancelRequestNotification {
1636    type Output = super::CancelRequestNotification;
1637
1638    fn try_to_v2(self) -> Result<Self::Output> {
1639        let Self { request_id, meta } = self;
1640        Ok(super::CancelRequestNotification {
1641            request_id: request_id.try_to_v2()?,
1642            meta: meta.try_to_v2()?,
1643        })
1644    }
1645}
1646
1647impl TryToV1 for super::ProtocolLevelNotification {
1648    type Output = crate::v1::ProtocolLevelNotification;
1649
1650    fn try_to_v1(self) -> Result<Self::Output> {
1651        Ok(match self {
1652            Self::CancelRequestNotification(value) => {
1653                crate::v1::ProtocolLevelNotification::CancelRequestNotification(value.try_to_v1()?)
1654            }
1655        })
1656    }
1657}
1658
1659impl TryToV2 for crate::v1::ProtocolLevelNotification {
1660    type Output = super::ProtocolLevelNotification;
1661
1662    fn try_to_v2(self) -> Result<Self::Output> {
1663        Ok(match self {
1664            Self::CancelRequestNotification(value) => {
1665                super::ProtocolLevelNotification::CancelRequestNotification(value.try_to_v2()?)
1666            }
1667        })
1668    }
1669}
1670
1671impl TryFrom<super::UpdateSessionNotification> for Vec<crate::v1::SessionNotification> {
1672    type Error = ProtocolConversionError;
1673
1674    fn try_from(value: super::UpdateSessionNotification) -> Result<Self> {
1675        let super::UpdateSessionNotification {
1676            session_id,
1677            update,
1678            meta,
1679        } = value;
1680        let session_id = session_id.try_to_v1()?;
1681        let meta = meta.try_to_v1()?;
1682        Vec::<crate::v1::SessionUpdate>::try_from(update)?
1683            .into_iter()
1684            .map(|update| {
1685                Ok(crate::v1::SessionNotification {
1686                    session_id: session_id.clone(),
1687                    update,
1688                    meta: meta.clone(),
1689                })
1690            })
1691            .collect()
1692    }
1693}
1694
1695impl TryToV2 for crate::v1::SessionNotification {
1696    type Output = super::UpdateSessionNotification;
1697
1698    fn try_to_v2(self) -> Result<Self::Output> {
1699        let Self {
1700            session_id,
1701            update,
1702            meta,
1703        } = self;
1704        Ok(super::UpdateSessionNotification {
1705            session_id: session_id.try_to_v2()?,
1706            update: update.try_to_v2()?,
1707            meta: meta.try_to_v2()?,
1708        })
1709    }
1710}
1711
1712impl TryFrom<super::SessionUpdate> for Vec<crate::v1::SessionUpdate> {
1713    type Error = ProtocolConversionError;
1714
1715    fn try_from(value: super::SessionUpdate) -> Result<Self> {
1716        Ok(match value {
1717            super::SessionUpdate::UserMessageChunk(value) => {
1718                vec![crate::v1::SessionUpdate::UserMessageChunk(
1719                    value.try_to_v1()?,
1720                )]
1721            }
1722            super::SessionUpdate::UserMessage(value) => v2_message_update_into_v1_chunks(
1723                "user_message",
1724                value.message_id,
1725                value.content,
1726                value.meta,
1727                crate::v1::SessionUpdate::UserMessageChunk,
1728            )?,
1729            super::SessionUpdate::AgentMessageChunk(value) => {
1730                vec![crate::v1::SessionUpdate::AgentMessageChunk(
1731                    value.try_to_v1()?,
1732                )]
1733            }
1734            super::SessionUpdate::AgentMessage(value) => v2_message_update_into_v1_chunks(
1735                "agent_message",
1736                value.message_id,
1737                value.content,
1738                value.meta,
1739                crate::v1::SessionUpdate::AgentMessageChunk,
1740            )?,
1741            super::SessionUpdate::AgentThoughtChunk(value) => {
1742                vec![crate::v1::SessionUpdate::AgentThoughtChunk(
1743                    value.try_to_v1()?,
1744                )]
1745            }
1746            super::SessionUpdate::AgentThought(value) => v2_message_update_into_v1_chunks(
1747                "agent_thought",
1748                value.message_id,
1749                value.content,
1750                value.meta,
1751                crate::v1::SessionUpdate::AgentThoughtChunk,
1752            )?,
1753            super::SessionUpdate::StateUpdate(_) => {
1754                return Err(ProtocolConversionError::new(
1755                    "v2 SessionUpdate variant `state_update` cannot be represented in v1 because v1 reports completion in the session/prompt response",
1756                ));
1757            }
1758            super::SessionUpdate::ToolCallContentChunk(_) => {
1759                return Err(ProtocolConversionError::new(
1760                    "v2 SessionUpdate variant `tool_call_content_chunk` cannot be represented in v1 because v1 tool-call content updates replace content instead of appending",
1761                ));
1762            }
1763            super::SessionUpdate::ToolCallUpdate(value) => {
1764                vec![crate::v1::SessionUpdate::ToolCallUpdate(value.try_to_v1()?)]
1765            }
1766            super::SessionUpdate::TerminalUpdate(_) => {
1767                return Err(ProtocolConversionError::new(
1768                    "v2 SessionUpdate variant `terminal_update` cannot be represented in v1",
1769                ));
1770            }
1771            super::SessionUpdate::TerminalOutputChunk(_) => {
1772                return Err(ProtocolConversionError::new(
1773                    "v2 SessionUpdate variant `terminal_output_chunk` cannot be represented in v1",
1774                ));
1775            }
1776            #[cfg(feature = "unstable_plan_operations")]
1777            super::SessionUpdate::PlanUpdate(value) => {
1778                vec![crate::v1::SessionUpdate::PlanUpdate(value.try_to_v1()?)]
1779            }
1780            #[cfg(not(feature = "unstable_plan_operations"))]
1781            super::SessionUpdate::PlanUpdate(value) => {
1782                vec![crate::v1::SessionUpdate::Plan(value.try_to_v1()?)]
1783            }
1784            #[cfg(feature = "unstable_plan_operations")]
1785            super::SessionUpdate::PlanRemoved(value) => {
1786                vec![crate::v1::SessionUpdate::PlanRemoved(value.try_to_v1()?)]
1787            }
1788            super::SessionUpdate::AvailableCommandsUpdate(value) => {
1789                vec![crate::v1::SessionUpdate::AvailableCommandsUpdate(
1790                    value.try_to_v1()?,
1791                )]
1792            }
1793            super::SessionUpdate::ConfigOptionUpdate(value) => {
1794                vec![crate::v1::SessionUpdate::ConfigOptionUpdate(
1795                    value.try_to_v1()?,
1796                )]
1797            }
1798            super::SessionUpdate::SessionInfoUpdate(value) => {
1799                vec![crate::v1::SessionUpdate::SessionInfoUpdate(
1800                    value.try_to_v1()?,
1801                )]
1802            }
1803            super::SessionUpdate::UsageUpdate(value) => {
1804                vec![crate::v1::SessionUpdate::UsageUpdate(value.try_to_v1()?)]
1805            }
1806            super::SessionUpdate::Other(value) => {
1807                return Err(unknown_v2_enum_variant(
1808                    "SessionUpdate",
1809                    &value.session_update,
1810                ));
1811            }
1812        })
1813    }
1814}
1815
1816fn v2_message_update_into_v1_chunks(
1817    variant: &str,
1818    message_id: super::MessageId,
1819    content: crate::MaybeUndefined<Vec<super::ContentBlock>>,
1820    meta: crate::MaybeUndefined<super::Meta>,
1821    wrap: impl Fn(crate::v1::ContentChunk) -> crate::v1::SessionUpdate,
1822) -> Result<Vec<crate::v1::SessionUpdate>> {
1823    let content = match content {
1824        crate::MaybeUndefined::Value(content) if !content.is_empty() => content,
1825        crate::MaybeUndefined::Value(_) => {
1826            return Err(ProtocolConversionError::new(format!(
1827                "v2 SessionUpdate variant `{variant}` with empty content cannot be represented in v1 chunks"
1828            )));
1829        }
1830        crate::MaybeUndefined::Null => {
1831            return Err(ProtocolConversionError::new(format!(
1832                "v2 SessionUpdate variant `{variant}` with null content cannot be represented in v1 chunks"
1833            )));
1834        }
1835        crate::MaybeUndefined::Undefined => {
1836            return Err(ProtocolConversionError::new(format!(
1837                "v2 SessionUpdate variant `{variant}` without content cannot be represented in v1 chunks"
1838            )));
1839        }
1840    };
1841    let message_id = message_id.try_to_v1()?;
1842    let meta = match meta {
1843        crate::MaybeUndefined::Value(meta) => Some(meta.try_to_v1()?),
1844        crate::MaybeUndefined::Null => {
1845            return Err(ProtocolConversionError::new(format!(
1846                "v2 SessionUpdate variant `{variant}` with null _meta cannot be represented in v1 chunks"
1847            )));
1848        }
1849        crate::MaybeUndefined::Undefined => None,
1850    };
1851
1852    content
1853        .into_iter()
1854        .map(|content| {
1855            Ok(wrap(crate::v1::ContentChunk {
1856                content: content.try_to_v1()?,
1857                message_id: Some(message_id.clone()),
1858                meta: meta.clone(),
1859            }))
1860        })
1861        .collect()
1862}
1863
1864impl TryToV2 for crate::v1::SessionUpdate {
1865    type Output = super::SessionUpdate;
1866
1867    fn try_to_v2(self) -> Result<Self::Output> {
1868        Ok(match self {
1869            Self::UserMessageChunk(value) => {
1870                super::SessionUpdate::UserMessageChunk(value.try_to_v2()?)
1871            }
1872            Self::AgentMessageChunk(value) => {
1873                super::SessionUpdate::AgentMessageChunk(value.try_to_v2()?)
1874            }
1875            Self::AgentThoughtChunk(value) => {
1876                super::SessionUpdate::AgentThoughtChunk(value.try_to_v2()?)
1877            }
1878            Self::ToolCall(value) => super::SessionUpdate::ToolCallUpdate(value.try_to_v2()?),
1879            Self::ToolCallUpdate(value) => super::SessionUpdate::ToolCallUpdate(value.try_to_v2()?),
1880            Self::Plan(value) => {
1881                let crate::v1::Plan { entries, meta } = value;
1882                super::SessionUpdate::PlanUpdate(super::PlanUpdate {
1883                    plan: super::PlanUpdateContent::items(LEGACY_V1_PLAN_ID, entries.try_to_v2()?),
1884                    meta: meta.try_to_v2()?,
1885                })
1886            }
1887            #[cfg(feature = "unstable_plan_operations")]
1888            Self::PlanUpdate(value) => super::SessionUpdate::PlanUpdate(value.try_to_v2()?),
1889            #[cfg(feature = "unstable_plan_operations")]
1890            Self::PlanRemoved(value) => super::SessionUpdate::PlanRemoved(value.try_to_v2()?),
1891            Self::AvailableCommandsUpdate(value) => {
1892                super::SessionUpdate::AvailableCommandsUpdate(value.try_to_v2()?)
1893            }
1894            Self::CurrentModeUpdate(_) => {
1895                return Err(removed_v1_enum_variant(
1896                    "SessionUpdate",
1897                    "current_mode_update",
1898                ));
1899            }
1900            Self::ConfigOptionUpdate(value) => {
1901                super::SessionUpdate::ConfigOptionUpdate(value.try_to_v2()?)
1902            }
1903            Self::SessionInfoUpdate(value) => {
1904                super::SessionUpdate::SessionInfoUpdate(value.try_to_v2()?)
1905            }
1906            Self::UsageUpdate(value) => super::SessionUpdate::UsageUpdate(value.try_to_v2()?),
1907        })
1908    }
1909}
1910
1911impl TryToV1 for super::ConfigOptionUpdate {
1912    type Output = crate::v1::ConfigOptionUpdate;
1913
1914    fn try_to_v1(self) -> Result<Self::Output> {
1915        let Self {
1916            config_options,
1917            meta,
1918        } = self;
1919        Ok(crate::v1::ConfigOptionUpdate {
1920            config_options: config_options.try_to_v1()?,
1921            meta: meta.try_to_v1()?,
1922        })
1923    }
1924}
1925
1926impl TryToV2 for crate::v1::ConfigOptionUpdate {
1927    type Output = super::ConfigOptionUpdate;
1928
1929    fn try_to_v2(self) -> Result<Self::Output> {
1930        let Self {
1931            config_options,
1932            meta,
1933        } = self;
1934        Ok(super::ConfigOptionUpdate {
1935            config_options: config_options.try_to_v2()?,
1936            meta: meta.try_to_v2()?,
1937        })
1938    }
1939}
1940
1941impl TryToV1 for super::SessionInfoUpdate {
1942    type Output = crate::v1::SessionInfoUpdate;
1943
1944    fn try_to_v1(self) -> Result<Self::Output> {
1945        let Self {
1946            title,
1947            updated_at,
1948            meta,
1949        } = self;
1950        Ok(crate::v1::SessionInfoUpdate {
1951            title: title.try_to_v1()?,
1952            updated_at: updated_at.try_to_v1()?,
1953            meta: maybe_undefined_meta_into_v1_option("SessionInfoUpdate", meta)?,
1954        })
1955    }
1956}
1957
1958impl TryToV2 for crate::v1::SessionInfoUpdate {
1959    type Output = super::SessionInfoUpdate;
1960
1961    fn try_to_v2(self) -> Result<Self::Output> {
1962        let Self {
1963            title,
1964            updated_at,
1965            meta,
1966        } = self;
1967        Ok(super::SessionInfoUpdate {
1968            title: title.try_to_v2()?,
1969            updated_at: updated_at.try_to_v2()?,
1970            meta: option_into_v2_maybe_undefined(meta)?,
1971        })
1972    }
1973}
1974
1975impl TryToV1 for super::UsageUpdate {
1976    type Output = crate::v1::UsageUpdate;
1977
1978    fn try_to_v1(self) -> Result<Self::Output> {
1979        let Self {
1980            used,
1981            size,
1982            cost,
1983            meta,
1984        } = self;
1985        Ok(crate::v1::UsageUpdate {
1986            used: used.try_to_v1()?,
1987            size: size.try_to_v1()?,
1988            cost: cost.try_to_v1()?,
1989            meta: meta.try_to_v1()?,
1990        })
1991    }
1992}
1993
1994impl TryToV2 for crate::v1::UsageUpdate {
1995    type Output = super::UsageUpdate;
1996
1997    fn try_to_v2(self) -> Result<Self::Output> {
1998        let Self {
1999            used,
2000            size,
2001            cost,
2002            meta,
2003        } = self;
2004        Ok(super::UsageUpdate {
2005            used: used.try_to_v2()?,
2006            size: size.try_to_v2()?,
2007            cost: cost.try_to_v2()?,
2008            meta: meta.try_to_v2()?,
2009        })
2010    }
2011}
2012
2013impl TryToV1 for super::Cost {
2014    type Output = crate::v1::Cost;
2015
2016    fn try_to_v1(self) -> Result<Self::Output> {
2017        let Self {
2018            amount,
2019            currency,
2020            meta,
2021        } = self;
2022        Ok(crate::v1::Cost {
2023            amount: amount.try_to_v1()?,
2024            currency: currency.try_to_v1()?,
2025            meta: meta.try_to_v1()?,
2026        })
2027    }
2028}
2029
2030impl TryToV2 for crate::v1::Cost {
2031    type Output = super::Cost;
2032
2033    fn try_to_v2(self) -> Result<Self::Output> {
2034        let Self {
2035            amount,
2036            currency,
2037            meta,
2038        } = self;
2039        Ok(super::Cost {
2040            amount: amount.try_to_v2()?,
2041            currency: currency.try_to_v2()?,
2042            meta: meta.try_to_v2()?,
2043        })
2044    }
2045}
2046
2047impl TryToV1 for super::ContentChunk {
2048    type Output = crate::v1::ContentChunk;
2049
2050    fn try_to_v1(self) -> Result<Self::Output> {
2051        let Self {
2052            content,
2053            message_id,
2054            meta,
2055        } = self;
2056        Ok(crate::v1::ContentChunk {
2057            content: content.try_to_v1()?,
2058            message_id: Some(message_id.try_to_v1()?),
2059            meta: meta.try_to_v1()?,
2060        })
2061    }
2062}
2063
2064impl TryToV2 for crate::v1::ContentChunk {
2065    type Output = super::ContentChunk;
2066
2067    fn try_to_v2(self) -> Result<Self::Output> {
2068        let Self {
2069            content,
2070            message_id,
2071            meta,
2072        } = self;
2073        Ok(super::ContentChunk {
2074            content: content.try_to_v2()?,
2075            message_id: message_id
2076                .ok_or_else(|| {
2077                    ProtocolConversionError::new(
2078                        "v1 ContentChunk without messageId cannot be represented in v2",
2079                    )
2080                })?
2081                .try_to_v2()?,
2082            meta: meta.try_to_v2()?,
2083        })
2084    }
2085}
2086
2087impl TryToV1 for super::AvailableCommandsUpdate {
2088    type Output = crate::v1::AvailableCommandsUpdate;
2089
2090    fn try_to_v1(self) -> Result<Self::Output> {
2091        let Self {
2092            available_commands,
2093            meta,
2094        } = self;
2095        Ok(crate::v1::AvailableCommandsUpdate {
2096            available_commands: available_commands.try_to_v1()?,
2097            meta: meta.try_to_v1()?,
2098        })
2099    }
2100}
2101
2102impl TryToV2 for crate::v1::AvailableCommandsUpdate {
2103    type Output = super::AvailableCommandsUpdate;
2104
2105    fn try_to_v2(self) -> Result<Self::Output> {
2106        let Self {
2107            available_commands,
2108            meta,
2109        } = self;
2110        Ok(super::AvailableCommandsUpdate {
2111            available_commands: available_commands.try_to_v2()?,
2112            meta: meta.try_to_v2()?,
2113        })
2114    }
2115}
2116
2117impl TryToV1 for super::AvailableCommand {
2118    type Output = crate::v1::AvailableCommand;
2119
2120    fn try_to_v1(self) -> Result<Self::Output> {
2121        let Self {
2122            name,
2123            description,
2124            input,
2125            meta,
2126        } = self;
2127        Ok(crate::v1::AvailableCommand {
2128            name: name.try_to_v1()?,
2129            description: description.try_to_v1()?,
2130            input: input.try_to_v1()?,
2131            meta: meta.try_to_v1()?,
2132        })
2133    }
2134}
2135
2136impl TryToV2 for crate::v1::AvailableCommand {
2137    type Output = super::AvailableCommand;
2138
2139    fn try_to_v2(self) -> Result<Self::Output> {
2140        let Self {
2141            name,
2142            description,
2143            input,
2144            meta,
2145        } = self;
2146        Ok(super::AvailableCommand {
2147            name: name.try_to_v2()?,
2148            description: description.try_to_v2()?,
2149            input: input.try_to_v2()?,
2150            meta: meta.try_to_v2()?,
2151        })
2152    }
2153}
2154
2155impl TryToV1 for super::AvailableCommandInput {
2156    type Output = crate::v1::AvailableCommandInput;
2157
2158    fn try_to_v1(self) -> Result<Self::Output> {
2159        Ok(match self {
2160            Self::Text(value) => crate::v1::AvailableCommandInput::Unstructured(value.try_to_v1()?),
2161            Self::Other(value) => {
2162                return Err(unknown_v2_enum_variant(
2163                    "AvailableCommandInput",
2164                    &value.type_,
2165                ));
2166            }
2167        })
2168    }
2169}
2170
2171impl TryToV2 for crate::v1::AvailableCommandInput {
2172    type Output = super::AvailableCommandInput;
2173
2174    fn try_to_v2(self) -> Result<Self::Output> {
2175        Ok(match self {
2176            Self::Unstructured(value) => super::AvailableCommandInput::Text(value.try_to_v2()?),
2177        })
2178    }
2179}
2180
2181impl TryToV1 for super::TextCommandInput {
2182    type Output = crate::v1::UnstructuredCommandInput;
2183
2184    fn try_to_v1(self) -> Result<Self::Output> {
2185        let Self { hint, meta } = self;
2186        Ok(crate::v1::UnstructuredCommandInput {
2187            hint: hint.try_to_v1()?,
2188            meta: meta.try_to_v1()?,
2189        })
2190    }
2191}
2192
2193impl TryToV2 for crate::v1::UnstructuredCommandInput {
2194    type Output = super::TextCommandInput;
2195
2196    fn try_to_v2(self) -> Result<Self::Output> {
2197        let Self { hint, meta } = self;
2198        Ok(super::TextCommandInput {
2199            hint: hint.try_to_v2()?,
2200            meta: meta.try_to_v2()?,
2201        })
2202    }
2203}
2204
2205impl TryToV1 for super::RequestPermissionRequest {
2206    type Output = crate::v1::RequestPermissionRequest;
2207
2208    fn try_to_v1(self) -> Result<Self::Output> {
2209        let Self {
2210            session_id,
2211            title,
2212            description,
2213            subject,
2214            options,
2215            meta,
2216        } = self;
2217        if description.is_some() {
2218            return Err(unrepresentable_v2_field(
2219                "RequestPermissionRequest",
2220                "description",
2221            ));
2222        }
2223        let Some(subject) = subject else {
2224            return Err(ProtocolConversionError::new(
2225                "v2 RequestPermissionRequest without `subject` cannot be represented in v1",
2226            ));
2227        };
2228        let tool_call = match subject {
2229            super::RequestPermissionSubject::ToolCall(subject) => {
2230                let super::ToolCallPermissionSubject { tool_call } = *subject;
2231                tool_call
2232            }
2233            super::RequestPermissionSubject::Command(_) => {
2234                return Err(ProtocolConversionError::new(
2235                    "v2 RequestPermissionSubject variant `command` cannot be represented in v1",
2236                ));
2237            }
2238            super::RequestPermissionSubject::Other(subject) => {
2239                return Err(unknown_v2_enum_variant(
2240                    "RequestPermissionSubject",
2241                    &subject.type_,
2242                ));
2243            }
2244        };
2245        if tool_call.title.value().map(String::as_str) != Some(title.as_str()) {
2246            return Err(ProtocolConversionError::new(
2247                "v2 RequestPermissionRequest.title cannot be represented in v1 unless it matches the tool-call title",
2248            ));
2249        }
2250        Ok(crate::v1::RequestPermissionRequest {
2251            session_id: session_id.try_to_v1()?,
2252            tool_call: tool_call.try_to_v1()?,
2253            options: options.try_to_v1()?,
2254            meta: meta.try_to_v1()?,
2255        })
2256    }
2257}
2258
2259impl TryToV2 for crate::v1::RequestPermissionRequest {
2260    type Output = super::RequestPermissionRequest;
2261
2262    fn try_to_v2(self) -> Result<Self::Output> {
2263        let Self {
2264            session_id,
2265            tool_call,
2266            options,
2267            meta,
2268        } = self;
2269        let Some(title) = tool_call
2270            .fields
2271            .title
2272            .clone()
2273            .filter(|title| !title.is_empty())
2274        else {
2275            return Err(ProtocolConversionError::new(
2276                "v1 RequestPermissionRequest without a tool-call title cannot be represented in v2",
2277            ));
2278        };
2279        Ok(super::RequestPermissionRequest {
2280            session_id: session_id.try_to_v2()?,
2281            title,
2282            description: None,
2283            subject: Some(super::RequestPermissionSubject::from(
2284                tool_call.try_to_v2()?,
2285            )),
2286            options: options.try_to_v2()?,
2287            meta: meta.try_to_v2()?,
2288        })
2289    }
2290}
2291
2292impl TryToV1 for super::PermissionOption {
2293    type Output = crate::v1::PermissionOption;
2294
2295    fn try_to_v1(self) -> Result<Self::Output> {
2296        let Self {
2297            option_id,
2298            name,
2299            kind,
2300            meta,
2301        } = self;
2302        Ok(crate::v1::PermissionOption {
2303            option_id: option_id.try_to_v1()?,
2304            name: name.try_to_v1()?,
2305            kind: kind.try_to_v1()?,
2306            meta: meta.try_to_v1()?,
2307        })
2308    }
2309}
2310
2311impl TryToV2 for crate::v1::PermissionOption {
2312    type Output = super::PermissionOption;
2313
2314    fn try_to_v2(self) -> Result<Self::Output> {
2315        let Self {
2316            option_id,
2317            name,
2318            kind,
2319            meta,
2320        } = self;
2321        Ok(super::PermissionOption {
2322            option_id: option_id.try_to_v2()?,
2323            name: name.try_to_v2()?,
2324            kind: kind.try_to_v2()?,
2325            meta: meta.try_to_v2()?,
2326        })
2327    }
2328}
2329
2330impl TryToV1 for super::PermissionOptionId {
2331    type Output = crate::v1::PermissionOptionId;
2332
2333    fn try_to_v1(self) -> Result<Self::Output> {
2334        Ok(crate::v1::PermissionOptionId(self.0.try_to_v1()?))
2335    }
2336}
2337
2338impl TryToV2 for crate::v1::PermissionOptionId {
2339    type Output = super::PermissionOptionId;
2340
2341    fn try_to_v2(self) -> Result<Self::Output> {
2342        Ok(super::PermissionOptionId(self.0.try_to_v2()?))
2343    }
2344}
2345
2346impl TryToV1 for super::PermissionOptionKind {
2347    type Output = crate::v1::PermissionOptionKind;
2348
2349    fn try_to_v1(self) -> Result<Self::Output> {
2350        Ok(match self {
2351            Self::AllowOnce => crate::v1::PermissionOptionKind::AllowOnce,
2352            Self::AllowAlways => crate::v1::PermissionOptionKind::AllowAlways,
2353            Self::RejectOnce => crate::v1::PermissionOptionKind::RejectOnce,
2354            Self::RejectAlways => crate::v1::PermissionOptionKind::RejectAlways,
2355            Self::Other(value) => {
2356                return Err(unknown_v2_enum_variant("PermissionOptionKind", &value));
2357            }
2358        })
2359    }
2360}
2361
2362impl TryToV2 for crate::v1::PermissionOptionKind {
2363    type Output = super::PermissionOptionKind;
2364
2365    fn try_to_v2(self) -> Result<Self::Output> {
2366        Ok(match self {
2367            Self::AllowOnce => super::PermissionOptionKind::AllowOnce,
2368            Self::AllowAlways => super::PermissionOptionKind::AllowAlways,
2369            Self::RejectOnce => super::PermissionOptionKind::RejectOnce,
2370            Self::RejectAlways => super::PermissionOptionKind::RejectAlways,
2371        })
2372    }
2373}
2374
2375impl TryToV1 for super::RequestPermissionResponse {
2376    type Output = crate::v1::RequestPermissionResponse;
2377
2378    fn try_to_v1(self) -> Result<Self::Output> {
2379        let Self { outcome, meta } = self;
2380        Ok(crate::v1::RequestPermissionResponse {
2381            outcome: outcome.try_to_v1()?,
2382            meta: meta.try_to_v1()?,
2383        })
2384    }
2385}
2386
2387impl TryToV2 for crate::v1::RequestPermissionResponse {
2388    type Output = super::RequestPermissionResponse;
2389
2390    fn try_to_v2(self) -> Result<Self::Output> {
2391        let Self { outcome, meta } = self;
2392        Ok(super::RequestPermissionResponse {
2393            outcome: outcome.try_to_v2()?,
2394            meta: meta.try_to_v2()?,
2395        })
2396    }
2397}
2398
2399impl TryToV1 for super::RequestPermissionOutcome {
2400    type Output = crate::v1::RequestPermissionOutcome;
2401
2402    fn try_to_v1(self) -> Result<Self::Output> {
2403        Ok(match self {
2404            Self::Cancelled => crate::v1::RequestPermissionOutcome::Cancelled,
2405            Self::Selected(value) => {
2406                crate::v1::RequestPermissionOutcome::Selected(value.try_to_v1()?)
2407            }
2408            Self::Other(value) => {
2409                return Err(unknown_v2_enum_variant(
2410                    "RequestPermissionOutcome",
2411                    &value.outcome,
2412                ));
2413            }
2414        })
2415    }
2416}
2417
2418impl TryToV2 for crate::v1::RequestPermissionOutcome {
2419    type Output = super::RequestPermissionOutcome;
2420
2421    fn try_to_v2(self) -> Result<Self::Output> {
2422        Ok(match self {
2423            Self::Cancelled => super::RequestPermissionOutcome::Cancelled,
2424            Self::Selected(value) => super::RequestPermissionOutcome::Selected(value.try_to_v2()?),
2425        })
2426    }
2427}
2428
2429impl TryToV1 for super::SelectedPermissionOutcome {
2430    type Output = crate::v1::SelectedPermissionOutcome;
2431
2432    fn try_to_v1(self) -> Result<Self::Output> {
2433        let Self { option_id, meta } = self;
2434        Ok(crate::v1::SelectedPermissionOutcome {
2435            option_id: option_id.try_to_v1()?,
2436            meta: meta.try_to_v1()?,
2437        })
2438    }
2439}
2440
2441impl TryToV2 for crate::v1::SelectedPermissionOutcome {
2442    type Output = super::SelectedPermissionOutcome;
2443
2444    fn try_to_v2(self) -> Result<Self::Output> {
2445        let Self { option_id, meta } = self;
2446        Ok(super::SelectedPermissionOutcome {
2447            option_id: option_id.try_to_v2()?,
2448            meta: meta.try_to_v2()?,
2449        })
2450    }
2451}
2452
2453#[cfg(feature = "unstable_mcp_over_acp")]
2454impl TryToV1 for super::ConnectMcpRequest {
2455    type Output = crate::v1::ConnectMcpRequest;
2456
2457    fn try_to_v1(self) -> Result<Self::Output> {
2458        let Self { server_id, meta } = self;
2459        Ok(crate::v1::ConnectMcpRequest {
2460            server_id: server_id.try_to_v1()?,
2461            meta: meta.try_to_v1()?,
2462        })
2463    }
2464}
2465
2466#[cfg(feature = "unstable_mcp_over_acp")]
2467impl TryToV2 for crate::v1::ConnectMcpRequest {
2468    type Output = super::ConnectMcpRequest;
2469
2470    fn try_to_v2(self) -> Result<Self::Output> {
2471        let Self { server_id, meta } = self;
2472        Ok(super::ConnectMcpRequest {
2473            server_id: server_id.try_to_v2()?,
2474            meta: meta.try_to_v2()?,
2475        })
2476    }
2477}
2478
2479#[cfg(feature = "unstable_mcp_over_acp")]
2480impl TryToV1 for super::ConnectMcpResponse {
2481    type Output = crate::v1::ConnectMcpResponse;
2482
2483    fn try_to_v1(self) -> Result<Self::Output> {
2484        let Self {
2485            connection_id,
2486            meta,
2487        } = self;
2488        Ok(crate::v1::ConnectMcpResponse {
2489            connection_id: connection_id.try_to_v1()?,
2490            meta: meta.try_to_v1()?,
2491        })
2492    }
2493}
2494
2495#[cfg(feature = "unstable_mcp_over_acp")]
2496impl TryToV2 for crate::v1::ConnectMcpResponse {
2497    type Output = super::ConnectMcpResponse;
2498
2499    fn try_to_v2(self) -> Result<Self::Output> {
2500        let Self {
2501            connection_id,
2502            meta,
2503        } = self;
2504        Ok(super::ConnectMcpResponse {
2505            connection_id: connection_id.try_to_v2()?,
2506            meta: meta.try_to_v2()?,
2507        })
2508    }
2509}
2510
2511#[cfg(feature = "unstable_mcp_over_acp")]
2512impl TryToV1 for super::MessageMcpRequest {
2513    type Output = crate::v1::MessageMcpRequest;
2514
2515    fn try_to_v1(self) -> Result<Self::Output> {
2516        let Self {
2517            connection_id,
2518            method,
2519            params,
2520            meta,
2521        } = self;
2522        Ok(crate::v1::MessageMcpRequest {
2523            connection_id: connection_id.try_to_v1()?,
2524            method: method.try_to_v1()?,
2525            params: params.try_to_v1()?,
2526            meta: meta.try_to_v1()?,
2527        })
2528    }
2529}
2530
2531#[cfg(feature = "unstable_mcp_over_acp")]
2532impl TryToV2 for crate::v1::MessageMcpRequest {
2533    type Output = super::MessageMcpRequest;
2534
2535    fn try_to_v2(self) -> Result<Self::Output> {
2536        let Self {
2537            connection_id,
2538            method,
2539            params,
2540            meta,
2541        } = self;
2542        Ok(super::MessageMcpRequest {
2543            connection_id: connection_id.try_to_v2()?,
2544            method: method.try_to_v2()?,
2545            params: params.try_to_v2()?,
2546            meta: meta.try_to_v2()?,
2547        })
2548    }
2549}
2550
2551#[cfg(feature = "unstable_mcp_over_acp")]
2552impl TryToV1 for super::MessageMcpNotification {
2553    type Output = crate::v1::MessageMcpNotification;
2554
2555    fn try_to_v1(self) -> Result<Self::Output> {
2556        let Self {
2557            connection_id,
2558            method,
2559            params,
2560            meta,
2561        } = self;
2562        Ok(crate::v1::MessageMcpNotification {
2563            connection_id: connection_id.try_to_v1()?,
2564            method: method.try_to_v1()?,
2565            params: params.try_to_v1()?,
2566            meta: meta.try_to_v1()?,
2567        })
2568    }
2569}
2570
2571#[cfg(feature = "unstable_mcp_over_acp")]
2572impl TryToV2 for crate::v1::MessageMcpNotification {
2573    type Output = super::MessageMcpNotification;
2574
2575    fn try_to_v2(self) -> Result<Self::Output> {
2576        let Self {
2577            connection_id,
2578            method,
2579            params,
2580            meta,
2581        } = self;
2582        Ok(super::MessageMcpNotification {
2583            connection_id: connection_id.try_to_v2()?,
2584            method: method.try_to_v2()?,
2585            params: params.try_to_v2()?,
2586            meta: meta.try_to_v2()?,
2587        })
2588    }
2589}
2590
2591#[cfg(feature = "unstable_mcp_over_acp")]
2592impl TryToV1 for super::MessageMcpResponse {
2593    type Output = crate::v1::MessageMcpResponse;
2594
2595    fn try_to_v1(self) -> Result<Self::Output> {
2596        let Self(result) = self;
2597        Ok(crate::v1::MessageMcpResponse::new(result.try_to_v1()?))
2598    }
2599}
2600
2601#[cfg(feature = "unstable_mcp_over_acp")]
2602impl TryToV2 for crate::v1::MessageMcpResponse {
2603    type Output = super::MessageMcpResponse;
2604
2605    fn try_to_v2(self) -> Result<Self::Output> {
2606        let Self(result) = self;
2607        Ok(super::MessageMcpResponse::new(result.try_to_v2()?))
2608    }
2609}
2610
2611#[cfg(feature = "unstable_mcp_over_acp")]
2612impl TryToV1 for super::DisconnectMcpRequest {
2613    type Output = crate::v1::DisconnectMcpRequest;
2614
2615    fn try_to_v1(self) -> Result<Self::Output> {
2616        let Self {
2617            connection_id,
2618            meta,
2619        } = self;
2620        Ok(crate::v1::DisconnectMcpRequest {
2621            connection_id: connection_id.try_to_v1()?,
2622            meta: meta.try_to_v1()?,
2623        })
2624    }
2625}
2626
2627#[cfg(feature = "unstable_mcp_over_acp")]
2628impl TryToV2 for crate::v1::DisconnectMcpRequest {
2629    type Output = super::DisconnectMcpRequest;
2630
2631    fn try_to_v2(self) -> Result<Self::Output> {
2632        let Self {
2633            connection_id,
2634            meta,
2635        } = self;
2636        Ok(super::DisconnectMcpRequest {
2637            connection_id: connection_id.try_to_v2()?,
2638            meta: meta.try_to_v2()?,
2639        })
2640    }
2641}
2642
2643#[cfg(feature = "unstable_mcp_over_acp")]
2644impl TryToV1 for super::DisconnectMcpResponse {
2645    type Output = crate::v1::DisconnectMcpResponse;
2646
2647    fn try_to_v1(self) -> Result<Self::Output> {
2648        let Self { meta } = self;
2649        Ok(crate::v1::DisconnectMcpResponse {
2650            meta: meta.try_to_v1()?,
2651        })
2652    }
2653}
2654
2655#[cfg(feature = "unstable_mcp_over_acp")]
2656impl TryToV2 for crate::v1::DisconnectMcpResponse {
2657    type Output = super::DisconnectMcpResponse;
2658
2659    fn try_to_v2(self) -> Result<Self::Output> {
2660        let Self { meta } = self;
2661        Ok(super::DisconnectMcpResponse {
2662            meta: meta.try_to_v2()?,
2663        })
2664    }
2665}
2666
2667impl TryToV1 for super::ClientCapabilities {
2668    type Output = crate::v1::ClientCapabilities;
2669
2670    fn try_to_v1(self) -> Result<Self::Output> {
2671        let Self {
2672            #[cfg(feature = "unstable_auth_methods")]
2673            auth,
2674            #[cfg(feature = "unstable_elicitation")]
2675            elicitation,
2676            #[cfg(feature = "unstable_nes")]
2677            nes,
2678            #[cfg(feature = "unstable_nes")]
2679            position_encodings,
2680            meta,
2681        } = self;
2682        Ok(crate::v1::ClientCapabilities {
2683            fs: crate::v1::FileSystemCapabilities::default(),
2684            terminal: false,
2685            session: Some(
2686                crate::v1::ClientSessionCapabilities::new().config_options(
2687                    crate::v1::SessionConfigOptionsCapabilities::new()
2688                        .boolean(crate::v1::BooleanConfigOptionCapabilities::new()),
2689                ),
2690            ),
2691            #[cfg(feature = "unstable_plan_operations")]
2692            plan: None,
2693            #[cfg(feature = "unstable_auth_methods")]
2694            auth: auth
2695                .map(TryToV1::try_to_v1)
2696                .transpose()?
2697                .unwrap_or_default(),
2698            #[cfg(feature = "unstable_elicitation")]
2699            elicitation: elicitation.try_to_v1()?,
2700            #[cfg(feature = "unstable_nes")]
2701            nes: nes.try_to_v1()?,
2702            #[cfg(feature = "unstable_nes")]
2703            position_encodings: position_encodings.try_to_v1()?,
2704            meta: meta.try_to_v1()?,
2705        })
2706    }
2707}
2708
2709impl TryToV2 for crate::v1::ClientCapabilities {
2710    type Output = super::ClientCapabilities;
2711
2712    fn try_to_v2(self) -> Result<Self::Output> {
2713        let Self {
2714            fs,
2715            terminal,
2716            session,
2717            #[cfg(feature = "unstable_plan_operations")]
2718            plan,
2719            #[cfg(feature = "unstable_auth_methods")]
2720            auth,
2721            #[cfg(feature = "unstable_elicitation")]
2722            elicitation,
2723            #[cfg(feature = "unstable_nes")]
2724            nes,
2725            #[cfg(feature = "unstable_nes")]
2726            position_encodings,
2727            meta,
2728        } = self;
2729        if fs != crate::v1::FileSystemCapabilities::default() {
2730            return Err(unrepresentable_v1_field("ClientCapabilities", "fs"));
2731        }
2732        if terminal {
2733            return Err(unrepresentable_v1_field("ClientCapabilities", "terminal"));
2734        }
2735        v1_client_session_capabilities_representable_in_v2(session)?;
2736        #[cfg(feature = "unstable_plan_operations")]
2737        if plan.is_some() {
2738            return Err(unrepresentable_v1_field("ClientCapabilities", "plan"));
2739        }
2740
2741        Ok(super::ClientCapabilities {
2742            #[cfg(feature = "unstable_auth_methods")]
2743            auth: v1_client_auth_capabilities_into_v2_option(auth)?,
2744            #[cfg(feature = "unstable_elicitation")]
2745            elicitation: elicitation.try_to_v2()?,
2746            #[cfg(feature = "unstable_nes")]
2747            nes: nes.try_to_v2()?,
2748            #[cfg(feature = "unstable_nes")]
2749            position_encodings: position_encodings.try_to_v2()?,
2750            meta: meta.try_to_v2()?,
2751        })
2752    }
2753}
2754
2755fn v1_client_session_capabilities_representable_in_v2(
2756    session: Option<crate::v1::ClientSessionCapabilities>,
2757) -> Result<()> {
2758    let Some(session) = session else {
2759        return Ok(());
2760    };
2761    let crate::v1::ClientSessionCapabilities {
2762        config_options,
2763        meta,
2764    } = session;
2765    reject_v1_marker_meta("ClientCapabilities", "session", meta.as_ref())?;
2766
2767    let Some(config_options) = config_options else {
2768        return Ok(());
2769    };
2770    let crate::v1::SessionConfigOptionsCapabilities { boolean, meta } = config_options;
2771    reject_v1_marker_meta("ClientCapabilities.session", "configOptions", meta.as_ref())?;
2772
2773    if let Some(boolean) = boolean {
2774        reject_v1_marker_meta(
2775            "ClientCapabilities.session.configOptions",
2776            "boolean",
2777            boolean.meta.as_ref(),
2778        )?;
2779    }
2780
2781    Ok(())
2782}
2783
2784#[cfg(feature = "unstable_auth_methods")]
2785fn v1_client_auth_capabilities_into_v2_option(
2786    auth: crate::v1::AuthCapabilities,
2787) -> Result<Option<super::AuthCapabilities>> {
2788    let crate::v1::AuthCapabilities { terminal, meta } = auth;
2789    if !terminal && meta.is_none() {
2790        return Ok(None);
2791    }
2792    Ok(Some(super::AuthCapabilities {
2793        terminal: terminal.then(super::TerminalAuthCapabilities::new),
2794        meta: meta.try_to_v2()?,
2795    }))
2796}
2797
2798#[cfg(feature = "unstable_auth_methods")]
2799impl TryToV1 for super::AuthCapabilities {
2800    type Output = crate::v1::AuthCapabilities;
2801
2802    fn try_to_v1(self) -> Result<Self::Output> {
2803        let Self { terminal, meta } = self;
2804        if let Some(terminal) = &terminal {
2805            reject_v2_marker_meta("AuthCapabilities", "terminal", terminal.meta.as_ref())?;
2806        }
2807        Ok(crate::v1::AuthCapabilities {
2808            terminal: terminal.is_some(),
2809            meta: meta.try_to_v1()?,
2810        })
2811    }
2812}
2813
2814#[cfg(feature = "unstable_auth_methods")]
2815impl TryToV2 for crate::v1::AuthCapabilities {
2816    type Output = super::AuthCapabilities;
2817
2818    fn try_to_v2(self) -> Result<Self::Output> {
2819        let Self { terminal, meta } = self;
2820        Ok(super::AuthCapabilities {
2821            terminal: terminal.then(super::TerminalAuthCapabilities::new),
2822            meta: meta.try_to_v2()?,
2823        })
2824    }
2825}
2826
2827impl TryToV1 for super::Error {
2828    type Output = crate::v1::Error;
2829
2830    fn try_to_v1(self) -> Result<Self::Output> {
2831        let Self {
2832            code,
2833            message,
2834            data,
2835        } = self;
2836        Ok(crate::v1::Error {
2837            code: code.try_to_v1()?,
2838            message: message.try_to_v1()?,
2839            data: data.try_to_v1()?,
2840        })
2841    }
2842}
2843
2844impl TryToV2 for crate::v1::Error {
2845    type Output = super::Error;
2846
2847    fn try_to_v2(self) -> Result<Self::Output> {
2848        let Self {
2849            code,
2850            message,
2851            data,
2852        } = self;
2853        Ok(super::Error {
2854            code: code.try_to_v2()?,
2855            message: message.try_to_v2()?,
2856            data: data.try_to_v2()?,
2857        })
2858    }
2859}
2860
2861impl TryToV1 for super::ErrorCode {
2862    type Output = crate::v1::ErrorCode;
2863
2864    fn try_to_v1(self) -> Result<Self::Output> {
2865        Ok(i32::from(self).into())
2866    }
2867}
2868
2869impl TryToV2 for crate::v1::ErrorCode {
2870    type Output = super::ErrorCode;
2871
2872    fn try_to_v2(self) -> Result<Self::Output> {
2873        Ok(i32::from(self).into())
2874    }
2875}
2876
2877impl TryToV1 for super::ExtRequest {
2878    type Output = crate::v1::ExtRequest;
2879
2880    fn try_to_v1(self) -> Result<Self::Output> {
2881        let Self { method, params } = self;
2882        Ok(crate::v1::ExtRequest {
2883            method: method.try_to_v1()?,
2884            params: params.try_to_v1()?,
2885        })
2886    }
2887}
2888
2889impl TryToV2 for crate::v1::ExtRequest {
2890    type Output = super::ExtRequest;
2891
2892    fn try_to_v2(self) -> Result<Self::Output> {
2893        let Self { method, params } = self;
2894        Ok(super::ExtRequest {
2895            method: method.try_to_v2()?,
2896            params: params.try_to_v2()?,
2897        })
2898    }
2899}
2900
2901impl TryToV1 for super::ExtResponse {
2902    type Output = crate::v1::ExtResponse;
2903
2904    fn try_to_v1(self) -> Result<Self::Output> {
2905        Ok(crate::v1::ExtResponse(self.0.try_to_v1()?))
2906    }
2907}
2908
2909impl TryToV2 for crate::v1::ExtResponse {
2910    type Output = super::ExtResponse;
2911
2912    fn try_to_v2(self) -> Result<Self::Output> {
2913        Ok(super::ExtResponse(self.0.try_to_v2()?))
2914    }
2915}
2916
2917impl TryToV1 for super::ExtNotification {
2918    type Output = crate::v1::ExtNotification;
2919
2920    fn try_to_v1(self) -> Result<Self::Output> {
2921        let Self { method, params } = self;
2922        Ok(crate::v1::ExtNotification {
2923            method: method.try_to_v1()?,
2924            params: params.try_to_v1()?,
2925        })
2926    }
2927}
2928
2929impl TryToV2 for crate::v1::ExtNotification {
2930    type Output = super::ExtNotification;
2931
2932    fn try_to_v2(self) -> Result<Self::Output> {
2933        let Self { method, params } = self;
2934        Ok(super::ExtNotification {
2935            method: method.try_to_v2()?,
2936            params: params.try_to_v2()?,
2937        })
2938    }
2939}
2940
2941fn maybe_undefined_value_into_v1_option<T>(
2942    context: &str,
2943    value: crate::MaybeUndefined<T>,
2944) -> Result<Option<T::Output>>
2945where
2946    T: TryToV1,
2947{
2948    match value {
2949        crate::MaybeUndefined::Value(value) => Ok(Some(value.try_to_v1()?)),
2950        crate::MaybeUndefined::Null => Err(ProtocolConversionError::new(format!(
2951            "v2 {context} with null value cannot be represented in v1"
2952        ))),
2953        crate::MaybeUndefined::Undefined => Ok(None),
2954    }
2955}
2956
2957fn maybe_undefined_vec_into_v1_option<T>(
2958    context: &str,
2959    value: crate::MaybeUndefined<Vec<T>>,
2960) -> Result<Option<Vec<T::Output>>>
2961where
2962    T: TryToV1,
2963{
2964    match value {
2965        crate::MaybeUndefined::Value(value) => Ok(Some(value.try_to_v1()?)),
2966        crate::MaybeUndefined::Null => Err(ProtocolConversionError::new(format!(
2967            "v2 {context} with null collection cannot be represented in v1"
2968        ))),
2969        crate::MaybeUndefined::Undefined => Ok(None),
2970    }
2971}
2972
2973fn maybe_undefined_meta_into_v1_option(
2974    context: &str,
2975    value: crate::MaybeUndefined<super::Meta>,
2976) -> Result<Option<crate::v1::Meta>> {
2977    match value {
2978        crate::MaybeUndefined::Value(value) => Ok(Some(value.try_to_v1()?)),
2979        crate::MaybeUndefined::Null => Err(ProtocolConversionError::new(format!(
2980            "v2 {context} with null _meta cannot be represented in v1"
2981        ))),
2982        crate::MaybeUndefined::Undefined => Ok(None),
2983    }
2984}
2985
2986fn option_into_v2_maybe_undefined<T>(value: Option<T>) -> Result<crate::MaybeUndefined<T::Output>>
2987where
2988    T: TryToV2,
2989{
2990    match value {
2991        Some(value) => Ok(crate::MaybeUndefined::Value(value.try_to_v2()?)),
2992        None => Ok(crate::MaybeUndefined::Undefined),
2993    }
2994}
2995
2996fn option_vec_into_v2_maybe_undefined<T>(
2997    value: Option<Vec<T>>,
2998) -> Result<crate::MaybeUndefined<Vec<T::Output>>>
2999where
3000    T: TryToV2,
3001{
3002    match value {
3003        Some(value) => Ok(crate::MaybeUndefined::Value(value.try_to_v2()?)),
3004        None => Ok(crate::MaybeUndefined::Undefined),
3005    }
3006}
3007
3008fn vec_into_v2_maybe_undefined<T>(value: Vec<T>) -> Result<crate::MaybeUndefined<Vec<T::Output>>>
3009where
3010    T: TryToV2,
3011{
3012    if value.is_empty() {
3013        Ok(crate::MaybeUndefined::Undefined)
3014    } else {
3015        Ok(crate::MaybeUndefined::Value(value.try_to_v2()?))
3016    }
3017}
3018
3019impl TryToV1 for super::ToolCallUpdate {
3020    type Output = crate::v1::ToolCallUpdate;
3021
3022    fn try_to_v1(self) -> Result<Self::Output> {
3023        let Self {
3024            tool_call_id,
3025            title,
3026            kind,
3027            status,
3028            content,
3029            locations,
3030            raw_input,
3031            raw_output,
3032            meta,
3033        } = self;
3034        Ok(crate::v1::ToolCallUpdate {
3035            tool_call_id: tool_call_id.try_to_v1()?,
3036            fields: crate::v1::ToolCallUpdateFields {
3037                kind: maybe_undefined_value_into_v1_option("ToolCallUpdate.kind", kind)?,
3038                status: maybe_undefined_value_into_v1_option("ToolCallUpdate.status", status)?,
3039                title: maybe_undefined_value_into_v1_option("ToolCallUpdate.title", title)?,
3040                content: maybe_undefined_vec_into_v1_option("ToolCallUpdate.content", content)?,
3041                locations: maybe_undefined_vec_into_v1_option(
3042                    "ToolCallUpdate.locations",
3043                    locations,
3044                )?,
3045                raw_input: maybe_undefined_value_into_v1_option(
3046                    "ToolCallUpdate.rawInput",
3047                    raw_input,
3048                )?,
3049                raw_output: maybe_undefined_value_into_v1_option(
3050                    "ToolCallUpdate.rawOutput",
3051                    raw_output,
3052                )?,
3053            },
3054            meta: maybe_undefined_meta_into_v1_option("ToolCallUpdate", meta)?,
3055        })
3056    }
3057}
3058
3059impl TryToV2 for crate::v1::ToolCall {
3060    type Output = super::ToolCallUpdate;
3061
3062    fn try_to_v2(self) -> Result<Self::Output> {
3063        let Self {
3064            tool_call_id,
3065            title,
3066            kind,
3067            status,
3068            content,
3069            locations,
3070            raw_input,
3071            raw_output,
3072            meta,
3073        } = self;
3074        Ok(super::ToolCallUpdate {
3075            tool_call_id: tool_call_id.try_to_v2()?,
3076            title: crate::MaybeUndefined::Value(title.try_to_v2()?),
3077            kind: if matches!(kind, crate::v1::ToolKind::Other) {
3078                crate::MaybeUndefined::Undefined
3079            } else {
3080                crate::MaybeUndefined::Value(kind.try_to_v2()?)
3081            },
3082            status: if matches!(status, crate::v1::ToolCallStatus::Pending) {
3083                crate::MaybeUndefined::Undefined
3084            } else {
3085                crate::MaybeUndefined::Value(status.try_to_v2()?)
3086            },
3087            content: vec_into_v2_maybe_undefined(content)?,
3088            locations: vec_into_v2_maybe_undefined(locations)?,
3089            raw_input: option_into_v2_maybe_undefined(raw_input)?,
3090            raw_output: option_into_v2_maybe_undefined(raw_output)?,
3091            meta: option_into_v2_maybe_undefined(meta)?,
3092        })
3093    }
3094}
3095
3096impl TryToV2 for crate::v1::ToolCallUpdate {
3097    type Output = super::ToolCallUpdate;
3098
3099    fn try_to_v2(self) -> Result<Self::Output> {
3100        let Self {
3101            tool_call_id,
3102            fields,
3103            meta,
3104        } = self;
3105        let crate::v1::ToolCallUpdateFields {
3106            kind,
3107            status,
3108            title,
3109            content,
3110            locations,
3111            raw_input,
3112            raw_output,
3113        } = fields;
3114        Ok(super::ToolCallUpdate {
3115            tool_call_id: tool_call_id.try_to_v2()?,
3116            kind: option_into_v2_maybe_undefined(kind)?,
3117            status: option_into_v2_maybe_undefined(status)?,
3118            title: option_into_v2_maybe_undefined(title)?,
3119            content: option_vec_into_v2_maybe_undefined(content)?,
3120            locations: option_vec_into_v2_maybe_undefined(locations)?,
3121            raw_input: option_into_v2_maybe_undefined(raw_input)?,
3122            raw_output: option_into_v2_maybe_undefined(raw_output)?,
3123            meta: option_into_v2_maybe_undefined(meta)?,
3124        })
3125    }
3126}
3127
3128impl TryToV1 for super::ToolCallId {
3129    type Output = crate::v1::ToolCallId;
3130
3131    fn try_to_v1(self) -> Result<Self::Output> {
3132        Ok(crate::v1::ToolCallId(self.0.try_to_v1()?))
3133    }
3134}
3135
3136impl TryToV2 for crate::v1::ToolCallId {
3137    type Output = super::ToolCallId;
3138
3139    fn try_to_v2(self) -> Result<Self::Output> {
3140        Ok(super::ToolCallId(self.0.try_to_v2()?))
3141    }
3142}
3143
3144impl TryToV1 for super::ToolKind {
3145    type Output = crate::v1::ToolKind;
3146
3147    fn try_to_v1(self) -> Result<Self::Output> {
3148        Ok(match self {
3149            Self::Read => crate::v1::ToolKind::Read,
3150            Self::Edit => crate::v1::ToolKind::Edit,
3151            Self::Delete => crate::v1::ToolKind::Delete,
3152            Self::Move => crate::v1::ToolKind::Move,
3153            Self::Search => crate::v1::ToolKind::Search,
3154            Self::Execute => crate::v1::ToolKind::Execute,
3155            Self::Think => crate::v1::ToolKind::Think,
3156            Self::Fetch => crate::v1::ToolKind::Fetch,
3157            Self::SwitchMode => crate::v1::ToolKind::SwitchMode,
3158            Self::Other => crate::v1::ToolKind::Other,
3159            Self::Unknown(value) => return Err(unknown_v2_enum_variant("ToolKind", &value)),
3160        })
3161    }
3162}
3163
3164impl TryToV2 for crate::v1::ToolKind {
3165    type Output = super::ToolKind;
3166
3167    fn try_to_v2(self) -> Result<Self::Output> {
3168        Ok(match self {
3169            Self::Read => super::ToolKind::Read,
3170            Self::Edit => super::ToolKind::Edit,
3171            Self::Delete => super::ToolKind::Delete,
3172            Self::Move => super::ToolKind::Move,
3173            Self::Search => super::ToolKind::Search,
3174            Self::Execute => super::ToolKind::Execute,
3175            Self::Think => super::ToolKind::Think,
3176            Self::Fetch => super::ToolKind::Fetch,
3177            Self::SwitchMode => super::ToolKind::SwitchMode,
3178            Self::Other => super::ToolKind::Other,
3179        })
3180    }
3181}
3182
3183impl TryToV1 for super::ToolCallStatus {
3184    type Output = crate::v1::ToolCallStatus;
3185
3186    fn try_to_v1(self) -> Result<Self::Output> {
3187        Ok(match self {
3188            Self::Pending => crate::v1::ToolCallStatus::Pending,
3189            Self::InProgress => crate::v1::ToolCallStatus::InProgress,
3190            Self::Completed => crate::v1::ToolCallStatus::Completed,
3191            Self::Failed => crate::v1::ToolCallStatus::Failed,
3192            Self::Other(value) => return Err(unknown_v2_enum_variant("ToolCallStatus", &value)),
3193        })
3194    }
3195}
3196
3197impl TryToV2 for crate::v1::ToolCallStatus {
3198    type Output = super::ToolCallStatus;
3199
3200    fn try_to_v2(self) -> Result<Self::Output> {
3201        Ok(match self {
3202            Self::Pending => super::ToolCallStatus::Pending,
3203            Self::InProgress => super::ToolCallStatus::InProgress,
3204            Self::Completed => super::ToolCallStatus::Completed,
3205            Self::Failed => super::ToolCallStatus::Failed,
3206        })
3207    }
3208}
3209
3210impl TryToV1 for super::ToolCallContent {
3211    type Output = crate::v1::ToolCallContent;
3212
3213    fn try_to_v1(self) -> Result<Self::Output> {
3214        Ok(match self {
3215            Self::Content(value) => crate::v1::ToolCallContent::Content(value.try_to_v1()?),
3216            Self::Diff(value) => crate::v1::ToolCallContent::Diff(value.try_to_v1()?),
3217            Self::Terminal(_) => {
3218                return Err(ProtocolConversionError::new(
3219                    "v2 ToolCallContent variant `terminal` cannot be represented in v1 because v1 terminal content refers to a client-created terminal",
3220                ));
3221            }
3222            Self::Other(value) => {
3223                return Err(unknown_v2_enum_variant("ToolCallContent", &value.type_));
3224            }
3225        })
3226    }
3227}
3228
3229impl TryToV2 for crate::v1::ToolCallContent {
3230    type Output = super::ToolCallContent;
3231
3232    fn try_to_v2(self) -> Result<Self::Output> {
3233        Ok(match self {
3234            Self::Content(value) => super::ToolCallContent::Content(Box::new(value.try_to_v2()?)),
3235            Self::Diff(value) => super::ToolCallContent::Diff(value.try_to_v2()?),
3236            Self::Terminal(_) => {
3237                return Err(removed_v1_enum_variant("ToolCallContent", "terminal"));
3238            }
3239        })
3240    }
3241}
3242
3243impl TryToV1 for super::Content {
3244    type Output = crate::v1::Content;
3245
3246    fn try_to_v1(self) -> Result<Self::Output> {
3247        let Self { content, meta } = self;
3248        Ok(crate::v1::Content {
3249            content: content.try_to_v1()?,
3250            meta: meta.try_to_v1()?,
3251        })
3252    }
3253}
3254
3255impl TryToV2 for crate::v1::Content {
3256    type Output = super::Content;
3257
3258    fn try_to_v2(self) -> Result<Self::Output> {
3259        let Self { content, meta } = self;
3260        Ok(super::Content {
3261            content: content.try_to_v2()?,
3262            meta: meta.try_to_v2()?,
3263        })
3264    }
3265}
3266
3267impl TryToV1 for super::Diff {
3268    type Output = crate::v1::Diff;
3269
3270    fn try_to_v1(self) -> Result<Self::Output> {
3271        Err(ProtocolConversionError::new(
3272            "v2 Diff cannot be represented in v1 because v1 requires oldText/newText while v2 carries Git --patch text and structured changes",
3273        ))
3274    }
3275}
3276
3277impl TryToV2 for crate::v1::Diff {
3278    type Output = super::Diff;
3279
3280    fn try_to_v2(self) -> Result<Self::Output> {
3281        let Self {
3282            path,
3283            old_text,
3284            new_text,
3285            meta,
3286        } = self;
3287        let path = path.try_to_v2()?;
3288        let old_text = old_text.try_to_v2()?;
3289        let new_text = new_text.try_to_v2()?;
3290        let change = if old_text.is_some() {
3291            super::DiffChange::modify(path.clone()).file_type(super::DiffFileType::Text)
3292        } else {
3293            super::DiffChange::add(path.clone()).file_type(super::DiffFileType::Text)
3294        };
3295        let patch_text = full_file_git_patch(&path, old_text.as_deref(), &new_text);
3296
3297        Ok(super::Diff::patch(patch_text, vec![change]).meta(meta.try_to_v2()?))
3298    }
3299}
3300
3301fn full_file_git_patch(path: &Path, old_text: Option<&str>, new_text: &str) -> String {
3302    let path = path.to_string_lossy();
3303    let old = old_text.unwrap_or_default();
3304    let original_filename = if old_text.is_some() {
3305        path.to_string()
3306    } else {
3307        "/dev/null".to_string()
3308    };
3309
3310    let mut options = diffy::DiffOptions::new();
3311    options
3312        .set_original_filename(original_filename)
3313        .set_modified_filename(path.to_string());
3314
3315    let mut patch_text = format!("diff --git {path} {path}\n");
3316    if old_text.is_none() {
3317        patch_text.push_str("new file mode 100644\n");
3318    }
3319    patch_text.push_str(&options.create_patch(old, new_text).to_string());
3320    patch_text
3321}
3322
3323impl TryToV1 for super::ToolCallLocation {
3324    type Output = crate::v1::ToolCallLocation;
3325
3326    fn try_to_v1(self) -> Result<Self::Output> {
3327        let Self { path, line, meta } = self;
3328        Ok(crate::v1::ToolCallLocation {
3329            path: path.try_to_v1()?,
3330            line: line.try_to_v1()?,
3331            meta: meta.try_to_v1()?,
3332        })
3333    }
3334}
3335
3336impl TryToV2 for crate::v1::ToolCallLocation {
3337    type Output = super::ToolCallLocation;
3338
3339    fn try_to_v2(self) -> Result<Self::Output> {
3340        let Self { path, line, meta } = self;
3341        Ok(super::ToolCallLocation {
3342            path: super::AbsolutePath::new(path),
3343            line: line.try_to_v2()?,
3344            meta: meta.try_to_v2()?,
3345        })
3346    }
3347}
3348
3349impl TryToV1 for super::InitializeRequest {
3350    type Output = crate::v1::InitializeRequest;
3351
3352    fn try_to_v1(self) -> Result<Self::Output> {
3353        let Self {
3354            protocol_version,
3355            capabilities,
3356            info,
3357            meta,
3358        } = self;
3359        Ok(crate::v1::InitializeRequest {
3360            protocol_version: protocol_version.try_to_v1()?,
3361            client_capabilities: capabilities.try_to_v1()?,
3362            client_info: Some(info.try_to_v1()?),
3363            meta: meta.try_to_v1()?,
3364        })
3365    }
3366}
3367
3368impl TryToV2 for crate::v1::InitializeRequest {
3369    type Output = super::InitializeRequest;
3370
3371    fn try_to_v2(self) -> Result<Self::Output> {
3372        let Self {
3373            protocol_version,
3374            client_capabilities,
3375            client_info,
3376            meta,
3377        } = self;
3378        let info = match client_info {
3379            Some(client_info) => client_info.try_to_v2()?,
3380            None => {
3381                return Err(ProtocolConversionError::new(
3382                    "v1 InitializeRequest without `clientInfo` cannot be represented in v2",
3383                ));
3384            }
3385        };
3386        Ok(super::InitializeRequest {
3387            protocol_version: protocol_version.try_to_v2()?,
3388            capabilities: client_capabilities.try_to_v2()?,
3389            info,
3390            meta: meta.try_to_v2()?,
3391        })
3392    }
3393}
3394
3395impl TryToV1 for super::InitializeResponse {
3396    type Output = crate::v1::InitializeResponse;
3397
3398    fn try_to_v1(self) -> Result<Self::Output> {
3399        let Self {
3400            protocol_version,
3401            capabilities: agent_capabilities,
3402            auth_methods,
3403            info,
3404            meta,
3405        } = self;
3406        let advertises_auth = !auth_methods.is_empty();
3407        let mut agent_capabilities = agent_capabilities.try_to_v1()?;
3408        if advertises_auth {
3409            agent_capabilities.auth.logout = Some(crate::v1::LogoutCapabilities::new());
3410        }
3411        Ok(crate::v1::InitializeResponse {
3412            protocol_version: protocol_version.try_to_v1()?,
3413            agent_capabilities,
3414            auth_methods: auth_methods.try_to_v1()?,
3415            agent_info: Some(info.try_to_v1()?),
3416            meta: meta.try_to_v1()?,
3417        })
3418    }
3419}
3420
3421impl TryToV2 for crate::v1::InitializeResponse {
3422    type Output = super::InitializeResponse;
3423
3424    fn try_to_v2(self) -> Result<Self::Output> {
3425        let Self {
3426            protocol_version,
3427            mut agent_capabilities,
3428            auth_methods,
3429            agent_info,
3430            meta,
3431        } = self;
3432        let info = match agent_info {
3433            Some(agent_info) => agent_info.try_to_v2()?,
3434            None => {
3435                return Err(ProtocolConversionError::new(
3436                    "v1 InitializeResponse without `agentInfo` cannot be represented in v2",
3437                ));
3438            }
3439        };
3440        let advertises_auth = !auth_methods.is_empty();
3441        match (advertises_auth, agent_capabilities.auth.logout.take()) {
3442            (true, Some(logout)) => {
3443                reject_v1_marker_meta(
3444                    "InitializeResponse.agentCapabilities.auth",
3445                    "logout",
3446                    logout.meta.as_ref(),
3447                )?;
3448            }
3449            (true, None) => {
3450                return Err(ProtocolConversionError::new(
3451                    "v1 InitializeResponse with non-empty `authMethods` and no \
3452                     `agentCapabilities.auth.logout` cannot be represented in v2",
3453                ));
3454            }
3455            (false, Some(_)) => {
3456                return Err(ProtocolConversionError::new(
3457                    "v1 InitializeResponse with `agentCapabilities.auth.logout` and empty \
3458                     `authMethods` cannot be represented in v2",
3459                ));
3460            }
3461            (false, None) => {}
3462        }
3463        Ok(super::InitializeResponse {
3464            protocol_version: protocol_version.try_to_v2()?,
3465            capabilities: agent_capabilities.try_to_v2()?,
3466            auth_methods: auth_methods.try_to_v2()?,
3467            info,
3468            meta: meta.try_to_v2()?,
3469        })
3470    }
3471}
3472
3473impl TryToV1 for super::Implementation {
3474    type Output = crate::v1::Implementation;
3475
3476    fn try_to_v1(self) -> Result<Self::Output> {
3477        let Self {
3478            name,
3479            title,
3480            version,
3481            meta,
3482        } = self;
3483        Ok(crate::v1::Implementation {
3484            name: name.try_to_v1()?,
3485            title: title.try_to_v1()?,
3486            version: version.try_to_v1()?,
3487            meta: meta.try_to_v1()?,
3488        })
3489    }
3490}
3491
3492impl TryToV2 for crate::v1::Implementation {
3493    type Output = super::Implementation;
3494
3495    fn try_to_v2(self) -> Result<Self::Output> {
3496        let Self {
3497            name,
3498            title,
3499            version,
3500            meta,
3501        } = self;
3502        Ok(super::Implementation {
3503            name: name.try_to_v2()?,
3504            title: title.try_to_v2()?,
3505            version: version.try_to_v2()?,
3506            meta: meta.try_to_v2()?,
3507        })
3508    }
3509}
3510
3511impl TryToV1 for super::LoginAuthRequest {
3512    type Output = crate::v1::AuthenticateRequest;
3513
3514    fn try_to_v1(self) -> Result<Self::Output> {
3515        let Self { method_id, meta } = self;
3516        Ok(crate::v1::AuthenticateRequest {
3517            method_id: method_id.try_to_v1()?,
3518            meta: meta.try_to_v1()?,
3519        })
3520    }
3521}
3522
3523impl TryToV2 for crate::v1::AuthenticateRequest {
3524    type Output = super::LoginAuthRequest;
3525
3526    fn try_to_v2(self) -> Result<Self::Output> {
3527        let Self { method_id, meta } = self;
3528        Ok(super::LoginAuthRequest {
3529            method_id: method_id.try_to_v2()?,
3530            meta: meta.try_to_v2()?,
3531        })
3532    }
3533}
3534
3535impl TryToV1 for super::LoginAuthResponse {
3536    type Output = crate::v1::AuthenticateResponse;
3537
3538    fn try_to_v1(self) -> Result<Self::Output> {
3539        let Self { meta } = self;
3540        Ok(crate::v1::AuthenticateResponse {
3541            meta: meta.try_to_v1()?,
3542        })
3543    }
3544}
3545
3546impl TryToV2 for crate::v1::AuthenticateResponse {
3547    type Output = super::LoginAuthResponse;
3548
3549    fn try_to_v2(self) -> Result<Self::Output> {
3550        let Self { meta } = self;
3551        Ok(super::LoginAuthResponse {
3552            meta: meta.try_to_v2()?,
3553        })
3554    }
3555}
3556
3557impl TryToV1 for super::LogoutAuthRequest {
3558    type Output = crate::v1::LogoutRequest;
3559
3560    fn try_to_v1(self) -> Result<Self::Output> {
3561        let Self { meta } = self;
3562        Ok(crate::v1::LogoutRequest {
3563            meta: meta.try_to_v1()?,
3564        })
3565    }
3566}
3567
3568impl TryToV2 for crate::v1::LogoutRequest {
3569    type Output = super::LogoutAuthRequest;
3570
3571    fn try_to_v2(self) -> Result<Self::Output> {
3572        let Self { meta } = self;
3573        Ok(super::LogoutAuthRequest {
3574            meta: meta.try_to_v2()?,
3575        })
3576    }
3577}
3578
3579impl TryToV1 for super::LogoutAuthResponse {
3580    type Output = crate::v1::LogoutResponse;
3581
3582    fn try_to_v1(self) -> Result<Self::Output> {
3583        let Self { meta } = self;
3584        Ok(crate::v1::LogoutResponse {
3585            meta: meta.try_to_v1()?,
3586        })
3587    }
3588}
3589
3590impl TryToV2 for crate::v1::LogoutResponse {
3591    type Output = super::LogoutAuthResponse;
3592
3593    fn try_to_v2(self) -> Result<Self::Output> {
3594        let Self { meta } = self;
3595        Ok(super::LogoutAuthResponse {
3596            meta: meta.try_to_v2()?,
3597        })
3598    }
3599}
3600
3601impl TryToV1 for super::AgentAuthCapabilities {
3602    type Output = crate::v1::AgentAuthCapabilities;
3603
3604    fn try_to_v1(self) -> Result<Self::Output> {
3605        let Self { meta } = self;
3606        Ok(crate::v1::AgentAuthCapabilities {
3607            logout: None,
3608            meta: meta.try_to_v1()?,
3609        })
3610    }
3611}
3612
3613fn v1_agent_auth_capabilities_into_v2_option(
3614    auth: crate::v1::AgentAuthCapabilities,
3615) -> Result<Option<super::AgentAuthCapabilities>> {
3616    let crate::v1::AgentAuthCapabilities { logout, meta } = auth;
3617    if logout.is_some() {
3618        return Err(unrepresentable_v1_field("AgentAuthCapabilities", "logout"));
3619    }
3620    if meta.is_none() {
3621        return Ok(None);
3622    }
3623    Ok(Some(super::AgentAuthCapabilities {
3624        meta: meta.try_to_v2()?,
3625    }))
3626}
3627
3628impl TryToV2 for crate::v1::AgentAuthCapabilities {
3629    type Output = super::AgentAuthCapabilities;
3630
3631    fn try_to_v2(self) -> Result<Self::Output> {
3632        let Self { logout, meta } = self;
3633        if logout.is_some() {
3634            return Err(unrepresentable_v1_field("AgentAuthCapabilities", "logout"));
3635        }
3636        Ok(super::AgentAuthCapabilities {
3637            meta: meta.try_to_v2()?,
3638        })
3639    }
3640}
3641
3642impl TryToV1 for super::AuthMethodId {
3643    type Output = crate::v1::AuthMethodId;
3644
3645    fn try_to_v1(self) -> Result<Self::Output> {
3646        Ok(crate::v1::AuthMethodId(self.0.try_to_v1()?))
3647    }
3648}
3649
3650impl TryToV2 for crate::v1::AuthMethodId {
3651    type Output = super::AuthMethodId;
3652
3653    fn try_to_v2(self) -> Result<Self::Output> {
3654        Ok(super::AuthMethodId(self.0.try_to_v2()?))
3655    }
3656}
3657
3658impl TryToV1 for super::AuthMethod {
3659    type Output = crate::v1::AuthMethod;
3660
3661    fn try_to_v1(self) -> Result<Self::Output> {
3662        Ok(match self {
3663            #[cfg(feature = "unstable_auth_methods")]
3664            Self::EnvVar(value) => crate::v1::AuthMethod::EnvVar(value.try_to_v1()?),
3665            #[cfg(feature = "unstable_auth_methods")]
3666            Self::Terminal(value) => crate::v1::AuthMethod::Terminal(value.try_to_v1()?),
3667            Self::Other(value) => {
3668                return Err(unknown_v2_enum_variant("AuthMethod", &value.type_));
3669            }
3670            Self::Agent(value) => crate::v1::AuthMethod::Agent(value.try_to_v1()?),
3671        })
3672    }
3673}
3674
3675impl TryToV2 for crate::v1::AuthMethod {
3676    type Output = super::AuthMethod;
3677
3678    fn try_to_v2(self) -> Result<Self::Output> {
3679        Ok(match self {
3680            #[cfg(feature = "unstable_auth_methods")]
3681            Self::EnvVar(value) => super::AuthMethod::EnvVar(value.try_to_v2()?),
3682            #[cfg(feature = "unstable_auth_methods")]
3683            Self::Terminal(value) => super::AuthMethod::Terminal(value.try_to_v2()?),
3684            Self::Agent(value) => super::AuthMethod::Agent(value.try_to_v2()?),
3685        })
3686    }
3687}
3688
3689impl TryToV1 for super::AuthMethodAgent {
3690    type Output = crate::v1::AuthMethodAgent;
3691
3692    fn try_to_v1(self) -> Result<Self::Output> {
3693        let Self {
3694            method_id,
3695            name,
3696            description,
3697            meta,
3698        } = self;
3699        Ok(crate::v1::AuthMethodAgent {
3700            id: method_id.try_to_v1()?,
3701            name: name.try_to_v1()?,
3702            description: description.try_to_v1()?,
3703            meta: meta.try_to_v1()?,
3704        })
3705    }
3706}
3707
3708impl TryToV2 for crate::v1::AuthMethodAgent {
3709    type Output = super::AuthMethodAgent;
3710
3711    fn try_to_v2(self) -> Result<Self::Output> {
3712        let Self {
3713            id,
3714            name,
3715            description,
3716            meta,
3717        } = self;
3718        Ok(super::AuthMethodAgent {
3719            method_id: id.try_to_v2()?,
3720            name: name.try_to_v2()?,
3721            description: description.try_to_v2()?,
3722            meta: meta.try_to_v2()?,
3723        })
3724    }
3725}
3726
3727#[cfg(feature = "unstable_auth_methods")]
3728impl TryToV1 for super::AuthMethodEnvVar {
3729    type Output = crate::v1::AuthMethodEnvVar;
3730
3731    fn try_to_v1(self) -> Result<Self::Output> {
3732        let Self {
3733            method_id,
3734            name,
3735            description,
3736            vars,
3737            link,
3738            meta,
3739        } = self;
3740        Ok(crate::v1::AuthMethodEnvVar {
3741            id: method_id.try_to_v1()?,
3742            name: name.try_to_v1()?,
3743            description: description.try_to_v1()?,
3744            vars: vars.try_to_v1()?,
3745            link: link.try_to_v1()?,
3746            meta: meta.try_to_v1()?,
3747        })
3748    }
3749}
3750
3751#[cfg(feature = "unstable_auth_methods")]
3752impl TryToV2 for crate::v1::AuthMethodEnvVar {
3753    type Output = super::AuthMethodEnvVar;
3754
3755    fn try_to_v2(self) -> Result<Self::Output> {
3756        let Self {
3757            id,
3758            name,
3759            description,
3760            vars,
3761            link,
3762            meta,
3763        } = self;
3764        Ok(super::AuthMethodEnvVar {
3765            method_id: id.try_to_v2()?,
3766            name: name.try_to_v2()?,
3767            description: description.try_to_v2()?,
3768            vars: vars.try_to_v2()?,
3769            link: link.try_to_v2()?,
3770            meta: meta.try_to_v2()?,
3771        })
3772    }
3773}
3774
3775#[cfg(feature = "unstable_auth_methods")]
3776impl TryToV1 for super::AuthEnvVar {
3777    type Output = crate::v1::AuthEnvVar;
3778
3779    fn try_to_v1(self) -> Result<Self::Output> {
3780        let Self {
3781            name,
3782            label,
3783            secret,
3784            optional,
3785            meta,
3786        } = self;
3787        Ok(crate::v1::AuthEnvVar {
3788            name: name.try_to_v1()?,
3789            label: label.try_to_v1()?,
3790            secret: secret.try_to_v1()?,
3791            optional: optional.try_to_v1()?,
3792            meta: meta.try_to_v1()?,
3793        })
3794    }
3795}
3796
3797#[cfg(feature = "unstable_auth_methods")]
3798impl TryToV2 for crate::v1::AuthEnvVar {
3799    type Output = super::AuthEnvVar;
3800
3801    fn try_to_v2(self) -> Result<Self::Output> {
3802        let Self {
3803            name,
3804            label,
3805            secret,
3806            optional,
3807            meta,
3808        } = self;
3809        Ok(super::AuthEnvVar {
3810            name: name.try_to_v2()?,
3811            label: label.try_to_v2()?,
3812            secret: secret.try_to_v2()?,
3813            optional: optional.try_to_v2()?,
3814            meta: meta.try_to_v2()?,
3815        })
3816    }
3817}
3818
3819#[cfg(feature = "unstable_auth_methods")]
3820impl TryToV1 for super::AuthMethodTerminal {
3821    type Output = crate::v1::AuthMethodTerminal;
3822
3823    fn try_to_v1(self) -> Result<Self::Output> {
3824        let Self {
3825            method_id,
3826            name,
3827            description,
3828            args,
3829            env,
3830            meta,
3831        } = self;
3832        let env = env
3833            .into_iter()
3834            .map(|env_var| {
3835                let super::EnvVariable { name, value, meta } = env_var;
3836                if meta.is_some() {
3837                    return Err(ProtocolConversionError::new(
3838                        "v2 AuthMethodTerminal env variable `_meta` cannot be represented in v1",
3839                    ));
3840                }
3841                Ok((name.try_to_v1()?, value.try_to_v1()?))
3842            })
3843            .try_fold(HashMap::new(), |mut env, item| {
3844                let (name, value) = item?;
3845                if env.insert(name.clone(), value).is_some() {
3846                    return Err(ProtocolConversionError::new(format!(
3847                        "v2 AuthMethodTerminal env variable `{name}` is duplicated and cannot be represented in v1",
3848                    )));
3849                }
3850                Ok(env)
3851            })?;
3852        Ok(crate::v1::AuthMethodTerminal {
3853            id: method_id.try_to_v1()?,
3854            name: name.try_to_v1()?,
3855            description: description.try_to_v1()?,
3856            args: args.try_to_v1()?,
3857            env,
3858            meta: meta.try_to_v1()?,
3859        })
3860    }
3861}
3862
3863#[cfg(feature = "unstable_auth_methods")]
3864impl TryToV2 for crate::v1::AuthMethodTerminal {
3865    type Output = super::AuthMethodTerminal;
3866
3867    fn try_to_v2(self) -> Result<Self::Output> {
3868        let Self {
3869            id,
3870            name,
3871            description,
3872            args,
3873            env,
3874            meta,
3875        } = self;
3876        let mut env = env
3877            .into_iter()
3878            .map(|(name, value)| {
3879                Ok(super::EnvVariable::new(
3880                    name.try_to_v2()?,
3881                    value.try_to_v2()?,
3882                ))
3883            })
3884            .collect::<Result<Vec<_>>>()?;
3885        env.sort_by(|left, right| left.name.cmp(&right.name));
3886        Ok(super::AuthMethodTerminal {
3887            method_id: id.try_to_v2()?,
3888            name: name.try_to_v2()?,
3889            description: description.try_to_v2()?,
3890            args: args.try_to_v2()?,
3891            env,
3892            meta: meta.try_to_v2()?,
3893        })
3894    }
3895}
3896
3897impl TryToV1 for super::NewSessionRequest {
3898    type Output = crate::v1::NewSessionRequest;
3899
3900    fn try_to_v1(self) -> Result<Self::Output> {
3901        let Self {
3902            cwd,
3903            additional_directories,
3904            mcp_servers,
3905            meta,
3906        } = self;
3907        Ok(crate::v1::NewSessionRequest {
3908            cwd: cwd.try_to_v1()?,
3909            additional_directories: additional_directories.try_to_v1()?,
3910            mcp_servers: mcp_servers.try_to_v1()?,
3911            meta: meta.try_to_v1()?,
3912        })
3913    }
3914}
3915
3916impl TryToV2 for crate::v1::NewSessionRequest {
3917    type Output = super::NewSessionRequest;
3918
3919    fn try_to_v2(self) -> Result<Self::Output> {
3920        let Self {
3921            cwd,
3922            additional_directories,
3923            mcp_servers,
3924            meta,
3925        } = self;
3926        Ok(super::NewSessionRequest {
3927            cwd: super::AbsolutePath::new(cwd),
3928            additional_directories: additional_directories
3929                .into_iter()
3930                .map(super::AbsolutePath::new)
3931                .collect(),
3932            mcp_servers: mcp_servers.try_to_v2()?,
3933            meta: meta.try_to_v2()?,
3934        })
3935    }
3936}
3937
3938impl TryToV1 for super::NewSessionResponse {
3939    type Output = crate::v1::NewSessionResponse;
3940
3941    fn try_to_v1(self) -> Result<Self::Output> {
3942        let Self {
3943            session_id,
3944            config_options,
3945            meta,
3946        } = self;
3947        Ok(crate::v1::NewSessionResponse {
3948            session_id: session_id.try_to_v1()?,
3949            modes: None,
3950            config_options: Some(config_options.try_to_v1()?),
3951            meta: meta.try_to_v1()?,
3952        })
3953    }
3954}
3955
3956impl TryToV2 for crate::v1::NewSessionResponse {
3957    type Output = super::NewSessionResponse;
3958
3959    fn try_to_v2(self) -> Result<Self::Output> {
3960        let Self {
3961            session_id,
3962            modes,
3963            config_options,
3964            meta,
3965        } = self;
3966        if modes.is_some() {
3967            return Err(unrepresentable_v1_field("NewSessionResponse", "modes"));
3968        }
3969        Ok(super::NewSessionResponse {
3970            session_id: session_id.try_to_v2()?,
3971            config_options: option_vec_into_v2_default(config_options)?,
3972            meta: meta.try_to_v2()?,
3973        })
3974    }
3975}
3976
3977impl TryToV2 for crate::v1::LoadSessionRequest {
3978    type Output = super::ResumeSessionRequest;
3979
3980    fn try_to_v2(self) -> Result<Self::Output> {
3981        let Self {
3982            mcp_servers,
3983            cwd,
3984            additional_directories,
3985            session_id,
3986            meta,
3987        } = self;
3988        Ok(super::ResumeSessionRequest {
3989            mcp_servers: mcp_servers.try_to_v2()?,
3990            cwd: super::AbsolutePath::new(cwd),
3991            additional_directories: additional_directories
3992                .into_iter()
3993                .map(super::AbsolutePath::new)
3994                .collect(),
3995            session_id: session_id.try_to_v2()?,
3996            replay_from: Some(super::ReplayFrom::Start(super::ReplayFromStart::new())),
3997            meta: meta.try_to_v2()?,
3998        })
3999    }
4000}
4001
4002impl TryToV2 for crate::v1::LoadSessionResponse {
4003    type Output = super::ResumeSessionResponse;
4004
4005    fn try_to_v2(self) -> Result<Self::Output> {
4006        let Self {
4007            modes,
4008            config_options,
4009            meta,
4010        } = self;
4011        if modes.is_some() {
4012            return Err(unrepresentable_v1_field("LoadSessionResponse", "modes"));
4013        }
4014        Ok(super::ResumeSessionResponse {
4015            config_options: option_vec_into_v2_default(config_options)?,
4016            meta: meta.try_to_v2()?,
4017        })
4018    }
4019}
4020
4021fn v2_resume_session_request_into_v1_load(
4022    request: super::ResumeSessionRequest,
4023) -> Result<crate::v1::LoadSessionRequest> {
4024    let super::ResumeSessionRequest {
4025        session_id,
4026        cwd,
4027        additional_directories,
4028        mcp_servers,
4029        replay_from,
4030        meta,
4031    } = request;
4032    match replay_from {
4033        Some(super::ReplayFrom::Start(_)) => {}
4034        Some(super::ReplayFrom::Other(other)) => {
4035            return Err(unknown_v2_enum_variant("ReplayFrom", &other.type_));
4036        }
4037        None => {
4038            return Err(ProtocolConversionError::new(
4039                "v2 ResumeSessionRequest without `replayFrom: start` maps to v1 session/resume, not v1 session/load",
4040            ));
4041        }
4042    }
4043    Ok(crate::v1::LoadSessionRequest {
4044        mcp_servers: mcp_servers.try_to_v1()?,
4045        cwd: cwd.try_to_v1()?,
4046        additional_directories: additional_directories.try_to_v1()?,
4047        session_id: session_id.try_to_v1()?,
4048        meta: meta.try_to_v1()?,
4049    })
4050}
4051
4052fn unsupported_replay_from_for_v1_resume(
4053    replay_from: super::ReplayFrom,
4054) -> ProtocolConversionError {
4055    match replay_from {
4056        super::ReplayFrom::Start(_) => ProtocolConversionError::new(
4057            "v2 ResumeSessionRequest `replayFrom: start` maps to v1 session/load, not v1 session/resume",
4058        ),
4059        super::ReplayFrom::Other(other) => unknown_v2_enum_variant("ReplayFrom", &other.type_),
4060    }
4061}
4062
4063#[cfg(feature = "unstable_session_fork")]
4064impl TryToV1 for super::ForkSessionRequest {
4065    type Output = crate::v1::ForkSessionRequest;
4066
4067    fn try_to_v1(self) -> Result<Self::Output> {
4068        let Self {
4069            session_id,
4070            cwd,
4071            additional_directories,
4072            mcp_servers,
4073            meta,
4074        } = self;
4075        Ok(crate::v1::ForkSessionRequest {
4076            session_id: session_id.try_to_v1()?,
4077            cwd: cwd.try_to_v1()?,
4078            additional_directories: additional_directories.try_to_v1()?,
4079            mcp_servers: mcp_servers.try_to_v1()?,
4080            meta: meta.try_to_v1()?,
4081        })
4082    }
4083}
4084
4085#[cfg(feature = "unstable_session_fork")]
4086impl TryToV2 for crate::v1::ForkSessionRequest {
4087    type Output = super::ForkSessionRequest;
4088
4089    fn try_to_v2(self) -> Result<Self::Output> {
4090        let Self {
4091            session_id,
4092            cwd,
4093            additional_directories,
4094            mcp_servers,
4095            meta,
4096        } = self;
4097        Ok(super::ForkSessionRequest {
4098            session_id: session_id.try_to_v2()?,
4099            cwd: super::AbsolutePath::new(cwd),
4100            additional_directories: additional_directories
4101                .into_iter()
4102                .map(super::AbsolutePath::new)
4103                .collect(),
4104            mcp_servers: mcp_servers.try_to_v2()?,
4105            meta: meta.try_to_v2()?,
4106        })
4107    }
4108}
4109
4110#[cfg(feature = "unstable_session_fork")]
4111impl TryToV1 for super::ForkSessionResponse {
4112    type Output = crate::v1::ForkSessionResponse;
4113
4114    fn try_to_v1(self) -> Result<Self::Output> {
4115        let Self {
4116            session_id,
4117            config_options,
4118            meta,
4119        } = self;
4120        Ok(crate::v1::ForkSessionResponse {
4121            session_id: session_id.try_to_v1()?,
4122            modes: None,
4123            config_options: Some(config_options.try_to_v1()?),
4124            meta: meta.try_to_v1()?,
4125        })
4126    }
4127}
4128
4129#[cfg(feature = "unstable_session_fork")]
4130impl TryToV2 for crate::v1::ForkSessionResponse {
4131    type Output = super::ForkSessionResponse;
4132
4133    fn try_to_v2(self) -> Result<Self::Output> {
4134        let Self {
4135            session_id,
4136            modes,
4137            config_options,
4138            meta,
4139        } = self;
4140        if modes.is_some() {
4141            return Err(unrepresentable_v1_field("ForkSessionResponse", "modes"));
4142        }
4143        Ok(super::ForkSessionResponse {
4144            session_id: session_id.try_to_v2()?,
4145            config_options: option_vec_into_v2_default(config_options)?,
4146            meta: meta.try_to_v2()?,
4147        })
4148    }
4149}
4150
4151impl TryToV1 for super::ResumeSessionRequest {
4152    type Output = crate::v1::ResumeSessionRequest;
4153
4154    fn try_to_v1(self) -> Result<Self::Output> {
4155        let Self {
4156            session_id,
4157            cwd,
4158            additional_directories,
4159            mcp_servers,
4160            replay_from,
4161            meta,
4162        } = self;
4163        if let Some(replay_from) = replay_from {
4164            return Err(unsupported_replay_from_for_v1_resume(replay_from));
4165        }
4166        Ok(crate::v1::ResumeSessionRequest {
4167            session_id: session_id.try_to_v1()?,
4168            cwd: cwd.try_to_v1()?,
4169            additional_directories: additional_directories.try_to_v1()?,
4170            mcp_servers: mcp_servers.try_to_v1()?,
4171            meta: meta.try_to_v1()?,
4172        })
4173    }
4174}
4175
4176impl TryToV2 for crate::v1::ResumeSessionRequest {
4177    type Output = super::ResumeSessionRequest;
4178
4179    fn try_to_v2(self) -> Result<Self::Output> {
4180        let Self {
4181            session_id,
4182            cwd,
4183            additional_directories,
4184            mcp_servers,
4185            meta,
4186        } = self;
4187        Ok(super::ResumeSessionRequest {
4188            session_id: session_id.try_to_v2()?,
4189            cwd: super::AbsolutePath::new(cwd),
4190            additional_directories: additional_directories
4191                .into_iter()
4192                .map(super::AbsolutePath::new)
4193                .collect(),
4194            mcp_servers: mcp_servers.try_to_v2()?,
4195            replay_from: None,
4196            meta: meta.try_to_v2()?,
4197        })
4198    }
4199}
4200
4201impl TryToV1 for super::ResumeSessionResponse {
4202    type Output = crate::v1::ResumeSessionResponse;
4203
4204    fn try_to_v1(self) -> Result<Self::Output> {
4205        let Self {
4206            config_options,
4207            meta,
4208        } = self;
4209        Ok(crate::v1::ResumeSessionResponse {
4210            modes: None,
4211            config_options: Some(config_options.try_to_v1()?),
4212            meta: meta.try_to_v1()?,
4213        })
4214    }
4215}
4216
4217impl TryToV2 for crate::v1::ResumeSessionResponse {
4218    type Output = super::ResumeSessionResponse;
4219
4220    fn try_to_v2(self) -> Result<Self::Output> {
4221        let Self {
4222            modes,
4223            config_options,
4224            meta,
4225        } = self;
4226        if modes.is_some() {
4227            return Err(unrepresentable_v1_field("ResumeSessionResponse", "modes"));
4228        }
4229        Ok(super::ResumeSessionResponse {
4230            config_options: option_vec_into_v2_default(config_options)?,
4231            meta: meta.try_to_v2()?,
4232        })
4233    }
4234}
4235
4236impl TryToV1 for super::CloseSessionRequest {
4237    type Output = crate::v1::CloseSessionRequest;
4238
4239    fn try_to_v1(self) -> Result<Self::Output> {
4240        let Self { session_id, meta } = self;
4241        Ok(crate::v1::CloseSessionRequest {
4242            session_id: session_id.try_to_v1()?,
4243            meta: meta.try_to_v1()?,
4244        })
4245    }
4246}
4247
4248impl TryToV2 for crate::v1::CloseSessionRequest {
4249    type Output = super::CloseSessionRequest;
4250
4251    fn try_to_v2(self) -> Result<Self::Output> {
4252        let Self { session_id, meta } = self;
4253        Ok(super::CloseSessionRequest {
4254            session_id: session_id.try_to_v2()?,
4255            meta: meta.try_to_v2()?,
4256        })
4257    }
4258}
4259
4260impl TryToV1 for super::CloseSessionResponse {
4261    type Output = crate::v1::CloseSessionResponse;
4262
4263    fn try_to_v1(self) -> Result<Self::Output> {
4264        let Self { meta } = self;
4265        Ok(crate::v1::CloseSessionResponse {
4266            meta: meta.try_to_v1()?,
4267        })
4268    }
4269}
4270
4271impl TryToV2 for crate::v1::CloseSessionResponse {
4272    type Output = super::CloseSessionResponse;
4273
4274    fn try_to_v2(self) -> Result<Self::Output> {
4275        let Self { meta } = self;
4276        Ok(super::CloseSessionResponse {
4277            meta: meta.try_to_v2()?,
4278        })
4279    }
4280}
4281
4282impl TryToV1 for super::DeleteSessionRequest {
4283    type Output = crate::v1::DeleteSessionRequest;
4284
4285    fn try_to_v1(self) -> Result<Self::Output> {
4286        let Self { session_id, meta } = self;
4287        Ok(crate::v1::DeleteSessionRequest {
4288            session_id: session_id.try_to_v1()?,
4289            meta: meta.try_to_v1()?,
4290        })
4291    }
4292}
4293
4294impl TryToV2 for crate::v1::DeleteSessionRequest {
4295    type Output = super::DeleteSessionRequest;
4296
4297    fn try_to_v2(self) -> Result<Self::Output> {
4298        let Self { session_id, meta } = self;
4299        Ok(super::DeleteSessionRequest {
4300            session_id: session_id.try_to_v2()?,
4301            meta: meta.try_to_v2()?,
4302        })
4303    }
4304}
4305
4306impl TryToV1 for super::DeleteSessionResponse {
4307    type Output = crate::v1::DeleteSessionResponse;
4308
4309    fn try_to_v1(self) -> Result<Self::Output> {
4310        let Self { meta } = self;
4311        Ok(crate::v1::DeleteSessionResponse {
4312            meta: meta.try_to_v1()?,
4313        })
4314    }
4315}
4316
4317impl TryToV2 for crate::v1::DeleteSessionResponse {
4318    type Output = super::DeleteSessionResponse;
4319
4320    fn try_to_v2(self) -> Result<Self::Output> {
4321        let Self { meta } = self;
4322        Ok(super::DeleteSessionResponse {
4323            meta: meta.try_to_v2()?,
4324        })
4325    }
4326}
4327
4328impl TryToV1 for super::ListSessionsRequest {
4329    type Output = crate::v1::ListSessionsRequest;
4330
4331    fn try_to_v1(self) -> Result<Self::Output> {
4332        let Self { cwd, cursor, meta } = self;
4333        Ok(crate::v1::ListSessionsRequest {
4334            cwd: cwd.try_to_v1()?,
4335            cursor: cursor.try_to_v1()?,
4336            meta: meta.try_to_v1()?,
4337        })
4338    }
4339}
4340
4341impl TryToV2 for crate::v1::ListSessionsRequest {
4342    type Output = super::ListSessionsRequest;
4343
4344    fn try_to_v2(self) -> Result<Self::Output> {
4345        let Self { cwd, cursor, meta } = self;
4346        Ok(super::ListSessionsRequest {
4347            cwd: cwd.map(super::AbsolutePath::new),
4348            cursor: cursor.map(super::SessionListCursor::new),
4349            meta: meta.try_to_v2()?,
4350        })
4351    }
4352}
4353
4354impl TryToV1 for super::ListSessionsResponse {
4355    type Output = crate::v1::ListSessionsResponse;
4356
4357    fn try_to_v1(self) -> Result<Self::Output> {
4358        let Self {
4359            sessions,
4360            next_cursor,
4361            meta,
4362        } = self;
4363        Ok(crate::v1::ListSessionsResponse {
4364            sessions: sessions.try_to_v1()?,
4365            next_cursor: next_cursor.try_to_v1()?,
4366            meta: meta.try_to_v1()?,
4367        })
4368    }
4369}
4370
4371impl TryToV2 for crate::v1::ListSessionsResponse {
4372    type Output = super::ListSessionsResponse;
4373
4374    fn try_to_v2(self) -> Result<Self::Output> {
4375        let Self {
4376            sessions,
4377            next_cursor,
4378            meta,
4379        } = self;
4380        Ok(super::ListSessionsResponse {
4381            sessions: sessions.try_to_v2()?,
4382            next_cursor: next_cursor.map(super::SessionListCursor::new),
4383            meta: meta.try_to_v2()?,
4384        })
4385    }
4386}
4387
4388impl TryToV1 for super::SessionInfo {
4389    type Output = crate::v1::SessionInfo;
4390
4391    fn try_to_v1(self) -> Result<Self::Output> {
4392        let Self {
4393            session_id,
4394            cwd,
4395            additional_directories,
4396            title,
4397            updated_at,
4398            meta,
4399        } = self;
4400        Ok(crate::v1::SessionInfo {
4401            session_id: session_id.try_to_v1()?,
4402            cwd: cwd.try_to_v1()?,
4403            additional_directories: additional_directories.try_to_v1()?,
4404            title: title.try_to_v1()?,
4405            updated_at: updated_at.try_to_v1()?,
4406            meta: meta.try_to_v1()?,
4407        })
4408    }
4409}
4410
4411impl TryToV2 for crate::v1::SessionInfo {
4412    type Output = super::SessionInfo;
4413
4414    fn try_to_v2(self) -> Result<Self::Output> {
4415        let Self {
4416            session_id,
4417            cwd,
4418            additional_directories,
4419            title,
4420            updated_at,
4421            meta,
4422        } = self;
4423        Ok(super::SessionInfo {
4424            session_id: session_id.try_to_v2()?,
4425            cwd: super::AbsolutePath::new(cwd),
4426            additional_directories: additional_directories
4427                .into_iter()
4428                .map(super::AbsolutePath::new)
4429                .collect(),
4430            title: title.try_to_v2()?,
4431            updated_at: updated_at.try_to_v2()?,
4432            meta: meta.try_to_v2()?,
4433        })
4434    }
4435}
4436
4437impl TryToV1 for super::SessionConfigId {
4438    type Output = crate::v1::SessionConfigId;
4439
4440    fn try_to_v1(self) -> Result<Self::Output> {
4441        Ok(crate::v1::SessionConfigId(self.0.try_to_v1()?))
4442    }
4443}
4444
4445impl TryToV2 for crate::v1::SessionConfigId {
4446    type Output = super::SessionConfigId;
4447
4448    fn try_to_v2(self) -> Result<Self::Output> {
4449        Ok(super::SessionConfigId(self.0.try_to_v2()?))
4450    }
4451}
4452
4453impl TryToV1 for super::SessionConfigValueId {
4454    type Output = crate::v1::SessionConfigValueId;
4455
4456    fn try_to_v1(self) -> Result<Self::Output> {
4457        Ok(crate::v1::SessionConfigValueId(self.0.try_to_v1()?))
4458    }
4459}
4460
4461impl TryToV2 for crate::v1::SessionConfigValueId {
4462    type Output = super::SessionConfigValueId;
4463
4464    fn try_to_v2(self) -> Result<Self::Output> {
4465        Ok(super::SessionConfigValueId(self.0.try_to_v2()?))
4466    }
4467}
4468
4469impl TryToV1 for super::SessionConfigGroupId {
4470    type Output = crate::v1::SessionConfigGroupId;
4471
4472    fn try_to_v1(self) -> Result<Self::Output> {
4473        Ok(crate::v1::SessionConfigGroupId(self.0.try_to_v1()?))
4474    }
4475}
4476
4477impl TryToV2 for crate::v1::SessionConfigGroupId {
4478    type Output = super::SessionConfigGroupId;
4479
4480    fn try_to_v2(self) -> Result<Self::Output> {
4481        Ok(super::SessionConfigGroupId(self.0.try_to_v2()?))
4482    }
4483}
4484
4485impl TryToV1 for super::SessionConfigSelectOption {
4486    type Output = crate::v1::SessionConfigSelectOption;
4487
4488    fn try_to_v1(self) -> Result<Self::Output> {
4489        let Self {
4490            value,
4491            name,
4492            description,
4493            meta,
4494        } = self;
4495        Ok(crate::v1::SessionConfigSelectOption {
4496            value: value.try_to_v1()?,
4497            name: name.try_to_v1()?,
4498            description: description.try_to_v1()?,
4499            meta: meta.try_to_v1()?,
4500        })
4501    }
4502}
4503
4504impl TryToV2 for crate::v1::SessionConfigSelectOption {
4505    type Output = super::SessionConfigSelectOption;
4506
4507    fn try_to_v2(self) -> Result<Self::Output> {
4508        let Self {
4509            value,
4510            name,
4511            description,
4512            meta,
4513        } = self;
4514        Ok(super::SessionConfigSelectOption {
4515            value: value.try_to_v2()?,
4516            name: name.try_to_v2()?,
4517            description: description.try_to_v2()?,
4518            meta: meta.try_to_v2()?,
4519        })
4520    }
4521}
4522
4523impl TryToV1 for super::SessionConfigSelectGroup {
4524    type Output = crate::v1::SessionConfigSelectGroup;
4525
4526    fn try_to_v1(self) -> Result<Self::Output> {
4527        let Self {
4528            group_id,
4529            name,
4530            options,
4531            meta,
4532        } = self;
4533        Ok(crate::v1::SessionConfigSelectGroup {
4534            group: group_id.try_to_v1()?,
4535            name: name.try_to_v1()?,
4536            options: options.try_to_v1()?,
4537            meta: meta.try_to_v1()?,
4538        })
4539    }
4540}
4541
4542impl TryToV2 for crate::v1::SessionConfigSelectGroup {
4543    type Output = super::SessionConfigSelectGroup;
4544
4545    fn try_to_v2(self) -> Result<Self::Output> {
4546        let Self {
4547            group,
4548            name,
4549            options,
4550            meta,
4551        } = self;
4552        Ok(super::SessionConfigSelectGroup {
4553            group_id: group.try_to_v2()?,
4554            name: name.try_to_v2()?,
4555            options: options.try_to_v2()?,
4556            meta: meta.try_to_v2()?,
4557        })
4558    }
4559}
4560
4561impl TryToV1 for super::SessionConfigSelectOptions {
4562    type Output = crate::v1::SessionConfigSelectOptions;
4563
4564    fn try_to_v1(self) -> Result<Self::Output> {
4565        Ok(match self {
4566            Self::Ungrouped(value) => {
4567                crate::v1::SessionConfigSelectOptions::Ungrouped(value.try_to_v1()?)
4568            }
4569            Self::Grouped(value) => {
4570                crate::v1::SessionConfigSelectOptions::Grouped(value.try_to_v1()?)
4571            }
4572        })
4573    }
4574}
4575
4576impl TryToV2 for crate::v1::SessionConfigSelectOptions {
4577    type Output = super::SessionConfigSelectOptions;
4578
4579    fn try_to_v2(self) -> Result<Self::Output> {
4580        Ok(match self {
4581            Self::Ungrouped(value) => {
4582                super::SessionConfigSelectOptions::Ungrouped(value.try_to_v2()?)
4583            }
4584            Self::Grouped(value) => super::SessionConfigSelectOptions::Grouped(value.try_to_v2()?),
4585        })
4586    }
4587}
4588
4589impl TryToV1 for super::SessionConfigSelect {
4590    type Output = crate::v1::SessionConfigSelect;
4591
4592    fn try_to_v1(self) -> Result<Self::Output> {
4593        let Self {
4594            current_value,
4595            options,
4596        } = self;
4597        Ok(crate::v1::SessionConfigSelect {
4598            current_value: current_value.try_to_v1()?,
4599            options: options.try_to_v1()?,
4600        })
4601    }
4602}
4603
4604impl TryToV2 for crate::v1::SessionConfigSelect {
4605    type Output = super::SessionConfigSelect;
4606
4607    fn try_to_v2(self) -> Result<Self::Output> {
4608        let Self {
4609            current_value,
4610            options,
4611        } = self;
4612        Ok(super::SessionConfigSelect {
4613            current_value: current_value.try_to_v2()?,
4614            options: options.try_to_v2()?,
4615        })
4616    }
4617}
4618
4619impl TryToV1 for super::SessionConfigBoolean {
4620    type Output = crate::v1::SessionConfigBoolean;
4621
4622    fn try_to_v1(self) -> Result<Self::Output> {
4623        let Self { current_value } = self;
4624        Ok(crate::v1::SessionConfigBoolean {
4625            current_value: current_value.try_to_v1()?,
4626        })
4627    }
4628}
4629
4630impl TryToV2 for crate::v1::SessionConfigBoolean {
4631    type Output = super::SessionConfigBoolean;
4632
4633    fn try_to_v2(self) -> Result<Self::Output> {
4634        let Self { current_value } = self;
4635        Ok(super::SessionConfigBoolean {
4636            current_value: current_value.try_to_v2()?,
4637        })
4638    }
4639}
4640
4641impl TryToV1 for super::SessionConfigOptionCategory {
4642    type Output = crate::v1::SessionConfigOptionCategory;
4643
4644    fn try_to_v1(self) -> Result<Self::Output> {
4645        Ok(match self {
4646            Self::Mode => crate::v1::SessionConfigOptionCategory::Mode,
4647            Self::Model => crate::v1::SessionConfigOptionCategory::Model,
4648            Self::ModelConfig => crate::v1::SessionConfigOptionCategory::ModelConfig,
4649            Self::ThoughtLevel => crate::v1::SessionConfigOptionCategory::ThoughtLevel,
4650            Self::Other(value) => crate::v1::SessionConfigOptionCategory::Other(value.try_to_v1()?),
4651        })
4652    }
4653}
4654
4655impl TryToV2 for crate::v1::SessionConfigOptionCategory {
4656    type Output = super::SessionConfigOptionCategory;
4657
4658    fn try_to_v2(self) -> Result<Self::Output> {
4659        Ok(match self {
4660            Self::Mode => super::SessionConfigOptionCategory::Mode,
4661            Self::Model => super::SessionConfigOptionCategory::Model,
4662            Self::ModelConfig => super::SessionConfigOptionCategory::ModelConfig,
4663            Self::ThoughtLevel => super::SessionConfigOptionCategory::ThoughtLevel,
4664            Self::Other(value) => super::SessionConfigOptionCategory::Other(value.try_to_v2()?),
4665        })
4666    }
4667}
4668
4669impl TryToV1 for super::SessionConfigKind {
4670    type Output = crate::v1::SessionConfigKind;
4671
4672    fn try_to_v1(self) -> Result<Self::Output> {
4673        Ok(match self {
4674            Self::Select(value) => crate::v1::SessionConfigKind::Select(value.try_to_v1()?),
4675            Self::Boolean(value) => crate::v1::SessionConfigKind::Boolean(value.try_to_v1()?),
4676            Self::Other(value) => {
4677                return Err(unknown_v2_enum_variant("SessionConfigKind", &value.type_));
4678            }
4679        })
4680    }
4681}
4682
4683impl TryToV2 for crate::v1::SessionConfigKind {
4684    type Output = super::SessionConfigKind;
4685
4686    fn try_to_v2(self) -> Result<Self::Output> {
4687        Ok(match self {
4688            Self::Select(value) => super::SessionConfigKind::Select(value.try_to_v2()?),
4689            Self::Boolean(value) => super::SessionConfigKind::Boolean(value.try_to_v2()?),
4690        })
4691    }
4692}
4693
4694impl TryToV1 for super::SessionConfigOption {
4695    type Output = crate::v1::SessionConfigOption;
4696
4697    fn try_to_v1(self) -> Result<Self::Output> {
4698        let Self {
4699            config_id,
4700            name,
4701            description,
4702            category,
4703            kind,
4704            meta,
4705        } = self;
4706        Ok(crate::v1::SessionConfigOption {
4707            id: config_id.try_to_v1()?,
4708            name: name.try_to_v1()?,
4709            description: description.try_to_v1()?,
4710            category: category.try_to_v1()?,
4711            kind: kind.try_to_v1()?,
4712            meta: meta.try_to_v1()?,
4713        })
4714    }
4715}
4716
4717impl TryToV2 for crate::v1::SessionConfigOption {
4718    type Output = super::SessionConfigOption;
4719
4720    fn try_to_v2(self) -> Result<Self::Output> {
4721        let Self {
4722            id,
4723            name,
4724            description,
4725            category,
4726            kind,
4727            meta,
4728        } = self;
4729        Ok(super::SessionConfigOption {
4730            config_id: id.try_to_v2()?,
4731            name: name.try_to_v2()?,
4732            description: description.try_to_v2()?,
4733            category: category.try_to_v2()?,
4734            kind: kind.try_to_v2()?,
4735            meta: meta.try_to_v2()?,
4736        })
4737    }
4738}
4739
4740impl TryToV1 for super::SessionConfigOptionValue {
4741    type Output = crate::v1::SessionConfigOptionValue;
4742
4743    fn try_to_v1(self) -> Result<Self::Output> {
4744        Ok(match self {
4745            Self::Id { value } => crate::v1::SessionConfigOptionValue::ValueId {
4746                value: value.try_to_v1()?,
4747            },
4748            Self::Boolean { value } => crate::v1::SessionConfigOptionValue::Boolean {
4749                value: value.try_to_v1()?,
4750            },
4751            Self::Other(value) => {
4752                return Err(unknown_v2_enum_variant(
4753                    "SessionConfigOptionValue",
4754                    &value.type_,
4755                ));
4756            }
4757        })
4758    }
4759}
4760
4761impl TryToV2 for crate::v1::SessionConfigOptionValue {
4762    type Output = super::SessionConfigOptionValue;
4763
4764    fn try_to_v2(self) -> Result<Self::Output> {
4765        Ok(match self {
4766            Self::Boolean { value } => super::SessionConfigOptionValue::Boolean {
4767                value: value.try_to_v2()?,
4768            },
4769            Self::ValueId { value } => super::SessionConfigOptionValue::Id {
4770                value: value.try_to_v2()?,
4771            },
4772        })
4773    }
4774}
4775
4776impl TryToV1 for super::SetSessionConfigOptionRequest {
4777    type Output = crate::v1::SetSessionConfigOptionRequest;
4778
4779    fn try_to_v1(self) -> Result<Self::Output> {
4780        let Self {
4781            session_id,
4782            config_id,
4783            value,
4784            meta,
4785        } = self;
4786        Ok(crate::v1::SetSessionConfigOptionRequest {
4787            session_id: session_id.try_to_v1()?,
4788            config_id: config_id.try_to_v1()?,
4789            value: value.try_to_v1()?,
4790            meta: meta.try_to_v1()?,
4791        })
4792    }
4793}
4794
4795impl TryToV2 for crate::v1::SetSessionConfigOptionRequest {
4796    type Output = super::SetSessionConfigOptionRequest;
4797
4798    fn try_to_v2(self) -> Result<Self::Output> {
4799        let Self {
4800            session_id,
4801            config_id,
4802            value,
4803            meta,
4804        } = self;
4805        Ok(super::SetSessionConfigOptionRequest {
4806            session_id: session_id.try_to_v2()?,
4807            config_id: config_id.try_to_v2()?,
4808            value: value.try_to_v2()?,
4809            meta: meta.try_to_v2()?,
4810        })
4811    }
4812}
4813
4814impl TryToV1 for super::SetSessionConfigOptionResponse {
4815    type Output = crate::v1::SetSessionConfigOptionResponse;
4816
4817    fn try_to_v1(self) -> Result<Self::Output> {
4818        let Self {
4819            config_options,
4820            meta,
4821        } = self;
4822        Ok(crate::v1::SetSessionConfigOptionResponse {
4823            config_options: config_options.try_to_v1()?,
4824            meta: meta.try_to_v1()?,
4825        })
4826    }
4827}
4828
4829impl TryToV2 for crate::v1::SetSessionConfigOptionResponse {
4830    type Output = super::SetSessionConfigOptionResponse;
4831
4832    fn try_to_v2(self) -> Result<Self::Output> {
4833        let Self {
4834            config_options,
4835            meta,
4836        } = self;
4837        Ok(super::SetSessionConfigOptionResponse {
4838            config_options: config_options.try_to_v2()?,
4839            meta: meta.try_to_v2()?,
4840        })
4841    }
4842}
4843
4844impl TryToV1 for super::McpServer {
4845    type Output = crate::v1::McpServer;
4846
4847    fn try_to_v1(self) -> Result<Self::Output> {
4848        Ok(match self {
4849            Self::Http(value) => crate::v1::McpServer::Http(value.try_to_v1()?),
4850            #[cfg(feature = "unstable_mcp_over_acp")]
4851            Self::Acp(value) => crate::v1::McpServer::Acp(value.try_to_v1()?),
4852            Self::Stdio(value) => crate::v1::McpServer::Stdio(value.try_to_v1()?),
4853            Self::Other(value) => return Err(unknown_v2_enum_variant("McpServer", &value.type_)),
4854        })
4855    }
4856}
4857
4858impl TryToV2 for crate::v1::McpServer {
4859    type Output = super::McpServer;
4860
4861    fn try_to_v2(self) -> Result<Self::Output> {
4862        Ok(match self {
4863            Self::Http(value) => super::McpServer::Http(value.try_to_v2()?),
4864            Self::Sse(_) => return Err(removed_v1_enum_variant("McpServer", "sse")),
4865            #[cfg(feature = "unstable_mcp_over_acp")]
4866            Self::Acp(value) => super::McpServer::Acp(value.try_to_v2()?),
4867            Self::Stdio(value) => super::McpServer::Stdio(value.try_to_v2()?),
4868        })
4869    }
4870}
4871
4872impl TryToV1 for super::McpServerHttp {
4873    type Output = crate::v1::McpServerHttp;
4874
4875    fn try_to_v1(self) -> Result<Self::Output> {
4876        let Self {
4877            name,
4878            url,
4879            headers,
4880            meta,
4881        } = self;
4882        Ok(crate::v1::McpServerHttp {
4883            name: name.try_to_v1()?,
4884            url: url.try_to_v1()?,
4885            headers: headers.try_to_v1()?,
4886            meta: meta.try_to_v1()?,
4887        })
4888    }
4889}
4890
4891impl TryToV2 for crate::v1::McpServerHttp {
4892    type Output = super::McpServerHttp;
4893
4894    fn try_to_v2(self) -> Result<Self::Output> {
4895        let Self {
4896            name,
4897            url,
4898            headers,
4899            meta,
4900        } = self;
4901        Ok(super::McpServerHttp {
4902            name: name.try_to_v2()?,
4903            url: url.try_to_v2()?,
4904            headers: headers.try_to_v2()?,
4905            meta: meta.try_to_v2()?,
4906        })
4907    }
4908}
4909
4910#[cfg(feature = "unstable_mcp_over_acp")]
4911impl TryToV1 for super::McpServerAcpId {
4912    type Output = crate::v1::McpServerAcpId;
4913
4914    fn try_to_v1(self) -> Result<Self::Output> {
4915        Ok(crate::v1::McpServerAcpId(self.0.try_to_v1()?))
4916    }
4917}
4918
4919#[cfg(feature = "unstable_mcp_over_acp")]
4920impl TryToV2 for crate::v1::McpServerAcpId {
4921    type Output = super::McpServerAcpId;
4922
4923    fn try_to_v2(self) -> Result<Self::Output> {
4924        Ok(super::McpServerAcpId(self.0.try_to_v2()?))
4925    }
4926}
4927
4928#[cfg(feature = "unstable_mcp_over_acp")]
4929impl TryToV1 for super::McpConnectionId {
4930    type Output = crate::v1::McpConnectionId;
4931
4932    fn try_to_v1(self) -> Result<Self::Output> {
4933        Ok(crate::v1::McpConnectionId(self.0.try_to_v1()?))
4934    }
4935}
4936
4937#[cfg(feature = "unstable_mcp_over_acp")]
4938impl TryToV2 for crate::v1::McpConnectionId {
4939    type Output = super::McpConnectionId;
4940
4941    fn try_to_v2(self) -> Result<Self::Output> {
4942        Ok(super::McpConnectionId(self.0.try_to_v2()?))
4943    }
4944}
4945
4946#[cfg(feature = "unstable_mcp_over_acp")]
4947impl TryToV1 for super::McpServerAcp {
4948    type Output = crate::v1::McpServerAcp;
4949
4950    fn try_to_v1(self) -> Result<Self::Output> {
4951        let Self {
4952            name,
4953            server_id,
4954            meta,
4955        } = self;
4956        Ok(crate::v1::McpServerAcp {
4957            name: name.try_to_v1()?,
4958            server_id: server_id.try_to_v1()?,
4959            meta: meta.try_to_v1()?,
4960        })
4961    }
4962}
4963
4964#[cfg(feature = "unstable_mcp_over_acp")]
4965impl TryToV2 for crate::v1::McpServerAcp {
4966    type Output = super::McpServerAcp;
4967
4968    fn try_to_v2(self) -> Result<Self::Output> {
4969        let Self {
4970            name,
4971            server_id,
4972            meta,
4973        } = self;
4974        Ok(super::McpServerAcp {
4975            name: name.try_to_v2()?,
4976            server_id: server_id.try_to_v2()?,
4977            meta: meta.try_to_v2()?,
4978        })
4979    }
4980}
4981
4982impl TryToV1 for super::McpServerStdio {
4983    type Output = crate::v1::McpServerStdio;
4984
4985    fn try_to_v1(self) -> Result<Self::Output> {
4986        let Self {
4987            name,
4988            command,
4989            args,
4990            env,
4991            meta,
4992        } = self;
4993        Ok(crate::v1::McpServerStdio {
4994            name: name.try_to_v1()?,
4995            command: command.try_to_v1()?,
4996            args: args.try_to_v1()?,
4997            env: env.try_to_v1()?,
4998            meta: meta.try_to_v1()?,
4999        })
5000    }
5001}
5002
5003impl TryToV2 for crate::v1::McpServerStdio {
5004    type Output = super::McpServerStdio;
5005
5006    fn try_to_v2(self) -> Result<Self::Output> {
5007        let Self {
5008            name,
5009            command,
5010            args,
5011            env,
5012            meta,
5013        } = self;
5014        Ok(super::McpServerStdio {
5015            name: name.try_to_v2()?,
5016            command: super::AbsolutePath::new(command),
5017            args: args.try_to_v2()?,
5018            env: env.try_to_v2()?,
5019            meta: meta.try_to_v2()?,
5020        })
5021    }
5022}
5023
5024impl TryToV1 for super::EnvVariable {
5025    type Output = crate::v1::EnvVariable;
5026
5027    fn try_to_v1(self) -> Result<Self::Output> {
5028        let Self { name, value, meta } = self;
5029        Ok(crate::v1::EnvVariable {
5030            name: name.try_to_v1()?,
5031            value: value.try_to_v1()?,
5032            meta: meta.try_to_v1()?,
5033        })
5034    }
5035}
5036
5037impl TryToV2 for crate::v1::EnvVariable {
5038    type Output = super::EnvVariable;
5039
5040    fn try_to_v2(self) -> Result<Self::Output> {
5041        let Self { name, value, meta } = self;
5042        Ok(super::EnvVariable {
5043            name: name.try_to_v2()?,
5044            value: value.try_to_v2()?,
5045            meta: meta.try_to_v2()?,
5046        })
5047    }
5048}
5049
5050impl TryToV1 for super::HttpHeader {
5051    type Output = crate::v1::HttpHeader;
5052
5053    fn try_to_v1(self) -> Result<Self::Output> {
5054        let Self { name, value, meta } = self;
5055        Ok(crate::v1::HttpHeader {
5056            name: name.try_to_v1()?,
5057            value: value.try_to_v1()?,
5058            meta: meta.try_to_v1()?,
5059        })
5060    }
5061}
5062
5063impl TryToV2 for crate::v1::HttpHeader {
5064    type Output = super::HttpHeader;
5065
5066    fn try_to_v2(self) -> Result<Self::Output> {
5067        let Self { name, value, meta } = self;
5068        Ok(super::HttpHeader {
5069            name: name.try_to_v2()?,
5070            value: value.try_to_v2()?,
5071            meta: meta.try_to_v2()?,
5072        })
5073    }
5074}
5075
5076impl TryToV1 for super::PromptRequest {
5077    type Output = crate::v1::PromptRequest;
5078
5079    fn try_to_v1(self) -> Result<Self::Output> {
5080        let Self {
5081            session_id,
5082            prompt,
5083            meta,
5084        } = self;
5085        Ok(crate::v1::PromptRequest {
5086            session_id: session_id.try_to_v1()?,
5087            prompt: prompt.try_to_v1()?,
5088            meta: meta.try_to_v1()?,
5089        })
5090    }
5091}
5092
5093impl TryToV2 for crate::v1::PromptRequest {
5094    type Output = super::PromptRequest;
5095
5096    fn try_to_v2(self) -> Result<Self::Output> {
5097        let Self {
5098            session_id,
5099            prompt,
5100            meta,
5101        } = self;
5102        Ok(super::PromptRequest {
5103            session_id: session_id.try_to_v2()?,
5104            prompt: prompt.try_to_v2()?,
5105            meta: meta.try_to_v2()?,
5106        })
5107    }
5108}
5109
5110impl TryToV1 for super::PromptResponse {
5111    type Output = crate::v1::PromptResponse;
5112
5113    fn try_to_v1(self) -> Result<Self::Output> {
5114        Err(ProtocolConversionError::new(
5115            "v2 PromptResponse cannot be represented in v1 because v2 reports completion with state_update session updates",
5116        ))
5117    }
5118}
5119
5120impl TryToV2 for crate::v1::PromptResponse {
5121    type Output = super::PromptResponse;
5122
5123    fn try_to_v2(self) -> Result<Self::Output> {
5124        Err(ProtocolConversionError::new(
5125            "v1 PromptResponse cannot be represented in v2 by itself because v2 reports completion with state_update session updates",
5126        ))
5127    }
5128}
5129
5130impl TryToV1 for super::StopReason {
5131    type Output = crate::v1::StopReason;
5132
5133    fn try_to_v1(self) -> Result<Self::Output> {
5134        Ok(match self {
5135            Self::EndTurn => crate::v1::StopReason::EndTurn,
5136            Self::MaxTokens => crate::v1::StopReason::MaxTokens,
5137            Self::MaxTurnRequests => crate::v1::StopReason::MaxTurnRequests,
5138            Self::Refusal => crate::v1::StopReason::Refusal,
5139            Self::Cancelled => crate::v1::StopReason::Cancelled,
5140            Self::Other(value) => return Err(unknown_v2_enum_variant("StopReason", &value)),
5141        })
5142    }
5143}
5144
5145impl TryToV2 for crate::v1::StopReason {
5146    type Output = super::StopReason;
5147
5148    fn try_to_v2(self) -> Result<Self::Output> {
5149        Ok(match self {
5150            Self::EndTurn => super::StopReason::EndTurn,
5151            Self::MaxTokens => super::StopReason::MaxTokens,
5152            Self::MaxTurnRequests => super::StopReason::MaxTurnRequests,
5153            Self::Refusal => super::StopReason::Refusal,
5154            Self::Cancelled => super::StopReason::Cancelled,
5155        })
5156    }
5157}
5158
5159#[cfg(feature = "unstable_end_turn_token_usage")]
5160impl TryToV1 for super::Usage {
5161    type Output = crate::v1::Usage;
5162
5163    fn try_to_v1(self) -> Result<Self::Output> {
5164        let Self {
5165            total_tokens,
5166            input_tokens,
5167            output_tokens,
5168            thought_tokens,
5169            cached_read_tokens,
5170            cached_write_tokens,
5171            meta,
5172        } = self;
5173        Ok(crate::v1::Usage {
5174            total_tokens: total_tokens.try_to_v1()?,
5175            input_tokens: input_tokens.try_to_v1()?,
5176            output_tokens: output_tokens.try_to_v1()?,
5177            thought_tokens: thought_tokens.try_to_v1()?,
5178            cached_read_tokens: cached_read_tokens.try_to_v1()?,
5179            cached_write_tokens: cached_write_tokens.try_to_v1()?,
5180            meta: meta.try_to_v1()?,
5181        })
5182    }
5183}
5184
5185#[cfg(feature = "unstable_end_turn_token_usage")]
5186impl TryToV2 for crate::v1::Usage {
5187    type Output = super::Usage;
5188
5189    fn try_to_v2(self) -> Result<Self::Output> {
5190        let Self {
5191            total_tokens,
5192            input_tokens,
5193            output_tokens,
5194            thought_tokens,
5195            cached_read_tokens,
5196            cached_write_tokens,
5197            meta,
5198        } = self;
5199        Ok(super::Usage {
5200            total_tokens: total_tokens.try_to_v2()?,
5201            input_tokens: input_tokens.try_to_v2()?,
5202            output_tokens: output_tokens.try_to_v2()?,
5203            thought_tokens: thought_tokens.try_to_v2()?,
5204            cached_read_tokens: cached_read_tokens.try_to_v2()?,
5205            cached_write_tokens: cached_write_tokens.try_to_v2()?,
5206            meta: meta.try_to_v2()?,
5207        })
5208    }
5209}
5210
5211#[cfg(feature = "unstable_llm_providers")]
5212impl TryToV1 for super::LlmProtocol {
5213    type Output = crate::v1::LlmProtocol;
5214
5215    fn try_to_v1(self) -> Result<Self::Output> {
5216        Ok(match self {
5217            Self::Anthropic => crate::v1::LlmProtocol::Anthropic,
5218            Self::OpenAi => crate::v1::LlmProtocol::OpenAi,
5219            Self::Azure => crate::v1::LlmProtocol::Azure,
5220            Self::Vertex => crate::v1::LlmProtocol::Vertex,
5221            Self::Bedrock => crate::v1::LlmProtocol::Bedrock,
5222            Self::Other(value) => crate::v1::LlmProtocol::Other(value.try_to_v1()?),
5223        })
5224    }
5225}
5226
5227#[cfg(feature = "unstable_llm_providers")]
5228impl TryToV2 for crate::v1::LlmProtocol {
5229    type Output = super::LlmProtocol;
5230
5231    fn try_to_v2(self) -> Result<Self::Output> {
5232        Ok(match self {
5233            Self::Anthropic => super::LlmProtocol::Anthropic,
5234            Self::OpenAi => super::LlmProtocol::OpenAi,
5235            Self::Azure => super::LlmProtocol::Azure,
5236            Self::Vertex => super::LlmProtocol::Vertex,
5237            Self::Bedrock => super::LlmProtocol::Bedrock,
5238            Self::Other(value) => super::LlmProtocol::Other(value.try_to_v2()?),
5239        })
5240    }
5241}
5242
5243#[cfg(feature = "unstable_llm_providers")]
5244impl TryToV1 for super::ProviderCurrentConfig {
5245    type Output = crate::v1::ProviderCurrentConfig;
5246
5247    fn try_to_v1(self) -> Result<Self::Output> {
5248        let Self {
5249            api_type,
5250            base_url,
5251            meta,
5252        } = self;
5253        Ok(crate::v1::ProviderCurrentConfig {
5254            api_type: api_type.try_to_v1()?,
5255            base_url: base_url.try_to_v1()?,
5256            meta: meta.try_to_v1()?,
5257        })
5258    }
5259}
5260
5261#[cfg(feature = "unstable_llm_providers")]
5262impl TryToV2 for crate::v1::ProviderCurrentConfig {
5263    type Output = super::ProviderCurrentConfig;
5264
5265    fn try_to_v2(self) -> Result<Self::Output> {
5266        let Self {
5267            api_type,
5268            base_url,
5269            meta,
5270        } = self;
5271        Ok(super::ProviderCurrentConfig {
5272            api_type: api_type.try_to_v2()?,
5273            base_url: base_url.try_to_v2()?,
5274            meta: meta.try_to_v2()?,
5275        })
5276    }
5277}
5278
5279#[cfg(feature = "unstable_llm_providers")]
5280impl TryToV1 for super::ProviderId {
5281    type Output = crate::v1::ProviderId;
5282
5283    fn try_to_v1(self) -> Result<Self::Output> {
5284        Ok(crate::v1::ProviderId(self.0.try_to_v1()?))
5285    }
5286}
5287
5288#[cfg(feature = "unstable_llm_providers")]
5289impl TryToV2 for crate::v1::ProviderId {
5290    type Output = super::ProviderId;
5291
5292    fn try_to_v2(self) -> Result<Self::Output> {
5293        Ok(super::ProviderId(self.0.try_to_v2()?))
5294    }
5295}
5296
5297#[cfg(feature = "unstable_llm_providers")]
5298impl TryToV1 for super::ProviderInfo {
5299    type Output = crate::v1::ProviderInfo;
5300
5301    fn try_to_v1(self) -> Result<Self::Output> {
5302        let Self {
5303            provider_id,
5304            supported,
5305            required,
5306            current,
5307            meta,
5308        } = self;
5309        Ok(crate::v1::ProviderInfo {
5310            provider_id: provider_id.try_to_v1()?,
5311            supported: supported.try_to_v1()?,
5312            required: required.try_to_v1()?,
5313            current: current.try_to_v1()?,
5314            meta: meta.try_to_v1()?,
5315        })
5316    }
5317}
5318
5319#[cfg(feature = "unstable_llm_providers")]
5320impl TryToV2 for crate::v1::ProviderInfo {
5321    type Output = super::ProviderInfo;
5322
5323    fn try_to_v2(self) -> Result<Self::Output> {
5324        let Self {
5325            provider_id,
5326            supported,
5327            required,
5328            current,
5329            meta,
5330        } = self;
5331        Ok(super::ProviderInfo {
5332            provider_id: provider_id.try_to_v2()?,
5333            supported: supported.try_to_v2()?,
5334            required: required.try_to_v2()?,
5335            current: current.try_to_v2()?,
5336            meta: meta.try_to_v2()?,
5337        })
5338    }
5339}
5340
5341#[cfg(feature = "unstable_llm_providers")]
5342impl TryToV1 for super::ListProvidersRequest {
5343    type Output = crate::v1::ListProvidersRequest;
5344
5345    fn try_to_v1(self) -> Result<Self::Output> {
5346        let Self { meta } = self;
5347        Ok(crate::v1::ListProvidersRequest {
5348            meta: meta.try_to_v1()?,
5349        })
5350    }
5351}
5352
5353#[cfg(feature = "unstable_llm_providers")]
5354impl TryToV2 for crate::v1::ListProvidersRequest {
5355    type Output = super::ListProvidersRequest;
5356
5357    fn try_to_v2(self) -> Result<Self::Output> {
5358        let Self { meta } = self;
5359        Ok(super::ListProvidersRequest {
5360            meta: meta.try_to_v2()?,
5361        })
5362    }
5363}
5364
5365#[cfg(feature = "unstable_llm_providers")]
5366impl TryToV1 for super::ListProvidersResponse {
5367    type Output = crate::v1::ListProvidersResponse;
5368
5369    fn try_to_v1(self) -> Result<Self::Output> {
5370        let Self { providers, meta } = self;
5371        Ok(crate::v1::ListProvidersResponse {
5372            providers: providers.try_to_v1()?,
5373            meta: meta.try_to_v1()?,
5374        })
5375    }
5376}
5377
5378#[cfg(feature = "unstable_llm_providers")]
5379impl TryToV2 for crate::v1::ListProvidersResponse {
5380    type Output = super::ListProvidersResponse;
5381
5382    fn try_to_v2(self) -> Result<Self::Output> {
5383        let Self { providers, meta } = self;
5384        Ok(super::ListProvidersResponse {
5385            providers: providers.try_to_v2()?,
5386            meta: meta.try_to_v2()?,
5387        })
5388    }
5389}
5390
5391#[cfg(feature = "unstable_llm_providers")]
5392impl TryToV1 for super::SetProviderRequest {
5393    type Output = crate::v1::SetProviderRequest;
5394
5395    fn try_to_v1(self) -> Result<Self::Output> {
5396        let Self {
5397            provider_id,
5398            api_type,
5399            base_url,
5400            headers,
5401            meta,
5402        } = self;
5403        Ok(crate::v1::SetProviderRequest {
5404            provider_id: provider_id.try_to_v1()?,
5405            api_type: api_type.try_to_v1()?,
5406            base_url: base_url.try_to_v1()?,
5407            headers: headers.try_to_v1()?,
5408            meta: meta.try_to_v1()?,
5409        })
5410    }
5411}
5412
5413#[cfg(feature = "unstable_llm_providers")]
5414impl TryToV2 for crate::v1::SetProviderRequest {
5415    type Output = super::SetProviderRequest;
5416
5417    fn try_to_v2(self) -> Result<Self::Output> {
5418        let Self {
5419            provider_id,
5420            api_type,
5421            base_url,
5422            headers,
5423            meta,
5424        } = self;
5425        Ok(super::SetProviderRequest {
5426            provider_id: provider_id.try_to_v2()?,
5427            api_type: api_type.try_to_v2()?,
5428            base_url: base_url.try_to_v2()?,
5429            headers: headers.try_to_v2()?,
5430            meta: meta.try_to_v2()?,
5431        })
5432    }
5433}
5434
5435#[cfg(feature = "unstable_llm_providers")]
5436impl TryToV1 for super::SetProviderResponse {
5437    type Output = crate::v1::SetProviderResponse;
5438
5439    fn try_to_v1(self) -> Result<Self::Output> {
5440        let Self { meta } = self;
5441        Ok(crate::v1::SetProviderResponse {
5442            meta: meta.try_to_v1()?,
5443        })
5444    }
5445}
5446
5447#[cfg(feature = "unstable_llm_providers")]
5448impl TryToV2 for crate::v1::SetProviderResponse {
5449    type Output = super::SetProviderResponse;
5450
5451    fn try_to_v2(self) -> Result<Self::Output> {
5452        let Self { meta } = self;
5453        Ok(super::SetProviderResponse {
5454            meta: meta.try_to_v2()?,
5455        })
5456    }
5457}
5458
5459#[cfg(feature = "unstable_llm_providers")]
5460impl TryToV1 for super::DisableProviderRequest {
5461    type Output = crate::v1::DisableProviderRequest;
5462
5463    fn try_to_v1(self) -> Result<Self::Output> {
5464        let Self { provider_id, meta } = self;
5465        Ok(crate::v1::DisableProviderRequest {
5466            provider_id: provider_id.try_to_v1()?,
5467            meta: meta.try_to_v1()?,
5468        })
5469    }
5470}
5471
5472#[cfg(feature = "unstable_llm_providers")]
5473impl TryToV2 for crate::v1::DisableProviderRequest {
5474    type Output = super::DisableProviderRequest;
5475
5476    fn try_to_v2(self) -> Result<Self::Output> {
5477        let Self { provider_id, meta } = self;
5478        Ok(super::DisableProviderRequest {
5479            provider_id: provider_id.try_to_v2()?,
5480            meta: meta.try_to_v2()?,
5481        })
5482    }
5483}
5484
5485#[cfg(feature = "unstable_llm_providers")]
5486impl TryToV1 for super::DisableProviderResponse {
5487    type Output = crate::v1::DisableProviderResponse;
5488
5489    fn try_to_v1(self) -> Result<Self::Output> {
5490        let Self { meta } = self;
5491        Ok(crate::v1::DisableProviderResponse {
5492            meta: meta.try_to_v1()?,
5493        })
5494    }
5495}
5496
5497#[cfg(feature = "unstable_llm_providers")]
5498impl TryToV2 for crate::v1::DisableProviderResponse {
5499    type Output = super::DisableProviderResponse;
5500
5501    fn try_to_v2(self) -> Result<Self::Output> {
5502        let Self { meta } = self;
5503        Ok(super::DisableProviderResponse {
5504            meta: meta.try_to_v2()?,
5505        })
5506    }
5507}
5508
5509impl TryToV1 for super::AgentCapabilities {
5510    type Output = crate::v1::AgentCapabilities;
5511
5512    fn try_to_v1(self) -> Result<Self::Output> {
5513        let Self {
5514            session,
5515            auth,
5516            #[cfg(feature = "unstable_llm_providers")]
5517            providers,
5518            #[cfg(feature = "unstable_nes")]
5519            nes,
5520            #[cfg(feature = "unstable_nes")]
5521            position_encoding,
5522            meta,
5523        } = self;
5524        let Some(session) = session else {
5525            return Err(ProtocolConversionError::new(
5526                "v2 AgentCapabilities without `session` cannot be represented in v1",
5527            ));
5528        };
5529        let V1SessionCapabilityParts {
5530            session_capabilities,
5531            prompt_capabilities,
5532            load_session,
5533            mcp_capabilities,
5534        } = session.try_into_v1_parts()?;
5535
5536        Ok(crate::v1::AgentCapabilities {
5537            load_session: load_session.try_to_v1()?,
5538            prompt_capabilities,
5539            mcp_capabilities,
5540            session_capabilities,
5541            auth: auth
5542                .map(TryToV1::try_to_v1)
5543                .transpose()?
5544                .unwrap_or_default(),
5545            #[cfg(feature = "unstable_llm_providers")]
5546            providers: providers.try_to_v1()?,
5547            #[cfg(feature = "unstable_nes")]
5548            nes: nes.try_to_v1()?,
5549            #[cfg(feature = "unstable_nes")]
5550            position_encoding: position_encoding.try_to_v1()?,
5551            meta: meta.try_to_v1()?,
5552        })
5553    }
5554}
5555
5556impl TryToV2 for crate::v1::AgentCapabilities {
5557    type Output = super::AgentCapabilities;
5558
5559    fn try_to_v2(self) -> Result<Self::Output> {
5560        let Self {
5561            load_session,
5562            prompt_capabilities,
5563            mcp_capabilities,
5564            session_capabilities,
5565            auth,
5566            #[cfg(feature = "unstable_llm_providers")]
5567            providers,
5568            #[cfg(feature = "unstable_nes")]
5569            nes,
5570            #[cfg(feature = "unstable_nes")]
5571            position_encoding,
5572            meta,
5573        } = self;
5574        let session = super::SessionCapabilities::from_v1(
5575            session_capabilities,
5576            prompt_capabilities,
5577            load_session,
5578            mcp_capabilities,
5579        )?;
5580
5581        Ok(super::AgentCapabilities {
5582            session: Some(session),
5583            auth: v1_agent_auth_capabilities_into_v2_option(auth)?,
5584            #[cfg(feature = "unstable_llm_providers")]
5585            providers: providers.try_to_v2()?,
5586            #[cfg(feature = "unstable_nes")]
5587            nes: nes.try_to_v2()?,
5588            #[cfg(feature = "unstable_nes")]
5589            position_encoding: position_encoding.try_to_v2()?,
5590            meta: meta.try_to_v2()?,
5591        })
5592    }
5593}
5594
5595#[cfg(feature = "unstable_llm_providers")]
5596impl TryToV1 for super::ProvidersCapabilities {
5597    type Output = crate::v1::ProvidersCapabilities;
5598
5599    fn try_to_v1(self) -> Result<Self::Output> {
5600        let Self { meta } = self;
5601        Ok(crate::v1::ProvidersCapabilities {
5602            meta: meta.try_to_v1()?,
5603        })
5604    }
5605}
5606
5607#[cfg(feature = "unstable_llm_providers")]
5608impl TryToV2 for crate::v1::ProvidersCapabilities {
5609    type Output = super::ProvidersCapabilities;
5610
5611    fn try_to_v2(self) -> Result<Self::Output> {
5612        let Self { meta } = self;
5613        Ok(super::ProvidersCapabilities {
5614            meta: meta.try_to_v2()?,
5615        })
5616    }
5617}
5618
5619/// The v1 capability fields represented by v2 `SessionCapabilities`.
5620#[derive(Debug, Clone, PartialEq, Eq)]
5621#[non_exhaustive]
5622pub struct V1SessionCapabilityParts {
5623    /// Session-specific v1 capabilities.
5624    pub session_capabilities: crate::v1::SessionCapabilities,
5625    /// Prompt capabilities for v1 `session/prompt` requests.
5626    pub prompt_capabilities: crate::v1::PromptCapabilities,
5627    /// Whether v1 `session/load` is supported.
5628    pub load_session: bool,
5629    /// MCP capabilities for v1 session lifecycle requests.
5630    pub mcp_capabilities: crate::v1::McpCapabilities,
5631}
5632
5633impl super::SessionCapabilities {
5634    /// Splits v2 session capabilities into the v1 agent capability fields that
5635    /// v2 groups under `session`.
5636    ///
5637    /// This is useful when shared internal capability construction produces a
5638    /// v2 [`SessionCapabilities`](super::SessionCapabilities) value but a v1
5639    /// implementation still needs the corresponding top-level v1 fields.
5640    ///
5641    /// # Errors
5642    ///
5643    /// Returns [`ProtocolConversionError`] when a nested v2 capability cannot
5644    /// be represented by the v1 capability fields.
5645    pub fn try_into_v1_parts(self) -> Result<V1SessionCapabilityParts> {
5646        let Self {
5647            prompt,
5648            mcp,
5649            delete,
5650            additional_directories,
5651            #[cfg(feature = "unstable_session_fork")]
5652            fork,
5653            meta,
5654        } = self;
5655
5656        Ok(V1SessionCapabilityParts {
5657            session_capabilities: crate::v1::SessionCapabilities {
5658                list: Some(crate::v1::SessionListCapabilities::new()),
5659                delete: delete.try_to_v1()?,
5660                additional_directories: additional_directories.try_to_v1()?,
5661                #[cfg(feature = "unstable_session_fork")]
5662                fork: fork.try_to_v1()?,
5663                resume: Some(crate::v1::SessionResumeCapabilities::new()),
5664                close: Some(crate::v1::SessionCloseCapabilities::new()),
5665                meta: meta.try_to_v1()?,
5666            },
5667            prompt_capabilities: prompt.unwrap_or_default().try_to_v1()?,
5668            load_session: true,
5669            mcp_capabilities: mcp.unwrap_or_default().try_to_v1()?,
5670        })
5671    }
5672
5673    /// Builds v2 draft session capabilities from the v1 agent capability fields
5674    /// that now live under `session` in v2.
5675    ///
5676    /// # Errors
5677    ///
5678    /// Returns [`ProtocolConversionError`] when any of the supplied v1
5679    /// capability fields cannot be represented in v2.
5680    pub fn from_v1(
5681        session_capabilities: crate::v1::SessionCapabilities,
5682        prompt_capabilities: crate::v1::PromptCapabilities,
5683        load_session: bool,
5684        mcp_capabilities: crate::v1::McpCapabilities,
5685    ) -> Result<Self> {
5686        if !load_session {
5687            return Err(unrepresentable_v1_field("AgentCapabilities", "loadSession"));
5688        }
5689        let crate::v1::SessionCapabilities {
5690            list,
5691            delete,
5692            additional_directories,
5693            #[cfg(feature = "unstable_session_fork")]
5694            fork,
5695            resume,
5696            close,
5697            meta,
5698        } = session_capabilities;
5699
5700        let Some(list) = list else {
5701            return Err(unrepresentable_v1_field("SessionCapabilities", "list"));
5702        };
5703        reject_v1_marker_meta("SessionCapabilities", "list", list.meta.as_ref())?;
5704
5705        let Some(resume) = resume else {
5706            return Err(unrepresentable_v1_field("SessionCapabilities", "resume"));
5707        };
5708        reject_v1_marker_meta("SessionCapabilities", "resume", resume.meta.as_ref())?;
5709
5710        let Some(close) = close else {
5711            return Err(unrepresentable_v1_field("SessionCapabilities", "close"));
5712        };
5713        reject_v1_marker_meta("SessionCapabilities", "close", close.meta.as_ref())?;
5714
5715        Ok(super::SessionCapabilities {
5716            prompt: Some(prompt_capabilities.try_to_v2()?),
5717            mcp: Some(mcp_capabilities.try_to_v2()?),
5718            delete: delete.try_to_v2()?,
5719            additional_directories: additional_directories.try_to_v2()?,
5720            #[cfg(feature = "unstable_session_fork")]
5721            fork: fork.try_to_v2()?,
5722            meta: meta.try_to_v2()?,
5723        })
5724    }
5725}
5726
5727impl TryFrom<super::SessionCapabilities> for V1SessionCapabilityParts {
5728    type Error = ProtocolConversionError;
5729
5730    fn try_from(value: super::SessionCapabilities) -> Result<Self> {
5731        value.try_into_v1_parts()
5732    }
5733}
5734
5735impl TryToV1 for super::SessionDeleteCapabilities {
5736    type Output = crate::v1::SessionDeleteCapabilities;
5737
5738    fn try_to_v1(self) -> Result<Self::Output> {
5739        let Self { meta } = self;
5740        Ok(crate::v1::SessionDeleteCapabilities {
5741            meta: meta.try_to_v1()?,
5742        })
5743    }
5744}
5745
5746impl TryToV2 for crate::v1::SessionDeleteCapabilities {
5747    type Output = super::SessionDeleteCapabilities;
5748
5749    fn try_to_v2(self) -> Result<Self::Output> {
5750        let Self { meta } = self;
5751        Ok(super::SessionDeleteCapabilities {
5752            meta: meta.try_to_v2()?,
5753        })
5754    }
5755}
5756impl TryToV1 for super::SessionAdditionalDirectoriesCapabilities {
5757    type Output = crate::v1::SessionAdditionalDirectoriesCapabilities;
5758
5759    fn try_to_v1(self) -> Result<Self::Output> {
5760        let Self { meta } = self;
5761        Ok(crate::v1::SessionAdditionalDirectoriesCapabilities {
5762            meta: meta.try_to_v1()?,
5763        })
5764    }
5765}
5766
5767impl TryToV2 for crate::v1::SessionAdditionalDirectoriesCapabilities {
5768    type Output = super::SessionAdditionalDirectoriesCapabilities;
5769
5770    fn try_to_v2(self) -> Result<Self::Output> {
5771        let Self { meta } = self;
5772        Ok(super::SessionAdditionalDirectoriesCapabilities {
5773            meta: meta.try_to_v2()?,
5774        })
5775    }
5776}
5777
5778#[cfg(feature = "unstable_session_fork")]
5779impl TryToV1 for super::SessionForkCapabilities {
5780    type Output = crate::v1::SessionForkCapabilities;
5781
5782    fn try_to_v1(self) -> Result<Self::Output> {
5783        let Self { meta } = self;
5784        Ok(crate::v1::SessionForkCapabilities {
5785            meta: meta.try_to_v1()?,
5786        })
5787    }
5788}
5789
5790#[cfg(feature = "unstable_session_fork")]
5791impl TryToV2 for crate::v1::SessionForkCapabilities {
5792    type Output = super::SessionForkCapabilities;
5793
5794    fn try_to_v2(self) -> Result<Self::Output> {
5795        let Self { meta } = self;
5796        Ok(super::SessionForkCapabilities {
5797            meta: meta.try_to_v2()?,
5798        })
5799    }
5800}
5801
5802impl TryToV1 for super::PromptCapabilities {
5803    type Output = crate::v1::PromptCapabilities;
5804
5805    fn try_to_v1(self) -> Result<Self::Output> {
5806        let Self {
5807            image,
5808            audio,
5809            embedded_context,
5810            meta,
5811        } = self;
5812        if let Some(image) = &image {
5813            reject_v2_marker_meta("PromptCapabilities", "image", image.meta.as_ref())?;
5814        }
5815        if let Some(audio) = &audio {
5816            reject_v2_marker_meta("PromptCapabilities", "audio", audio.meta.as_ref())?;
5817        }
5818        if let Some(embedded_context) = &embedded_context {
5819            reject_v2_marker_meta(
5820                "PromptCapabilities",
5821                "embeddedContext",
5822                embedded_context.meta.as_ref(),
5823            )?;
5824        }
5825        Ok(crate::v1::PromptCapabilities {
5826            image: image.is_some(),
5827            audio: audio.is_some(),
5828            embedded_context: embedded_context.is_some(),
5829            meta: meta.try_to_v1()?,
5830        })
5831    }
5832}
5833
5834impl TryToV2 for crate::v1::PromptCapabilities {
5835    type Output = super::PromptCapabilities;
5836
5837    fn try_to_v2(self) -> Result<Self::Output> {
5838        let Self {
5839            image,
5840            audio,
5841            embedded_context,
5842            meta,
5843        } = self;
5844        Ok(super::PromptCapabilities {
5845            image: image.then(super::PromptImageCapabilities::new),
5846            audio: audio.then(super::PromptAudioCapabilities::new),
5847            embedded_context: embedded_context.then(super::PromptEmbeddedContextCapabilities::new),
5848            meta: meta.try_to_v2()?,
5849        })
5850    }
5851}
5852
5853impl TryToV1 for super::McpCapabilities {
5854    type Output = crate::v1::McpCapabilities;
5855
5856    fn try_to_v1(self) -> Result<Self::Output> {
5857        let Self {
5858            stdio,
5859            http,
5860            #[cfg(feature = "unstable_mcp_over_acp")]
5861            acp,
5862            meta,
5863        } = self;
5864        if let Some(stdio) = &stdio {
5865            reject_v2_marker_meta("McpCapabilities", "stdio", stdio.meta.as_ref())?;
5866        }
5867        if let Some(http) = &http {
5868            reject_v2_marker_meta("McpCapabilities", "http", http.meta.as_ref())?;
5869        }
5870        #[cfg(feature = "unstable_mcp_over_acp")]
5871        if let Some(acp) = &acp {
5872            reject_v2_marker_meta("McpCapabilities", "acp", acp.meta.as_ref())?;
5873        }
5874        Ok(crate::v1::McpCapabilities {
5875            http: http.is_some(),
5876            sse: false,
5877            #[cfg(feature = "unstable_mcp_over_acp")]
5878            acp: acp.is_some(),
5879            meta: meta.try_to_v1()?,
5880        })
5881    }
5882}
5883
5884impl TryToV2 for crate::v1::McpCapabilities {
5885    type Output = super::McpCapabilities;
5886
5887    fn try_to_v2(self) -> Result<Self::Output> {
5888        let Self {
5889            http,
5890            sse,
5891            #[cfg(feature = "unstable_mcp_over_acp")]
5892            acp,
5893            meta,
5894        } = self;
5895        if sse {
5896            return Err(unrepresentable_v1_field("McpCapabilities", "sse"));
5897        }
5898        Ok(super::McpCapabilities {
5899            stdio: Some(super::McpStdioCapabilities::new()),
5900            http: http.then(super::McpHttpCapabilities::new),
5901            #[cfg(feature = "unstable_mcp_over_acp")]
5902            acp: acp.then(super::McpAcpCapabilities::new),
5903            meta: meta.try_to_v2()?,
5904        })
5905    }
5906}
5907
5908impl TryToV1 for super::CancelSessionNotification {
5909    type Output = crate::v1::CancelNotification;
5910
5911    fn try_to_v1(self) -> Result<Self::Output> {
5912        let Self { session_id, meta } = self;
5913        Ok(crate::v1::CancelNotification {
5914            session_id: session_id.try_to_v1()?,
5915            meta: meta.try_to_v1()?,
5916        })
5917    }
5918}
5919
5920impl TryToV2 for crate::v1::CancelNotification {
5921    type Output = super::CancelSessionNotification;
5922
5923    fn try_to_v2(self) -> Result<Self::Output> {
5924        let Self { session_id, meta } = self;
5925        Ok(super::CancelSessionNotification {
5926            session_id: session_id.try_to_v2()?,
5927            meta: meta.try_to_v2()?,
5928        })
5929    }
5930}
5931
5932#[cfg(feature = "unstable_nes")]
5933impl TryToV1 for super::PositionEncodingKind {
5934    type Output = crate::v1::PositionEncodingKind;
5935
5936    fn try_to_v1(self) -> Result<Self::Output> {
5937        Ok(match self {
5938            Self::Utf16 => crate::v1::PositionEncodingKind::Utf16,
5939            Self::Utf32 => crate::v1::PositionEncodingKind::Utf32,
5940            Self::Utf8 => crate::v1::PositionEncodingKind::Utf8,
5941        })
5942    }
5943}
5944
5945#[cfg(feature = "unstable_nes")]
5946impl TryToV2 for crate::v1::PositionEncodingKind {
5947    type Output = super::PositionEncodingKind;
5948
5949    fn try_to_v2(self) -> Result<Self::Output> {
5950        Ok(match self {
5951            Self::Utf16 => super::PositionEncodingKind::Utf16,
5952            Self::Utf32 => super::PositionEncodingKind::Utf32,
5953            Self::Utf8 => super::PositionEncodingKind::Utf8,
5954        })
5955    }
5956}
5957
5958#[cfg(feature = "unstable_nes")]
5959impl TryToV1 for super::Position {
5960    type Output = crate::v1::Position;
5961
5962    fn try_to_v1(self) -> Result<Self::Output> {
5963        let Self {
5964            line,
5965            character,
5966            meta,
5967        } = self;
5968        Ok(crate::v1::Position {
5969            line: line.try_to_v1()?,
5970            character: character.try_to_v1()?,
5971            meta: meta.try_to_v1()?,
5972        })
5973    }
5974}
5975
5976#[cfg(feature = "unstable_nes")]
5977impl TryToV2 for crate::v1::Position {
5978    type Output = super::Position;
5979
5980    fn try_to_v2(self) -> Result<Self::Output> {
5981        let Self {
5982            line,
5983            character,
5984            meta,
5985        } = self;
5986        Ok(super::Position {
5987            line: line.try_to_v2()?,
5988            character: character.try_to_v2()?,
5989            meta: meta.try_to_v2()?,
5990        })
5991    }
5992}
5993
5994#[cfg(feature = "unstable_nes")]
5995impl TryToV1 for super::Range {
5996    type Output = crate::v1::Range;
5997
5998    fn try_to_v1(self) -> Result<Self::Output> {
5999        let Self { start, end, meta } = self;
6000        Ok(crate::v1::Range {
6001            start: start.try_to_v1()?,
6002            end: end.try_to_v1()?,
6003            meta: meta.try_to_v1()?,
6004        })
6005    }
6006}
6007
6008#[cfg(feature = "unstable_nes")]
6009impl TryToV2 for crate::v1::Range {
6010    type Output = super::Range;
6011
6012    fn try_to_v2(self) -> Result<Self::Output> {
6013        let Self { start, end, meta } = self;
6014        Ok(super::Range {
6015            start: start.try_to_v2()?,
6016            end: end.try_to_v2()?,
6017            meta: meta.try_to_v2()?,
6018        })
6019    }
6020}
6021
6022#[cfg(feature = "unstable_nes")]
6023impl TryToV1 for super::NesCapabilities {
6024    type Output = crate::v1::NesCapabilities;
6025
6026    fn try_to_v1(self) -> Result<Self::Output> {
6027        let Self {
6028            events,
6029            context,
6030            meta,
6031        } = self;
6032        Ok(crate::v1::NesCapabilities {
6033            events: events.try_to_v1()?,
6034            context: context.try_to_v1()?,
6035            meta: meta.try_to_v1()?,
6036        })
6037    }
6038}
6039
6040#[cfg(feature = "unstable_nes")]
6041impl TryToV2 for crate::v1::NesCapabilities {
6042    type Output = super::NesCapabilities;
6043
6044    fn try_to_v2(self) -> Result<Self::Output> {
6045        let Self {
6046            events,
6047            context,
6048            meta,
6049        } = self;
6050        Ok(super::NesCapabilities {
6051            events: events.try_to_v2()?,
6052            context: context.try_to_v2()?,
6053            meta: meta.try_to_v2()?,
6054        })
6055    }
6056}
6057
6058#[cfg(feature = "unstable_nes")]
6059impl TryToV1 for super::NesEventCapabilities {
6060    type Output = crate::v1::NesEventCapabilities;
6061
6062    fn try_to_v1(self) -> Result<Self::Output> {
6063        let Self { document, meta } = self;
6064        Ok(crate::v1::NesEventCapabilities {
6065            document: document.try_to_v1()?,
6066            meta: meta.try_to_v1()?,
6067        })
6068    }
6069}
6070
6071#[cfg(feature = "unstable_nes")]
6072impl TryToV2 for crate::v1::NesEventCapabilities {
6073    type Output = super::NesEventCapabilities;
6074
6075    fn try_to_v2(self) -> Result<Self::Output> {
6076        let Self { document, meta } = self;
6077        Ok(super::NesEventCapabilities {
6078            document: document.try_to_v2()?,
6079            meta: meta.try_to_v2()?,
6080        })
6081    }
6082}
6083
6084#[cfg(feature = "unstable_nes")]
6085impl TryToV1 for super::NesDocumentEventCapabilities {
6086    type Output = crate::v1::NesDocumentEventCapabilities;
6087
6088    fn try_to_v1(self) -> Result<Self::Output> {
6089        let Self {
6090            did_open,
6091            did_change,
6092            did_close,
6093            did_save,
6094            did_focus,
6095            meta,
6096        } = self;
6097        Ok(crate::v1::NesDocumentEventCapabilities {
6098            did_open: did_open.try_to_v1()?,
6099            did_change: did_change.try_to_v1()?,
6100            did_close: did_close.try_to_v1()?,
6101            did_save: did_save.try_to_v1()?,
6102            did_focus: did_focus.try_to_v1()?,
6103            meta: meta.try_to_v1()?,
6104        })
6105    }
6106}
6107
6108#[cfg(feature = "unstable_nes")]
6109impl TryToV2 for crate::v1::NesDocumentEventCapabilities {
6110    type Output = super::NesDocumentEventCapabilities;
6111
6112    fn try_to_v2(self) -> Result<Self::Output> {
6113        let Self {
6114            did_open,
6115            did_change,
6116            did_close,
6117            did_save,
6118            did_focus,
6119            meta,
6120        } = self;
6121        Ok(super::NesDocumentEventCapabilities {
6122            did_open: did_open.try_to_v2()?,
6123            did_change: did_change.try_to_v2()?,
6124            did_close: did_close.try_to_v2()?,
6125            did_save: did_save.try_to_v2()?,
6126            did_focus: did_focus.try_to_v2()?,
6127            meta: meta.try_to_v2()?,
6128        })
6129    }
6130}
6131
6132#[cfg(feature = "unstable_nes")]
6133impl TryToV1 for super::NesDocumentDidOpenCapabilities {
6134    type Output = crate::v1::NesDocumentDidOpenCapabilities;
6135
6136    fn try_to_v1(self) -> Result<Self::Output> {
6137        let Self { meta } = self;
6138        Ok(crate::v1::NesDocumentDidOpenCapabilities {
6139            meta: meta.try_to_v1()?,
6140        })
6141    }
6142}
6143
6144#[cfg(feature = "unstable_nes")]
6145impl TryToV2 for crate::v1::NesDocumentDidOpenCapabilities {
6146    type Output = super::NesDocumentDidOpenCapabilities;
6147
6148    fn try_to_v2(self) -> Result<Self::Output> {
6149        let Self { meta } = self;
6150        Ok(super::NesDocumentDidOpenCapabilities {
6151            meta: meta.try_to_v2()?,
6152        })
6153    }
6154}
6155
6156#[cfg(feature = "unstable_nes")]
6157impl TryToV1 for super::NesDocumentDidChangeCapabilities {
6158    type Output = crate::v1::NesDocumentDidChangeCapabilities;
6159
6160    fn try_to_v1(self) -> Result<Self::Output> {
6161        let Self { sync_kind, meta } = self;
6162        Ok(crate::v1::NesDocumentDidChangeCapabilities {
6163            sync_kind: sync_kind.try_to_v1()?,
6164            meta: meta.try_to_v1()?,
6165        })
6166    }
6167}
6168
6169#[cfg(feature = "unstable_nes")]
6170impl TryToV2 for crate::v1::NesDocumentDidChangeCapabilities {
6171    type Output = super::NesDocumentDidChangeCapabilities;
6172
6173    fn try_to_v2(self) -> Result<Self::Output> {
6174        let Self { sync_kind, meta } = self;
6175        Ok(super::NesDocumentDidChangeCapabilities {
6176            sync_kind: sync_kind.try_to_v2()?,
6177            meta: meta.try_to_v2()?,
6178        })
6179    }
6180}
6181
6182#[cfg(feature = "unstable_nes")]
6183impl TryToV1 for super::TextDocumentSyncKind {
6184    type Output = crate::v1::TextDocumentSyncKind;
6185
6186    fn try_to_v1(self) -> Result<Self::Output> {
6187        Ok(match self {
6188            Self::Full => crate::v1::TextDocumentSyncKind::Full,
6189            Self::Incremental => crate::v1::TextDocumentSyncKind::Incremental,
6190        })
6191    }
6192}
6193
6194#[cfg(feature = "unstable_nes")]
6195impl TryToV2 for crate::v1::TextDocumentSyncKind {
6196    type Output = super::TextDocumentSyncKind;
6197
6198    fn try_to_v2(self) -> Result<Self::Output> {
6199        Ok(match self {
6200            Self::Full => super::TextDocumentSyncKind::Full,
6201            Self::Incremental => super::TextDocumentSyncKind::Incremental,
6202        })
6203    }
6204}
6205
6206#[cfg(feature = "unstable_nes")]
6207impl TryToV1 for super::NesDocumentDidCloseCapabilities {
6208    type Output = crate::v1::NesDocumentDidCloseCapabilities;
6209
6210    fn try_to_v1(self) -> Result<Self::Output> {
6211        let Self { meta } = self;
6212        Ok(crate::v1::NesDocumentDidCloseCapabilities {
6213            meta: meta.try_to_v1()?,
6214        })
6215    }
6216}
6217
6218#[cfg(feature = "unstable_nes")]
6219impl TryToV2 for crate::v1::NesDocumentDidCloseCapabilities {
6220    type Output = super::NesDocumentDidCloseCapabilities;
6221
6222    fn try_to_v2(self) -> Result<Self::Output> {
6223        let Self { meta } = self;
6224        Ok(super::NesDocumentDidCloseCapabilities {
6225            meta: meta.try_to_v2()?,
6226        })
6227    }
6228}
6229
6230#[cfg(feature = "unstable_nes")]
6231impl TryToV1 for super::NesDocumentDidSaveCapabilities {
6232    type Output = crate::v1::NesDocumentDidSaveCapabilities;
6233
6234    fn try_to_v1(self) -> Result<Self::Output> {
6235        let Self { meta } = self;
6236        Ok(crate::v1::NesDocumentDidSaveCapabilities {
6237            meta: meta.try_to_v1()?,
6238        })
6239    }
6240}
6241
6242#[cfg(feature = "unstable_nes")]
6243impl TryToV2 for crate::v1::NesDocumentDidSaveCapabilities {
6244    type Output = super::NesDocumentDidSaveCapabilities;
6245
6246    fn try_to_v2(self) -> Result<Self::Output> {
6247        let Self { meta } = self;
6248        Ok(super::NesDocumentDidSaveCapabilities {
6249            meta: meta.try_to_v2()?,
6250        })
6251    }
6252}
6253
6254#[cfg(feature = "unstable_nes")]
6255impl TryToV1 for super::NesDocumentDidFocusCapabilities {
6256    type Output = crate::v1::NesDocumentDidFocusCapabilities;
6257
6258    fn try_to_v1(self) -> Result<Self::Output> {
6259        let Self { meta } = self;
6260        Ok(crate::v1::NesDocumentDidFocusCapabilities {
6261            meta: meta.try_to_v1()?,
6262        })
6263    }
6264}
6265
6266#[cfg(feature = "unstable_nes")]
6267impl TryToV2 for crate::v1::NesDocumentDidFocusCapabilities {
6268    type Output = super::NesDocumentDidFocusCapabilities;
6269
6270    fn try_to_v2(self) -> Result<Self::Output> {
6271        let Self { meta } = self;
6272        Ok(super::NesDocumentDidFocusCapabilities {
6273            meta: meta.try_to_v2()?,
6274        })
6275    }
6276}
6277
6278#[cfg(feature = "unstable_nes")]
6279impl TryToV1 for super::NesContextCapabilities {
6280    type Output = crate::v1::NesContextCapabilities;
6281
6282    fn try_to_v1(self) -> Result<Self::Output> {
6283        let Self {
6284            recent_files,
6285            related_snippets,
6286            edit_history,
6287            user_actions,
6288            open_files,
6289            diagnostics,
6290            meta,
6291        } = self;
6292        Ok(crate::v1::NesContextCapabilities {
6293            recent_files: recent_files.try_to_v1()?,
6294            related_snippets: related_snippets.try_to_v1()?,
6295            edit_history: edit_history.try_to_v1()?,
6296            user_actions: user_actions.try_to_v1()?,
6297            open_files: open_files.try_to_v1()?,
6298            diagnostics: diagnostics.try_to_v1()?,
6299            meta: meta.try_to_v1()?,
6300        })
6301    }
6302}
6303
6304#[cfg(feature = "unstable_nes")]
6305impl TryToV2 for crate::v1::NesContextCapabilities {
6306    type Output = super::NesContextCapabilities;
6307
6308    fn try_to_v2(self) -> Result<Self::Output> {
6309        let Self {
6310            recent_files,
6311            related_snippets,
6312            edit_history,
6313            user_actions,
6314            open_files,
6315            diagnostics,
6316            meta,
6317        } = self;
6318        Ok(super::NesContextCapabilities {
6319            recent_files: recent_files.try_to_v2()?,
6320            related_snippets: related_snippets.try_to_v2()?,
6321            edit_history: edit_history.try_to_v2()?,
6322            user_actions: user_actions.try_to_v2()?,
6323            open_files: open_files.try_to_v2()?,
6324            diagnostics: diagnostics.try_to_v2()?,
6325            meta: meta.try_to_v2()?,
6326        })
6327    }
6328}
6329
6330#[cfg(feature = "unstable_nes")]
6331impl TryToV1 for super::NesRecentFilesCapabilities {
6332    type Output = crate::v1::NesRecentFilesCapabilities;
6333
6334    fn try_to_v1(self) -> Result<Self::Output> {
6335        let Self { max_count, meta } = self;
6336        Ok(crate::v1::NesRecentFilesCapabilities {
6337            max_count: max_count.try_to_v1()?,
6338            meta: meta.try_to_v1()?,
6339        })
6340    }
6341}
6342
6343#[cfg(feature = "unstable_nes")]
6344impl TryToV2 for crate::v1::NesRecentFilesCapabilities {
6345    type Output = super::NesRecentFilesCapabilities;
6346
6347    fn try_to_v2(self) -> Result<Self::Output> {
6348        let Self { max_count, meta } = self;
6349        Ok(super::NesRecentFilesCapabilities {
6350            max_count: max_count.try_to_v2()?,
6351            meta: meta.try_to_v2()?,
6352        })
6353    }
6354}
6355
6356#[cfg(feature = "unstable_nes")]
6357impl TryToV1 for super::NesRelatedSnippetsCapabilities {
6358    type Output = crate::v1::NesRelatedSnippetsCapabilities;
6359
6360    fn try_to_v1(self) -> Result<Self::Output> {
6361        let Self { meta } = self;
6362        Ok(crate::v1::NesRelatedSnippetsCapabilities {
6363            meta: meta.try_to_v1()?,
6364        })
6365    }
6366}
6367
6368#[cfg(feature = "unstable_nes")]
6369impl TryToV2 for crate::v1::NesRelatedSnippetsCapabilities {
6370    type Output = super::NesRelatedSnippetsCapabilities;
6371
6372    fn try_to_v2(self) -> Result<Self::Output> {
6373        let Self { meta } = self;
6374        Ok(super::NesRelatedSnippetsCapabilities {
6375            meta: meta.try_to_v2()?,
6376        })
6377    }
6378}
6379
6380#[cfg(feature = "unstable_nes")]
6381impl TryToV1 for super::NesEditHistoryCapabilities {
6382    type Output = crate::v1::NesEditHistoryCapabilities;
6383
6384    fn try_to_v1(self) -> Result<Self::Output> {
6385        let Self { max_count, meta } = self;
6386        Ok(crate::v1::NesEditHistoryCapabilities {
6387            max_count: max_count.try_to_v1()?,
6388            meta: meta.try_to_v1()?,
6389        })
6390    }
6391}
6392
6393#[cfg(feature = "unstable_nes")]
6394impl TryToV2 for crate::v1::NesEditHistoryCapabilities {
6395    type Output = super::NesEditHistoryCapabilities;
6396
6397    fn try_to_v2(self) -> Result<Self::Output> {
6398        let Self { max_count, meta } = self;
6399        Ok(super::NesEditHistoryCapabilities {
6400            max_count: max_count.try_to_v2()?,
6401            meta: meta.try_to_v2()?,
6402        })
6403    }
6404}
6405
6406#[cfg(feature = "unstable_nes")]
6407impl TryToV1 for super::NesUserActionsCapabilities {
6408    type Output = crate::v1::NesUserActionsCapabilities;
6409
6410    fn try_to_v1(self) -> Result<Self::Output> {
6411        let Self { max_count, meta } = self;
6412        Ok(crate::v1::NesUserActionsCapabilities {
6413            max_count: max_count.try_to_v1()?,
6414            meta: meta.try_to_v1()?,
6415        })
6416    }
6417}
6418
6419#[cfg(feature = "unstable_nes")]
6420impl TryToV2 for crate::v1::NesUserActionsCapabilities {
6421    type Output = super::NesUserActionsCapabilities;
6422
6423    fn try_to_v2(self) -> Result<Self::Output> {
6424        let Self { max_count, meta } = self;
6425        Ok(super::NesUserActionsCapabilities {
6426            max_count: max_count.try_to_v2()?,
6427            meta: meta.try_to_v2()?,
6428        })
6429    }
6430}
6431
6432#[cfg(feature = "unstable_nes")]
6433impl TryToV1 for super::NesOpenFilesCapabilities {
6434    type Output = crate::v1::NesOpenFilesCapabilities;
6435
6436    fn try_to_v1(self) -> Result<Self::Output> {
6437        let Self { meta } = self;
6438        Ok(crate::v1::NesOpenFilesCapabilities {
6439            meta: meta.try_to_v1()?,
6440        })
6441    }
6442}
6443
6444#[cfg(feature = "unstable_nes")]
6445impl TryToV2 for crate::v1::NesOpenFilesCapabilities {
6446    type Output = super::NesOpenFilesCapabilities;
6447
6448    fn try_to_v2(self) -> Result<Self::Output> {
6449        let Self { meta } = self;
6450        Ok(super::NesOpenFilesCapabilities {
6451            meta: meta.try_to_v2()?,
6452        })
6453    }
6454}
6455
6456#[cfg(feature = "unstable_nes")]
6457impl TryToV1 for super::NesDiagnosticsCapabilities {
6458    type Output = crate::v1::NesDiagnosticsCapabilities;
6459
6460    fn try_to_v1(self) -> Result<Self::Output> {
6461        let Self { meta } = self;
6462        Ok(crate::v1::NesDiagnosticsCapabilities {
6463            meta: meta.try_to_v1()?,
6464        })
6465    }
6466}
6467
6468#[cfg(feature = "unstable_nes")]
6469impl TryToV2 for crate::v1::NesDiagnosticsCapabilities {
6470    type Output = super::NesDiagnosticsCapabilities;
6471
6472    fn try_to_v2(self) -> Result<Self::Output> {
6473        let Self { meta } = self;
6474        Ok(super::NesDiagnosticsCapabilities {
6475            meta: meta.try_to_v2()?,
6476        })
6477    }
6478}
6479
6480#[cfg(feature = "unstable_nes")]
6481impl TryToV1 for super::ClientNesCapabilities {
6482    type Output = crate::v1::ClientNesCapabilities;
6483
6484    fn try_to_v1(self) -> Result<Self::Output> {
6485        let Self {
6486            jump,
6487            rename,
6488            search_and_replace,
6489            meta,
6490        } = self;
6491        Ok(crate::v1::ClientNesCapabilities {
6492            jump: jump.try_to_v1()?,
6493            rename: rename.try_to_v1()?,
6494            search_and_replace: search_and_replace.try_to_v1()?,
6495            meta: meta.try_to_v1()?,
6496        })
6497    }
6498}
6499
6500#[cfg(feature = "unstable_nes")]
6501impl TryToV2 for crate::v1::ClientNesCapabilities {
6502    type Output = super::ClientNesCapabilities;
6503
6504    fn try_to_v2(self) -> Result<Self::Output> {
6505        let Self {
6506            jump,
6507            rename,
6508            search_and_replace,
6509            meta,
6510        } = self;
6511        Ok(super::ClientNesCapabilities {
6512            jump: jump.try_to_v2()?,
6513            rename: rename.try_to_v2()?,
6514            search_and_replace: search_and_replace.try_to_v2()?,
6515            meta: meta.try_to_v2()?,
6516        })
6517    }
6518}
6519
6520#[cfg(feature = "unstable_nes")]
6521impl TryToV1 for super::NesJumpCapabilities {
6522    type Output = crate::v1::NesJumpCapabilities;
6523
6524    fn try_to_v1(self) -> Result<Self::Output> {
6525        let Self { meta } = self;
6526        Ok(crate::v1::NesJumpCapabilities {
6527            meta: meta.try_to_v1()?,
6528        })
6529    }
6530}
6531
6532#[cfg(feature = "unstable_nes")]
6533impl TryToV2 for crate::v1::NesJumpCapabilities {
6534    type Output = super::NesJumpCapabilities;
6535
6536    fn try_to_v2(self) -> Result<Self::Output> {
6537        let Self { meta } = self;
6538        Ok(super::NesJumpCapabilities {
6539            meta: meta.try_to_v2()?,
6540        })
6541    }
6542}
6543
6544#[cfg(feature = "unstable_nes")]
6545impl TryToV1 for super::NesRenameCapabilities {
6546    type Output = crate::v1::NesRenameCapabilities;
6547
6548    fn try_to_v1(self) -> Result<Self::Output> {
6549        let Self { meta } = self;
6550        Ok(crate::v1::NesRenameCapabilities {
6551            meta: meta.try_to_v1()?,
6552        })
6553    }
6554}
6555
6556#[cfg(feature = "unstable_nes")]
6557impl TryToV2 for crate::v1::NesRenameCapabilities {
6558    type Output = super::NesRenameCapabilities;
6559
6560    fn try_to_v2(self) -> Result<Self::Output> {
6561        let Self { meta } = self;
6562        Ok(super::NesRenameCapabilities {
6563            meta: meta.try_to_v2()?,
6564        })
6565    }
6566}
6567
6568#[cfg(feature = "unstable_nes")]
6569impl TryToV1 for super::NesSearchAndReplaceCapabilities {
6570    type Output = crate::v1::NesSearchAndReplaceCapabilities;
6571
6572    fn try_to_v1(self) -> Result<Self::Output> {
6573        let Self { meta } = self;
6574        Ok(crate::v1::NesSearchAndReplaceCapabilities {
6575            meta: meta.try_to_v1()?,
6576        })
6577    }
6578}
6579
6580#[cfg(feature = "unstable_nes")]
6581impl TryToV2 for crate::v1::NesSearchAndReplaceCapabilities {
6582    type Output = super::NesSearchAndReplaceCapabilities;
6583
6584    fn try_to_v2(self) -> Result<Self::Output> {
6585        let Self { meta } = self;
6586        Ok(super::NesSearchAndReplaceCapabilities {
6587            meta: meta.try_to_v2()?,
6588        })
6589    }
6590}
6591
6592#[cfg(feature = "unstable_nes")]
6593impl TryToV1 for super::DidOpenDocumentNotification {
6594    type Output = crate::v1::DidOpenDocumentNotification;
6595
6596    fn try_to_v1(self) -> Result<Self::Output> {
6597        let Self {
6598            session_id,
6599            uri,
6600            language_id,
6601            version,
6602            text,
6603            meta,
6604        } = self;
6605        Ok(crate::v1::DidOpenDocumentNotification {
6606            session_id: session_id.try_to_v1()?,
6607            uri: uri.try_to_v1()?,
6608            language_id: language_id.try_to_v1()?,
6609            version: version.try_to_v1()?,
6610            text: text.try_to_v1()?,
6611            meta: meta.try_to_v1()?,
6612        })
6613    }
6614}
6615
6616#[cfg(feature = "unstable_nes")]
6617impl TryToV2 for crate::v1::DidOpenDocumentNotification {
6618    type Output = super::DidOpenDocumentNotification;
6619
6620    fn try_to_v2(self) -> Result<Self::Output> {
6621        let Self {
6622            session_id,
6623            uri,
6624            language_id,
6625            version,
6626            text,
6627            meta,
6628        } = self;
6629        Ok(super::DidOpenDocumentNotification {
6630            session_id: session_id.try_to_v2()?,
6631            uri: uri.try_to_v2()?,
6632            language_id: language_id.try_to_v2()?,
6633            version: version.try_to_v2()?,
6634            text: text.try_to_v2()?,
6635            meta: meta.try_to_v2()?,
6636        })
6637    }
6638}
6639
6640#[cfg(feature = "unstable_nes")]
6641impl TryToV1 for super::DidChangeDocumentNotification {
6642    type Output = crate::v1::DidChangeDocumentNotification;
6643
6644    fn try_to_v1(self) -> Result<Self::Output> {
6645        let Self {
6646            session_id,
6647            uri,
6648            version,
6649            content_changes,
6650            meta,
6651        } = self;
6652        Ok(crate::v1::DidChangeDocumentNotification {
6653            session_id: session_id.try_to_v1()?,
6654            uri: uri.try_to_v1()?,
6655            version: version.try_to_v1()?,
6656            content_changes: content_changes.try_to_v1()?,
6657            meta: meta.try_to_v1()?,
6658        })
6659    }
6660}
6661
6662#[cfg(feature = "unstable_nes")]
6663impl TryToV2 for crate::v1::DidChangeDocumentNotification {
6664    type Output = super::DidChangeDocumentNotification;
6665
6666    fn try_to_v2(self) -> Result<Self::Output> {
6667        let Self {
6668            session_id,
6669            uri,
6670            version,
6671            content_changes,
6672            meta,
6673        } = self;
6674        Ok(super::DidChangeDocumentNotification {
6675            session_id: session_id.try_to_v2()?,
6676            uri: uri.try_to_v2()?,
6677            version: version.try_to_v2()?,
6678            content_changes: content_changes.try_to_v2()?,
6679            meta: meta.try_to_v2()?,
6680        })
6681    }
6682}
6683
6684#[cfg(feature = "unstable_nes")]
6685impl TryToV1 for super::TextDocumentContentChangeEvent {
6686    type Output = crate::v1::TextDocumentContentChangeEvent;
6687
6688    fn try_to_v1(self) -> Result<Self::Output> {
6689        let Self { range, text, meta } = self;
6690        Ok(crate::v1::TextDocumentContentChangeEvent {
6691            range: range.try_to_v1()?,
6692            text: text.try_to_v1()?,
6693            meta: meta.try_to_v1()?,
6694        })
6695    }
6696}
6697
6698#[cfg(feature = "unstable_nes")]
6699impl TryToV2 for crate::v1::TextDocumentContentChangeEvent {
6700    type Output = super::TextDocumentContentChangeEvent;
6701
6702    fn try_to_v2(self) -> Result<Self::Output> {
6703        let Self { range, text, meta } = self;
6704        Ok(super::TextDocumentContentChangeEvent {
6705            range: range.try_to_v2()?,
6706            text: text.try_to_v2()?,
6707            meta: meta.try_to_v2()?,
6708        })
6709    }
6710}
6711
6712#[cfg(feature = "unstable_nes")]
6713impl TryToV1 for super::DidCloseDocumentNotification {
6714    type Output = crate::v1::DidCloseDocumentNotification;
6715
6716    fn try_to_v1(self) -> Result<Self::Output> {
6717        let Self {
6718            session_id,
6719            uri,
6720            meta,
6721        } = self;
6722        Ok(crate::v1::DidCloseDocumentNotification {
6723            session_id: session_id.try_to_v1()?,
6724            uri: uri.try_to_v1()?,
6725            meta: meta.try_to_v1()?,
6726        })
6727    }
6728}
6729
6730#[cfg(feature = "unstable_nes")]
6731impl TryToV2 for crate::v1::DidCloseDocumentNotification {
6732    type Output = super::DidCloseDocumentNotification;
6733
6734    fn try_to_v2(self) -> Result<Self::Output> {
6735        let Self {
6736            session_id,
6737            uri,
6738            meta,
6739        } = self;
6740        Ok(super::DidCloseDocumentNotification {
6741            session_id: session_id.try_to_v2()?,
6742            uri: uri.try_to_v2()?,
6743            meta: meta.try_to_v2()?,
6744        })
6745    }
6746}
6747
6748#[cfg(feature = "unstable_nes")]
6749impl TryToV1 for super::DidSaveDocumentNotification {
6750    type Output = crate::v1::DidSaveDocumentNotification;
6751
6752    fn try_to_v1(self) -> Result<Self::Output> {
6753        let Self {
6754            session_id,
6755            uri,
6756            meta,
6757        } = self;
6758        Ok(crate::v1::DidSaveDocumentNotification {
6759            session_id: session_id.try_to_v1()?,
6760            uri: uri.try_to_v1()?,
6761            meta: meta.try_to_v1()?,
6762        })
6763    }
6764}
6765
6766#[cfg(feature = "unstable_nes")]
6767impl TryToV2 for crate::v1::DidSaveDocumentNotification {
6768    type Output = super::DidSaveDocumentNotification;
6769
6770    fn try_to_v2(self) -> Result<Self::Output> {
6771        let Self {
6772            session_id,
6773            uri,
6774            meta,
6775        } = self;
6776        Ok(super::DidSaveDocumentNotification {
6777            session_id: session_id.try_to_v2()?,
6778            uri: uri.try_to_v2()?,
6779            meta: meta.try_to_v2()?,
6780        })
6781    }
6782}
6783
6784#[cfg(feature = "unstable_nes")]
6785impl TryToV1 for super::DidFocusDocumentNotification {
6786    type Output = crate::v1::DidFocusDocumentNotification;
6787
6788    fn try_to_v1(self) -> Result<Self::Output> {
6789        let Self {
6790            session_id,
6791            uri,
6792            version,
6793            position,
6794            visible_range,
6795            meta,
6796        } = self;
6797        Ok(crate::v1::DidFocusDocumentNotification {
6798            session_id: session_id.try_to_v1()?,
6799            uri: uri.try_to_v1()?,
6800            version: version.try_to_v1()?,
6801            position: position.try_to_v1()?,
6802            visible_range: visible_range.try_to_v1()?,
6803            meta: meta.try_to_v1()?,
6804        })
6805    }
6806}
6807
6808#[cfg(feature = "unstable_nes")]
6809impl TryToV2 for crate::v1::DidFocusDocumentNotification {
6810    type Output = super::DidFocusDocumentNotification;
6811
6812    fn try_to_v2(self) -> Result<Self::Output> {
6813        let Self {
6814            session_id,
6815            uri,
6816            version,
6817            position,
6818            visible_range,
6819            meta,
6820        } = self;
6821        Ok(super::DidFocusDocumentNotification {
6822            session_id: session_id.try_to_v2()?,
6823            uri: uri.try_to_v2()?,
6824            version: version.try_to_v2()?,
6825            position: position.try_to_v2()?,
6826            visible_range: visible_range.try_to_v2()?,
6827            meta: meta.try_to_v2()?,
6828        })
6829    }
6830}
6831
6832#[cfg(feature = "unstable_nes")]
6833impl TryToV1 for super::StartNesRequest {
6834    type Output = crate::v1::StartNesRequest;
6835
6836    fn try_to_v1(self) -> Result<Self::Output> {
6837        let Self {
6838            workspace_uri,
6839            workspace_folders,
6840            repository,
6841            meta,
6842        } = self;
6843        Ok(crate::v1::StartNesRequest {
6844            workspace_uri: workspace_uri.try_to_v1()?,
6845            workspace_folders: workspace_folders.try_to_v1()?,
6846            repository: repository.try_to_v1()?,
6847            meta: meta.try_to_v1()?,
6848        })
6849    }
6850}
6851
6852#[cfg(feature = "unstable_nes")]
6853impl TryToV2 for crate::v1::StartNesRequest {
6854    type Output = super::StartNesRequest;
6855
6856    fn try_to_v2(self) -> Result<Self::Output> {
6857        let Self {
6858            workspace_uri,
6859            workspace_folders,
6860            repository,
6861            meta,
6862        } = self;
6863        Ok(super::StartNesRequest {
6864            workspace_uri: workspace_uri.try_to_v2()?,
6865            workspace_folders: workspace_folders.try_to_v2()?,
6866            repository: repository.try_to_v2()?,
6867            meta: meta.try_to_v2()?,
6868        })
6869    }
6870}
6871
6872#[cfg(feature = "unstable_nes")]
6873impl TryToV1 for super::WorkspaceFolder {
6874    type Output = crate::v1::WorkspaceFolder;
6875
6876    fn try_to_v1(self) -> Result<Self::Output> {
6877        let Self { uri, name, meta } = self;
6878        Ok(crate::v1::WorkspaceFolder {
6879            uri: uri.try_to_v1()?,
6880            name: name.try_to_v1()?,
6881            meta: meta.try_to_v1()?,
6882        })
6883    }
6884}
6885
6886#[cfg(feature = "unstable_nes")]
6887impl TryToV2 for crate::v1::WorkspaceFolder {
6888    type Output = super::WorkspaceFolder;
6889
6890    fn try_to_v2(self) -> Result<Self::Output> {
6891        let Self { uri, name, meta } = self;
6892        Ok(super::WorkspaceFolder {
6893            uri: uri.try_to_v2()?,
6894            name: name.try_to_v2()?,
6895            meta: meta.try_to_v2()?,
6896        })
6897    }
6898}
6899
6900#[cfg(feature = "unstable_nes")]
6901impl TryToV1 for super::NesRepository {
6902    type Output = crate::v1::NesRepository;
6903
6904    fn try_to_v1(self) -> Result<Self::Output> {
6905        let Self {
6906            name,
6907            owner,
6908            remote_url,
6909            meta,
6910        } = self;
6911        Ok(crate::v1::NesRepository {
6912            name: name.try_to_v1()?,
6913            owner: owner.try_to_v1()?,
6914            remote_url: remote_url.try_to_v1()?,
6915            meta: meta.try_to_v1()?,
6916        })
6917    }
6918}
6919
6920#[cfg(feature = "unstable_nes")]
6921impl TryToV2 for crate::v1::NesRepository {
6922    type Output = super::NesRepository;
6923
6924    fn try_to_v2(self) -> Result<Self::Output> {
6925        let Self {
6926            name,
6927            owner,
6928            remote_url,
6929            meta,
6930        } = self;
6931        Ok(super::NesRepository {
6932            name: name.try_to_v2()?,
6933            owner: owner.try_to_v2()?,
6934            remote_url: remote_url.try_to_v2()?,
6935            meta: meta.try_to_v2()?,
6936        })
6937    }
6938}
6939
6940#[cfg(feature = "unstable_nes")]
6941impl TryToV1 for super::StartNesResponse {
6942    type Output = crate::v1::StartNesResponse;
6943
6944    fn try_to_v1(self) -> Result<Self::Output> {
6945        let Self { session_id, meta } = self;
6946        Ok(crate::v1::StartNesResponse {
6947            session_id: session_id.try_to_v1()?,
6948            meta: meta.try_to_v1()?,
6949        })
6950    }
6951}
6952
6953#[cfg(feature = "unstable_nes")]
6954impl TryToV2 for crate::v1::StartNesResponse {
6955    type Output = super::StartNesResponse;
6956
6957    fn try_to_v2(self) -> Result<Self::Output> {
6958        let Self { session_id, meta } = self;
6959        Ok(super::StartNesResponse {
6960            session_id: session_id.try_to_v2()?,
6961            meta: meta.try_to_v2()?,
6962        })
6963    }
6964}
6965
6966#[cfg(feature = "unstable_nes")]
6967impl TryToV1 for super::CloseNesRequest {
6968    type Output = crate::v1::CloseNesRequest;
6969
6970    fn try_to_v1(self) -> Result<Self::Output> {
6971        let Self { session_id, meta } = self;
6972        Ok(crate::v1::CloseNesRequest {
6973            session_id: session_id.try_to_v1()?,
6974            meta: meta.try_to_v1()?,
6975        })
6976    }
6977}
6978
6979#[cfg(feature = "unstable_nes")]
6980impl TryToV2 for crate::v1::CloseNesRequest {
6981    type Output = super::CloseNesRequest;
6982
6983    fn try_to_v2(self) -> Result<Self::Output> {
6984        let Self { session_id, meta } = self;
6985        Ok(super::CloseNesRequest {
6986            session_id: session_id.try_to_v2()?,
6987            meta: meta.try_to_v2()?,
6988        })
6989    }
6990}
6991
6992#[cfg(feature = "unstable_nes")]
6993impl TryToV1 for super::CloseNesResponse {
6994    type Output = crate::v1::CloseNesResponse;
6995
6996    fn try_to_v1(self) -> Result<Self::Output> {
6997        let Self { meta } = self;
6998        Ok(crate::v1::CloseNesResponse {
6999            meta: meta.try_to_v1()?,
7000        })
7001    }
7002}
7003
7004#[cfg(feature = "unstable_nes")]
7005impl TryToV2 for crate::v1::CloseNesResponse {
7006    type Output = super::CloseNesResponse;
7007
7008    fn try_to_v2(self) -> Result<Self::Output> {
7009        let Self { meta } = self;
7010        Ok(super::CloseNesResponse {
7011            meta: meta.try_to_v2()?,
7012        })
7013    }
7014}
7015
7016#[cfg(feature = "unstable_nes")]
7017impl TryToV1 for super::NesTriggerKind {
7018    type Output = crate::v1::NesTriggerKind;
7019
7020    fn try_to_v1(self) -> Result<Self::Output> {
7021        Ok(match self {
7022            Self::Automatic => crate::v1::NesTriggerKind::Automatic,
7023            Self::Diagnostic => crate::v1::NesTriggerKind::Diagnostic,
7024            Self::Manual => crate::v1::NesTriggerKind::Manual,
7025            Self::Other(value) => return Err(unknown_v2_enum_variant("NesTriggerKind", &value)),
7026        })
7027    }
7028}
7029
7030#[cfg(feature = "unstable_nes")]
7031impl TryToV2 for crate::v1::NesTriggerKind {
7032    type Output = super::NesTriggerKind;
7033
7034    fn try_to_v2(self) -> Result<Self::Output> {
7035        Ok(match self {
7036            Self::Automatic => super::NesTriggerKind::Automatic,
7037            Self::Diagnostic => super::NesTriggerKind::Diagnostic,
7038            Self::Manual => super::NesTriggerKind::Manual,
7039        })
7040    }
7041}
7042
7043#[cfg(feature = "unstable_nes")]
7044impl TryToV1 for super::SuggestNesRequest {
7045    type Output = crate::v1::SuggestNesRequest;
7046
7047    fn try_to_v1(self) -> Result<Self::Output> {
7048        let Self {
7049            session_id,
7050            uri,
7051            version,
7052            position,
7053            selection,
7054            trigger_kind,
7055            context,
7056            meta,
7057        } = self;
7058        Ok(crate::v1::SuggestNesRequest {
7059            session_id: session_id.try_to_v1()?,
7060            uri: uri.try_to_v1()?,
7061            version: version.try_to_v1()?,
7062            position: position.try_to_v1()?,
7063            selection: selection.try_to_v1()?,
7064            trigger_kind: trigger_kind.try_to_v1()?,
7065            context: context.try_to_v1()?,
7066            meta: meta.try_to_v1()?,
7067        })
7068    }
7069}
7070
7071#[cfg(feature = "unstable_nes")]
7072impl TryToV2 for crate::v1::SuggestNesRequest {
7073    type Output = super::SuggestNesRequest;
7074
7075    fn try_to_v2(self) -> Result<Self::Output> {
7076        let Self {
7077            session_id,
7078            uri,
7079            version,
7080            position,
7081            selection,
7082            trigger_kind,
7083            context,
7084            meta,
7085        } = self;
7086        Ok(super::SuggestNesRequest {
7087            session_id: session_id.try_to_v2()?,
7088            uri: uri.try_to_v2()?,
7089            version: version.try_to_v2()?,
7090            position: position.try_to_v2()?,
7091            selection: selection.try_to_v2()?,
7092            trigger_kind: trigger_kind.try_to_v2()?,
7093            context: context.try_to_v2()?,
7094            meta: meta.try_to_v2()?,
7095        })
7096    }
7097}
7098
7099#[cfg(feature = "unstable_nes")]
7100impl TryToV1 for super::NesSuggestContext {
7101    type Output = crate::v1::NesSuggestContext;
7102
7103    fn try_to_v1(self) -> Result<Self::Output> {
7104        let Self {
7105            recent_files,
7106            related_snippets,
7107            edit_history,
7108            user_actions,
7109            open_files,
7110            diagnostics,
7111            meta,
7112        } = self;
7113        Ok(crate::v1::NesSuggestContext {
7114            recent_files: recent_files.try_to_v1()?,
7115            related_snippets: related_snippets.try_to_v1()?,
7116            edit_history: edit_history.try_to_v1()?,
7117            user_actions: user_actions.try_to_v1()?,
7118            open_files: open_files.try_to_v1()?,
7119            diagnostics: diagnostics.try_to_v1()?,
7120            meta: meta.try_to_v1()?,
7121        })
7122    }
7123}
7124
7125#[cfg(feature = "unstable_nes")]
7126impl TryToV2 for crate::v1::NesSuggestContext {
7127    type Output = super::NesSuggestContext;
7128
7129    fn try_to_v2(self) -> Result<Self::Output> {
7130        let Self {
7131            recent_files,
7132            related_snippets,
7133            edit_history,
7134            user_actions,
7135            open_files,
7136            diagnostics,
7137            meta,
7138        } = self;
7139        Ok(super::NesSuggestContext {
7140            recent_files: recent_files.try_to_v2()?,
7141            related_snippets: related_snippets.try_to_v2()?,
7142            edit_history: edit_history.try_to_v2()?,
7143            user_actions: user_actions.try_to_v2()?,
7144            open_files: open_files.try_to_v2()?,
7145            diagnostics: diagnostics.try_to_v2()?,
7146            meta: meta.try_to_v2()?,
7147        })
7148    }
7149}
7150
7151#[cfg(feature = "unstable_nes")]
7152impl TryToV1 for super::NesRecentFile {
7153    type Output = crate::v1::NesRecentFile;
7154
7155    fn try_to_v1(self) -> Result<Self::Output> {
7156        let Self {
7157            uri,
7158            language_id,
7159            text,
7160            meta,
7161        } = self;
7162        Ok(crate::v1::NesRecentFile {
7163            uri: uri.try_to_v1()?,
7164            language_id: language_id.try_to_v1()?,
7165            text: text.try_to_v1()?,
7166            meta: meta.try_to_v1()?,
7167        })
7168    }
7169}
7170
7171#[cfg(feature = "unstable_nes")]
7172impl TryToV2 for crate::v1::NesRecentFile {
7173    type Output = super::NesRecentFile;
7174
7175    fn try_to_v2(self) -> Result<Self::Output> {
7176        let Self {
7177            uri,
7178            language_id,
7179            text,
7180            meta,
7181        } = self;
7182        Ok(super::NesRecentFile {
7183            uri: uri.try_to_v2()?,
7184            language_id: language_id.try_to_v2()?,
7185            text: text.try_to_v2()?,
7186            meta: meta.try_to_v2()?,
7187        })
7188    }
7189}
7190
7191#[cfg(feature = "unstable_nes")]
7192impl TryToV1 for super::NesRelatedSnippet {
7193    type Output = crate::v1::NesRelatedSnippet;
7194
7195    fn try_to_v1(self) -> Result<Self::Output> {
7196        let Self {
7197            uri,
7198            excerpts,
7199            meta,
7200        } = self;
7201        Ok(crate::v1::NesRelatedSnippet {
7202            uri: uri.try_to_v1()?,
7203            excerpts: excerpts.try_to_v1()?,
7204            meta: meta.try_to_v1()?,
7205        })
7206    }
7207}
7208
7209#[cfg(feature = "unstable_nes")]
7210impl TryToV2 for crate::v1::NesRelatedSnippet {
7211    type Output = super::NesRelatedSnippet;
7212
7213    fn try_to_v2(self) -> Result<Self::Output> {
7214        let Self {
7215            uri,
7216            excerpts,
7217            meta,
7218        } = self;
7219        Ok(super::NesRelatedSnippet {
7220            uri: uri.try_to_v2()?,
7221            excerpts: excerpts.try_to_v2()?,
7222            meta: meta.try_to_v2()?,
7223        })
7224    }
7225}
7226
7227#[cfg(feature = "unstable_nes")]
7228impl TryToV1 for super::NesExcerpt {
7229    type Output = crate::v1::NesExcerpt;
7230
7231    fn try_to_v1(self) -> Result<Self::Output> {
7232        let Self {
7233            start_line,
7234            end_line,
7235            text,
7236            meta,
7237        } = self;
7238        Ok(crate::v1::NesExcerpt {
7239            start_line: start_line.try_to_v1()?,
7240            end_line: end_line.try_to_v1()?,
7241            text: text.try_to_v1()?,
7242            meta: meta.try_to_v1()?,
7243        })
7244    }
7245}
7246
7247#[cfg(feature = "unstable_nes")]
7248impl TryToV2 for crate::v1::NesExcerpt {
7249    type Output = super::NesExcerpt;
7250
7251    fn try_to_v2(self) -> Result<Self::Output> {
7252        let Self {
7253            start_line,
7254            end_line,
7255            text,
7256            meta,
7257        } = self;
7258        Ok(super::NesExcerpt {
7259            start_line: start_line.try_to_v2()?,
7260            end_line: end_line.try_to_v2()?,
7261            text: text.try_to_v2()?,
7262            meta: meta.try_to_v2()?,
7263        })
7264    }
7265}
7266
7267#[cfg(feature = "unstable_nes")]
7268impl TryToV1 for super::NesEditHistoryEntry {
7269    type Output = crate::v1::NesEditHistoryEntry;
7270
7271    fn try_to_v1(self) -> Result<Self::Output> {
7272        let Self { uri, diff, meta } = self;
7273        Ok(crate::v1::NesEditHistoryEntry {
7274            uri: uri.try_to_v1()?,
7275            diff: diff.try_to_v1()?,
7276            meta: meta.try_to_v1()?,
7277        })
7278    }
7279}
7280
7281#[cfg(feature = "unstable_nes")]
7282impl TryToV2 for crate::v1::NesEditHistoryEntry {
7283    type Output = super::NesEditHistoryEntry;
7284
7285    fn try_to_v2(self) -> Result<Self::Output> {
7286        let Self { uri, diff, meta } = self;
7287        Ok(super::NesEditHistoryEntry {
7288            uri: uri.try_to_v2()?,
7289            diff: diff.try_to_v2()?,
7290            meta: meta.try_to_v2()?,
7291        })
7292    }
7293}
7294
7295#[cfg(feature = "unstable_nes")]
7296impl TryToV1 for super::NesUserAction {
7297    type Output = crate::v1::NesUserAction;
7298
7299    fn try_to_v1(self) -> Result<Self::Output> {
7300        let Self {
7301            action,
7302            uri,
7303            position,
7304            timestamp_ms,
7305            meta,
7306        } = self;
7307        Ok(crate::v1::NesUserAction {
7308            action: action.try_to_v1()?,
7309            uri: uri.try_to_v1()?,
7310            position: position.try_to_v1()?,
7311            timestamp_ms: timestamp_ms.try_to_v1()?,
7312            meta: meta.try_to_v1()?,
7313        })
7314    }
7315}
7316
7317#[cfg(feature = "unstable_nes")]
7318impl TryToV2 for crate::v1::NesUserAction {
7319    type Output = super::NesUserAction;
7320
7321    fn try_to_v2(self) -> Result<Self::Output> {
7322        let Self {
7323            action,
7324            uri,
7325            position,
7326            timestamp_ms,
7327            meta,
7328        } = self;
7329        Ok(super::NesUserAction {
7330            action: action.try_to_v2()?,
7331            uri: uri.try_to_v2()?,
7332            position: position.try_to_v2()?,
7333            timestamp_ms: timestamp_ms.try_to_v2()?,
7334            meta: meta.try_to_v2()?,
7335        })
7336    }
7337}
7338
7339#[cfg(feature = "unstable_nes")]
7340impl TryToV1 for super::NesOpenFile {
7341    type Output = crate::v1::NesOpenFile;
7342
7343    fn try_to_v1(self) -> Result<Self::Output> {
7344        let Self {
7345            uri,
7346            language_id,
7347            visible_range,
7348            last_focused_ms,
7349            meta,
7350        } = self;
7351        Ok(crate::v1::NesOpenFile {
7352            uri: uri.try_to_v1()?,
7353            language_id: language_id.try_to_v1()?,
7354            visible_range: visible_range.try_to_v1()?,
7355            last_focused_ms: last_focused_ms.try_to_v1()?,
7356            meta: meta.try_to_v1()?,
7357        })
7358    }
7359}
7360
7361#[cfg(feature = "unstable_nes")]
7362impl TryToV2 for crate::v1::NesOpenFile {
7363    type Output = super::NesOpenFile;
7364
7365    fn try_to_v2(self) -> Result<Self::Output> {
7366        let Self {
7367            uri,
7368            language_id,
7369            visible_range,
7370            last_focused_ms,
7371            meta,
7372        } = self;
7373        Ok(super::NesOpenFile {
7374            uri: uri.try_to_v2()?,
7375            language_id: language_id.try_to_v2()?,
7376            visible_range: visible_range.try_to_v2()?,
7377            last_focused_ms: last_focused_ms.try_to_v2()?,
7378            meta: meta.try_to_v2()?,
7379        })
7380    }
7381}
7382
7383#[cfg(feature = "unstable_nes")]
7384impl TryToV1 for super::NesDiagnostic {
7385    type Output = crate::v1::NesDiagnostic;
7386
7387    fn try_to_v1(self) -> Result<Self::Output> {
7388        let Self {
7389            uri,
7390            range,
7391            severity,
7392            message,
7393            meta,
7394        } = self;
7395        Ok(crate::v1::NesDiagnostic {
7396            uri: uri.try_to_v1()?,
7397            range: range.try_to_v1()?,
7398            severity: severity.try_to_v1()?,
7399            message: message.try_to_v1()?,
7400            meta: meta.try_to_v1()?,
7401        })
7402    }
7403}
7404
7405#[cfg(feature = "unstable_nes")]
7406impl TryToV2 for crate::v1::NesDiagnostic {
7407    type Output = super::NesDiagnostic;
7408
7409    fn try_to_v2(self) -> Result<Self::Output> {
7410        let Self {
7411            uri,
7412            range,
7413            severity,
7414            message,
7415            meta,
7416        } = self;
7417        Ok(super::NesDiagnostic {
7418            uri: uri.try_to_v2()?,
7419            range: range.try_to_v2()?,
7420            severity: severity.try_to_v2()?,
7421            message: message.try_to_v2()?,
7422            meta: meta.try_to_v2()?,
7423        })
7424    }
7425}
7426
7427#[cfg(feature = "unstable_nes")]
7428impl TryToV1 for super::NesDiagnosticSeverity {
7429    type Output = crate::v1::NesDiagnosticSeverity;
7430
7431    fn try_to_v1(self) -> Result<Self::Output> {
7432        Ok(match self {
7433            Self::Error => crate::v1::NesDiagnosticSeverity::Error,
7434            Self::Warning => crate::v1::NesDiagnosticSeverity::Warning,
7435            Self::Information => crate::v1::NesDiagnosticSeverity::Information,
7436            Self::Hint => crate::v1::NesDiagnosticSeverity::Hint,
7437            Self::Other(value) => {
7438                return Err(unknown_v2_enum_variant("NesDiagnosticSeverity", &value));
7439            }
7440        })
7441    }
7442}
7443
7444#[cfg(feature = "unstable_nes")]
7445impl TryToV2 for crate::v1::NesDiagnosticSeverity {
7446    type Output = super::NesDiagnosticSeverity;
7447
7448    fn try_to_v2(self) -> Result<Self::Output> {
7449        Ok(match self {
7450            Self::Error => super::NesDiagnosticSeverity::Error,
7451            Self::Warning => super::NesDiagnosticSeverity::Warning,
7452            Self::Information => super::NesDiagnosticSeverity::Information,
7453            Self::Hint => super::NesDiagnosticSeverity::Hint,
7454        })
7455    }
7456}
7457
7458#[cfg(feature = "unstable_nes")]
7459impl TryToV1 for super::SuggestNesResponse {
7460    type Output = crate::v1::SuggestNesResponse;
7461
7462    fn try_to_v1(self) -> Result<Self::Output> {
7463        let Self { suggestions, meta } = self;
7464        Ok(crate::v1::SuggestNesResponse {
7465            suggestions: suggestions.try_to_v1()?,
7466            meta: meta.try_to_v1()?,
7467        })
7468    }
7469}
7470
7471#[cfg(feature = "unstable_nes")]
7472impl TryToV2 for crate::v1::SuggestNesResponse {
7473    type Output = super::SuggestNesResponse;
7474
7475    fn try_to_v2(self) -> Result<Self::Output> {
7476        let Self { suggestions, meta } = self;
7477        Ok(super::SuggestNesResponse {
7478            suggestions: suggestions.try_to_v2()?,
7479            meta: meta.try_to_v2()?,
7480        })
7481    }
7482}
7483
7484#[cfg(feature = "unstable_nes")]
7485impl TryToV1 for super::NesSuggestion {
7486    type Output = crate::v1::NesSuggestion;
7487
7488    fn try_to_v1(self) -> Result<Self::Output> {
7489        Ok(match self {
7490            Self::Edit(value) => crate::v1::NesSuggestion::Edit(value.try_to_v1()?),
7491            Self::Jump(value) => crate::v1::NesSuggestion::Jump(value.try_to_v1()?),
7492            Self::Rename(value) => crate::v1::NesSuggestion::Rename(value.try_to_v1()?),
7493            Self::SearchAndReplace(value) => {
7494                crate::v1::NesSuggestion::SearchAndReplace(value.try_to_v1()?)
7495            }
7496            Self::Other(value) => {
7497                return Err(unknown_v2_enum_variant("NesSuggestion", &value.kind));
7498            }
7499        })
7500    }
7501}
7502
7503#[cfg(feature = "unstable_nes")]
7504impl TryToV2 for crate::v1::NesSuggestion {
7505    type Output = super::NesSuggestion;
7506
7507    fn try_to_v2(self) -> Result<Self::Output> {
7508        Ok(match self {
7509            Self::Edit(value) => super::NesSuggestion::Edit(value.try_to_v2()?),
7510            Self::Jump(value) => super::NesSuggestion::Jump(value.try_to_v2()?),
7511            Self::Rename(value) => super::NesSuggestion::Rename(value.try_to_v2()?),
7512            Self::SearchAndReplace(value) => {
7513                super::NesSuggestion::SearchAndReplace(value.try_to_v2()?)
7514            }
7515        })
7516    }
7517}
7518
7519#[cfg(feature = "unstable_nes")]
7520impl TryToV1 for super::NesSuggestionId {
7521    type Output = crate::v1::NesSuggestionId;
7522
7523    fn try_to_v1(self) -> Result<Self::Output> {
7524        Ok(crate::v1::NesSuggestionId(self.0.try_to_v1()?))
7525    }
7526}
7527
7528#[cfg(feature = "unstable_nes")]
7529impl TryToV2 for crate::v1::NesSuggestionId {
7530    type Output = super::NesSuggestionId;
7531
7532    fn try_to_v2(self) -> Result<Self::Output> {
7533        Ok(super::NesSuggestionId(self.0.try_to_v2()?))
7534    }
7535}
7536
7537#[cfg(feature = "unstable_nes")]
7538impl TryToV1 for super::NesEditSuggestion {
7539    type Output = crate::v1::NesEditSuggestion;
7540
7541    fn try_to_v1(self) -> Result<Self::Output> {
7542        let Self {
7543            suggestion_id,
7544            uri,
7545            edits,
7546            cursor_position,
7547            meta,
7548        } = self;
7549        Ok(crate::v1::NesEditSuggestion {
7550            id: suggestion_id.try_to_v1()?,
7551            uri: uri.try_to_v1()?,
7552            edits: edits.try_to_v1()?,
7553            cursor_position: cursor_position.try_to_v1()?,
7554            meta: meta.try_to_v1()?,
7555        })
7556    }
7557}
7558
7559#[cfg(feature = "unstable_nes")]
7560impl TryToV2 for crate::v1::NesEditSuggestion {
7561    type Output = super::NesEditSuggestion;
7562
7563    fn try_to_v2(self) -> Result<Self::Output> {
7564        let Self {
7565            id,
7566            uri,
7567            edits,
7568            cursor_position,
7569            meta,
7570        } = self;
7571        Ok(super::NesEditSuggestion {
7572            suggestion_id: id.try_to_v2()?,
7573            uri: uri.try_to_v2()?,
7574            edits: edits.try_to_v2()?,
7575            cursor_position: cursor_position.try_to_v2()?,
7576            meta: meta.try_to_v2()?,
7577        })
7578    }
7579}
7580
7581#[cfg(feature = "unstable_nes")]
7582impl TryToV1 for super::NesTextEdit {
7583    type Output = crate::v1::NesTextEdit;
7584
7585    fn try_to_v1(self) -> Result<Self::Output> {
7586        let Self {
7587            range,
7588            new_text,
7589            meta,
7590        } = self;
7591        Ok(crate::v1::NesTextEdit {
7592            range: range.try_to_v1()?,
7593            new_text: new_text.try_to_v1()?,
7594            meta: meta.try_to_v1()?,
7595        })
7596    }
7597}
7598
7599#[cfg(feature = "unstable_nes")]
7600impl TryToV2 for crate::v1::NesTextEdit {
7601    type Output = super::NesTextEdit;
7602
7603    fn try_to_v2(self) -> Result<Self::Output> {
7604        let Self {
7605            range,
7606            new_text,
7607            meta,
7608        } = self;
7609        Ok(super::NesTextEdit {
7610            range: range.try_to_v2()?,
7611            new_text: new_text.try_to_v2()?,
7612            meta: meta.try_to_v2()?,
7613        })
7614    }
7615}
7616
7617#[cfg(feature = "unstable_nes")]
7618impl TryToV1 for super::NesJumpSuggestion {
7619    type Output = crate::v1::NesJumpSuggestion;
7620
7621    fn try_to_v1(self) -> Result<Self::Output> {
7622        let Self {
7623            suggestion_id,
7624            uri,
7625            position,
7626            meta,
7627        } = self;
7628        Ok(crate::v1::NesJumpSuggestion {
7629            id: suggestion_id.try_to_v1()?,
7630            uri: uri.try_to_v1()?,
7631            position: position.try_to_v1()?,
7632            meta: meta.try_to_v1()?,
7633        })
7634    }
7635}
7636
7637#[cfg(feature = "unstable_nes")]
7638impl TryToV2 for crate::v1::NesJumpSuggestion {
7639    type Output = super::NesJumpSuggestion;
7640
7641    fn try_to_v2(self) -> Result<Self::Output> {
7642        let Self {
7643            id,
7644            uri,
7645            position,
7646            meta,
7647        } = self;
7648        Ok(super::NesJumpSuggestion {
7649            suggestion_id: id.try_to_v2()?,
7650            uri: uri.try_to_v2()?,
7651            position: position.try_to_v2()?,
7652            meta: meta.try_to_v2()?,
7653        })
7654    }
7655}
7656
7657#[cfg(feature = "unstable_nes")]
7658impl TryToV1 for super::NesRenameSuggestion {
7659    type Output = crate::v1::NesRenameSuggestion;
7660
7661    fn try_to_v1(self) -> Result<Self::Output> {
7662        let Self {
7663            suggestion_id,
7664            uri,
7665            position,
7666            new_name,
7667            meta,
7668        } = self;
7669        Ok(crate::v1::NesRenameSuggestion {
7670            id: suggestion_id.try_to_v1()?,
7671            uri: uri.try_to_v1()?,
7672            position: position.try_to_v1()?,
7673            new_name: new_name.try_to_v1()?,
7674            meta: meta.try_to_v1()?,
7675        })
7676    }
7677}
7678
7679#[cfg(feature = "unstable_nes")]
7680impl TryToV2 for crate::v1::NesRenameSuggestion {
7681    type Output = super::NesRenameSuggestion;
7682
7683    fn try_to_v2(self) -> Result<Self::Output> {
7684        let Self {
7685            id,
7686            uri,
7687            position,
7688            new_name,
7689            meta,
7690        } = self;
7691        Ok(super::NesRenameSuggestion {
7692            suggestion_id: id.try_to_v2()?,
7693            uri: uri.try_to_v2()?,
7694            position: position.try_to_v2()?,
7695            new_name: new_name.try_to_v2()?,
7696            meta: meta.try_to_v2()?,
7697        })
7698    }
7699}
7700
7701#[cfg(feature = "unstable_nes")]
7702impl TryToV1 for super::NesSearchAndReplaceSuggestion {
7703    type Output = crate::v1::NesSearchAndReplaceSuggestion;
7704
7705    fn try_to_v1(self) -> Result<Self::Output> {
7706        let Self {
7707            suggestion_id,
7708            uri,
7709            search,
7710            replace,
7711            is_regex,
7712            meta,
7713        } = self;
7714        Ok(crate::v1::NesSearchAndReplaceSuggestion {
7715            id: suggestion_id.try_to_v1()?,
7716            uri: uri.try_to_v1()?,
7717            search: search.try_to_v1()?,
7718            replace: replace.try_to_v1()?,
7719            is_regex: is_regex.try_to_v1()?,
7720            meta: meta.try_to_v1()?,
7721        })
7722    }
7723}
7724
7725#[cfg(feature = "unstable_nes")]
7726impl TryToV2 for crate::v1::NesSearchAndReplaceSuggestion {
7727    type Output = super::NesSearchAndReplaceSuggestion;
7728
7729    fn try_to_v2(self) -> Result<Self::Output> {
7730        let Self {
7731            id,
7732            uri,
7733            search,
7734            replace,
7735            is_regex,
7736            meta,
7737        } = self;
7738        Ok(super::NesSearchAndReplaceSuggestion {
7739            suggestion_id: id.try_to_v2()?,
7740            uri: uri.try_to_v2()?,
7741            search: search.try_to_v2()?,
7742            replace: replace.try_to_v2()?,
7743            is_regex: is_regex.try_to_v2()?,
7744            meta: meta.try_to_v2()?,
7745        })
7746    }
7747}
7748
7749#[cfg(feature = "unstable_nes")]
7750impl TryToV1 for super::AcceptNesNotification {
7751    type Output = crate::v1::AcceptNesNotification;
7752
7753    fn try_to_v1(self) -> Result<Self::Output> {
7754        let Self {
7755            session_id,
7756            suggestion_id,
7757            meta,
7758        } = self;
7759        Ok(crate::v1::AcceptNesNotification {
7760            session_id: session_id.try_to_v1()?,
7761            id: suggestion_id.try_to_v1()?,
7762            meta: meta.try_to_v1()?,
7763        })
7764    }
7765}
7766
7767#[cfg(feature = "unstable_nes")]
7768impl TryToV2 for crate::v1::AcceptNesNotification {
7769    type Output = super::AcceptNesNotification;
7770
7771    fn try_to_v2(self) -> Result<Self::Output> {
7772        let Self {
7773            session_id,
7774            id,
7775            meta,
7776        } = self;
7777        Ok(super::AcceptNesNotification {
7778            session_id: session_id.try_to_v2()?,
7779            suggestion_id: id.try_to_v2()?,
7780            meta: meta.try_to_v2()?,
7781        })
7782    }
7783}
7784
7785#[cfg(feature = "unstable_nes")]
7786impl TryToV1 for super::RejectNesNotification {
7787    type Output = crate::v1::RejectNesNotification;
7788
7789    fn try_to_v1(self) -> Result<Self::Output> {
7790        let Self {
7791            session_id,
7792            suggestion_id,
7793            reason,
7794            meta,
7795        } = self;
7796        Ok(crate::v1::RejectNesNotification {
7797            session_id: session_id.try_to_v1()?,
7798            id: suggestion_id.try_to_v1()?,
7799            reason: reason.try_to_v1()?,
7800            meta: meta.try_to_v1()?,
7801        })
7802    }
7803}
7804
7805#[cfg(feature = "unstable_nes")]
7806impl TryToV2 for crate::v1::RejectNesNotification {
7807    type Output = super::RejectNesNotification;
7808
7809    fn try_to_v2(self) -> Result<Self::Output> {
7810        let Self {
7811            session_id,
7812            id,
7813            reason,
7814            meta,
7815        } = self;
7816        Ok(super::RejectNesNotification {
7817            session_id: session_id.try_to_v2()?,
7818            suggestion_id: id.try_to_v2()?,
7819            reason: reason.try_to_v2()?,
7820            meta: meta.try_to_v2()?,
7821        })
7822    }
7823}
7824
7825#[cfg(feature = "unstable_nes")]
7826impl TryToV1 for super::NesRejectReason {
7827    type Output = crate::v1::NesRejectReason;
7828
7829    fn try_to_v1(self) -> Result<Self::Output> {
7830        Ok(match self {
7831            Self::Rejected => crate::v1::NesRejectReason::Rejected,
7832            Self::Ignored => crate::v1::NesRejectReason::Ignored,
7833            Self::Replaced => crate::v1::NesRejectReason::Replaced,
7834            Self::Cancelled => crate::v1::NesRejectReason::Cancelled,
7835            Self::Other(value) => return Err(unknown_v2_enum_variant("NesRejectReason", &value)),
7836        })
7837    }
7838}
7839
7840#[cfg(feature = "unstable_nes")]
7841impl TryToV2 for crate::v1::NesRejectReason {
7842    type Output = super::NesRejectReason;
7843
7844    fn try_to_v2(self) -> Result<Self::Output> {
7845        Ok(match self {
7846            Self::Rejected => super::NesRejectReason::Rejected,
7847            Self::Ignored => super::NesRejectReason::Ignored,
7848            Self::Replaced => super::NesRejectReason::Replaced,
7849            Self::Cancelled => super::NesRejectReason::Cancelled,
7850        })
7851    }
7852}
7853
7854#[cfg(feature = "unstable_elicitation")]
7855impl TryToV1 for super::ElicitationId {
7856    type Output = crate::v1::ElicitationId;
7857
7858    fn try_to_v1(self) -> Result<Self::Output> {
7859        Ok(crate::v1::ElicitationId(self.0.try_to_v1()?))
7860    }
7861}
7862
7863#[cfg(feature = "unstable_elicitation")]
7864impl TryToV2 for crate::v1::ElicitationId {
7865    type Output = super::ElicitationId;
7866
7867    fn try_to_v2(self) -> Result<Self::Output> {
7868        Ok(super::ElicitationId(self.0.try_to_v2()?))
7869    }
7870}
7871
7872#[cfg(feature = "unstable_elicitation")]
7873impl TryToV1 for super::StringFormat {
7874    type Output = crate::v1::StringFormat;
7875
7876    fn try_to_v1(self) -> Result<Self::Output> {
7877        Ok(match self {
7878            Self::Email => crate::v1::StringFormat::Email,
7879            Self::Uri => crate::v1::StringFormat::Uri,
7880            Self::Date => crate::v1::StringFormat::Date,
7881            Self::DateTime => crate::v1::StringFormat::DateTime,
7882            Self::Other(value) => return Err(unknown_v2_enum_variant("StringFormat", &value)),
7883        })
7884    }
7885}
7886
7887#[cfg(feature = "unstable_elicitation")]
7888impl TryToV2 for crate::v1::StringFormat {
7889    type Output = super::StringFormat;
7890
7891    fn try_to_v2(self) -> Result<Self::Output> {
7892        Ok(match self {
7893            Self::Email => super::StringFormat::Email,
7894            Self::Uri => super::StringFormat::Uri,
7895            Self::Date => super::StringFormat::Date,
7896            Self::DateTime => super::StringFormat::DateTime,
7897        })
7898    }
7899}
7900
7901#[cfg(feature = "unstable_elicitation")]
7902impl TryToV1 for super::ElicitationSchemaType {
7903    type Output = crate::v1::ElicitationSchemaType;
7904
7905    fn try_to_v1(self) -> Result<Self::Output> {
7906        Ok(match self {
7907            Self::Object => crate::v1::ElicitationSchemaType::Object,
7908        })
7909    }
7910}
7911
7912#[cfg(feature = "unstable_elicitation")]
7913impl TryToV2 for crate::v1::ElicitationSchemaType {
7914    type Output = super::ElicitationSchemaType;
7915
7916    fn try_to_v2(self) -> Result<Self::Output> {
7917        Ok(match self {
7918            Self::Object => super::ElicitationSchemaType::Object,
7919        })
7920    }
7921}
7922
7923#[cfg(feature = "unstable_elicitation")]
7924impl TryToV1 for super::EnumOption {
7925    type Output = crate::v1::EnumOption;
7926
7927    fn try_to_v1(self) -> Result<Self::Output> {
7928        let Self {
7929            value,
7930            title,
7931            description,
7932            meta,
7933        } = self;
7934        Ok(crate::v1::EnumOption {
7935            value: value.try_to_v1()?,
7936            title: title.try_to_v1()?,
7937            description: description.try_to_v1()?,
7938            meta: meta.try_to_v1()?,
7939        })
7940    }
7941}
7942
7943#[cfg(feature = "unstable_elicitation")]
7944impl TryToV2 for crate::v1::EnumOption {
7945    type Output = super::EnumOption;
7946
7947    fn try_to_v2(self) -> Result<Self::Output> {
7948        let Self {
7949            value,
7950            title,
7951            description,
7952            meta,
7953        } = self;
7954        Ok(super::EnumOption {
7955            value: value.try_to_v2()?,
7956            title: title.try_to_v2()?,
7957            description: description.try_to_v2()?,
7958            meta: meta.try_to_v2()?,
7959        })
7960    }
7961}
7962
7963#[cfg(feature = "unstable_elicitation")]
7964impl TryToV1 for super::StringPropertySchema {
7965    type Output = crate::v1::StringPropertySchema;
7966
7967    fn try_to_v1(self) -> Result<Self::Output> {
7968        let Self {
7969            title,
7970            description,
7971            min_length,
7972            max_length,
7973            pattern,
7974            format,
7975            default,
7976            enum_values,
7977            one_of,
7978            meta,
7979        } = self;
7980        Ok(crate::v1::StringPropertySchema {
7981            title: title.try_to_v1()?,
7982            description: description.try_to_v1()?,
7983            min_length: min_length.try_to_v1()?,
7984            max_length: max_length.try_to_v1()?,
7985            pattern: pattern.try_to_v1()?,
7986            format: format.try_to_v1()?,
7987            default: default.try_to_v1()?,
7988            enum_values: enum_values.try_to_v1()?,
7989            one_of: one_of.try_to_v1()?,
7990            meta: meta.try_to_v1()?,
7991        })
7992    }
7993}
7994
7995#[cfg(feature = "unstable_elicitation")]
7996impl TryToV2 for crate::v1::StringPropertySchema {
7997    type Output = super::StringPropertySchema;
7998
7999    fn try_to_v2(self) -> Result<Self::Output> {
8000        let Self {
8001            title,
8002            description,
8003            min_length,
8004            max_length,
8005            pattern,
8006            format,
8007            default,
8008            enum_values,
8009            one_of,
8010            meta,
8011        } = self;
8012        Ok(super::StringPropertySchema {
8013            title: title.try_to_v2()?,
8014            description: description.try_to_v2()?,
8015            min_length: min_length.try_to_v2()?,
8016            max_length: max_length.try_to_v2()?,
8017            pattern: pattern.try_to_v2()?,
8018            format: format.try_to_v2()?,
8019            default: default.try_to_v2()?,
8020            enum_values: enum_values.try_to_v2()?,
8021            one_of: one_of.try_to_v2()?,
8022            meta: meta.try_to_v2()?,
8023        })
8024    }
8025}
8026
8027#[cfg(feature = "unstable_elicitation")]
8028impl TryToV1 for super::NumberPropertySchema {
8029    type Output = crate::v1::NumberPropertySchema;
8030
8031    fn try_to_v1(self) -> Result<Self::Output> {
8032        let Self {
8033            title,
8034            description,
8035            minimum,
8036            maximum,
8037            default,
8038            meta,
8039        } = self;
8040        Ok(crate::v1::NumberPropertySchema {
8041            title: title.try_to_v1()?,
8042            description: description.try_to_v1()?,
8043            minimum: minimum.try_to_v1()?,
8044            maximum: maximum.try_to_v1()?,
8045            default: default.try_to_v1()?,
8046            meta: meta.try_to_v1()?,
8047        })
8048    }
8049}
8050
8051#[cfg(feature = "unstable_elicitation")]
8052impl TryToV2 for crate::v1::NumberPropertySchema {
8053    type Output = super::NumberPropertySchema;
8054
8055    fn try_to_v2(self) -> Result<Self::Output> {
8056        let Self {
8057            title,
8058            description,
8059            minimum,
8060            maximum,
8061            default,
8062            meta,
8063        } = self;
8064        Ok(super::NumberPropertySchema {
8065            title: title.try_to_v2()?,
8066            description: description.try_to_v2()?,
8067            minimum: minimum.try_to_v2()?,
8068            maximum: maximum.try_to_v2()?,
8069            default: default.try_to_v2()?,
8070            meta: meta.try_to_v2()?,
8071        })
8072    }
8073}
8074
8075#[cfg(feature = "unstable_elicitation")]
8076impl TryToV1 for super::IntegerPropertySchema {
8077    type Output = crate::v1::IntegerPropertySchema;
8078
8079    fn try_to_v1(self) -> Result<Self::Output> {
8080        let Self {
8081            title,
8082            description,
8083            minimum,
8084            maximum,
8085            default,
8086            meta,
8087        } = self;
8088        Ok(crate::v1::IntegerPropertySchema {
8089            title: title.try_to_v1()?,
8090            description: description.try_to_v1()?,
8091            minimum: minimum.try_to_v1()?,
8092            maximum: maximum.try_to_v1()?,
8093            default: default.try_to_v1()?,
8094            meta: meta.try_to_v1()?,
8095        })
8096    }
8097}
8098
8099#[cfg(feature = "unstable_elicitation")]
8100impl TryToV2 for crate::v1::IntegerPropertySchema {
8101    type Output = super::IntegerPropertySchema;
8102
8103    fn try_to_v2(self) -> Result<Self::Output> {
8104        let Self {
8105            title,
8106            description,
8107            minimum,
8108            maximum,
8109            default,
8110            meta,
8111        } = self;
8112        Ok(super::IntegerPropertySchema {
8113            title: title.try_to_v2()?,
8114            description: description.try_to_v2()?,
8115            minimum: minimum.try_to_v2()?,
8116            maximum: maximum.try_to_v2()?,
8117            default: default.try_to_v2()?,
8118            meta: meta.try_to_v2()?,
8119        })
8120    }
8121}
8122
8123#[cfg(feature = "unstable_elicitation")]
8124impl TryToV1 for super::BooleanPropertySchema {
8125    type Output = crate::v1::BooleanPropertySchema;
8126
8127    fn try_to_v1(self) -> Result<Self::Output> {
8128        let Self {
8129            title,
8130            description,
8131            default,
8132            meta,
8133        } = self;
8134        Ok(crate::v1::BooleanPropertySchema {
8135            title: title.try_to_v1()?,
8136            description: description.try_to_v1()?,
8137            default: default.try_to_v1()?,
8138            meta: meta.try_to_v1()?,
8139        })
8140    }
8141}
8142
8143#[cfg(feature = "unstable_elicitation")]
8144impl TryToV2 for crate::v1::BooleanPropertySchema {
8145    type Output = super::BooleanPropertySchema;
8146
8147    fn try_to_v2(self) -> Result<Self::Output> {
8148        let Self {
8149            title,
8150            description,
8151            default,
8152            meta,
8153        } = self;
8154        Ok(super::BooleanPropertySchema {
8155            title: title.try_to_v2()?,
8156            description: description.try_to_v2()?,
8157            default: default.try_to_v2()?,
8158            meta: meta.try_to_v2()?,
8159        })
8160    }
8161}
8162
8163#[cfg(feature = "unstable_elicitation")]
8164impl TryToV1 for super::StringMultiSelectItems {
8165    type Output = crate::v1::StringMultiSelectItems;
8166
8167    fn try_to_v1(self) -> Result<Self::Output> {
8168        let Self { values, meta } = self;
8169        Ok(crate::v1::StringMultiSelectItems {
8170            values: values.try_to_v1()?,
8171            meta: meta.try_to_v1()?,
8172        })
8173    }
8174}
8175
8176#[cfg(feature = "unstable_elicitation")]
8177impl TryToV2 for crate::v1::StringMultiSelectItems {
8178    type Output = super::StringMultiSelectItems;
8179
8180    fn try_to_v2(self) -> Result<Self::Output> {
8181        let Self { values, meta } = self;
8182        Ok(super::StringMultiSelectItems {
8183            values: values.try_to_v2()?,
8184            meta: meta.try_to_v2()?,
8185        })
8186    }
8187}
8188
8189#[cfg(feature = "unstable_elicitation")]
8190impl TryToV1 for super::OtherMultiSelectItems {
8191    type Output = crate::v1::OtherMultiSelectItems;
8192
8193    fn try_to_v1(self) -> Result<Self::Output> {
8194        let Self { type_, fields } = self;
8195        Ok(crate::v1::OtherMultiSelectItems {
8196            type_: type_.try_to_v1()?,
8197            fields: fields.try_to_v1()?,
8198        })
8199    }
8200}
8201
8202#[cfg(feature = "unstable_elicitation")]
8203impl TryToV2 for crate::v1::OtherMultiSelectItems {
8204    type Output = super::OtherMultiSelectItems;
8205
8206    fn try_to_v2(self) -> Result<Self::Output> {
8207        let Self { type_, fields } = self;
8208        Ok(super::OtherMultiSelectItems {
8209            type_: type_.try_to_v2()?,
8210            fields: fields.try_to_v2()?,
8211        })
8212    }
8213}
8214
8215#[cfg(feature = "unstable_elicitation")]
8216impl TryToV1 for super::TitledMultiSelectItems {
8217    type Output = crate::v1::TitledMultiSelectItems;
8218
8219    fn try_to_v1(self) -> Result<Self::Output> {
8220        let Self { options, meta } = self;
8221        Ok(crate::v1::TitledMultiSelectItems {
8222            options: options.try_to_v1()?,
8223            meta: meta.try_to_v1()?,
8224        })
8225    }
8226}
8227
8228#[cfg(feature = "unstable_elicitation")]
8229impl TryToV2 for crate::v1::TitledMultiSelectItems {
8230    type Output = super::TitledMultiSelectItems;
8231
8232    fn try_to_v2(self) -> Result<Self::Output> {
8233        let Self { options, meta } = self;
8234        Ok(super::TitledMultiSelectItems {
8235            options: options.try_to_v2()?,
8236            meta: meta.try_to_v2()?,
8237        })
8238    }
8239}
8240
8241#[cfg(feature = "unstable_elicitation")]
8242impl TryToV1 for super::MultiSelectItems {
8243    type Output = crate::v1::MultiSelectItems;
8244
8245    fn try_to_v1(self) -> Result<Self::Output> {
8246        Ok(match self {
8247            Self::String(value) => crate::v1::MultiSelectItems::String(value.try_to_v1()?),
8248            Self::Other(value) => crate::v1::MultiSelectItems::Other(value.try_to_v1()?),
8249            Self::Titled(value) => crate::v1::MultiSelectItems::Titled(value.try_to_v1()?),
8250        })
8251    }
8252}
8253
8254#[cfg(feature = "unstable_elicitation")]
8255impl TryToV2 for crate::v1::MultiSelectItems {
8256    type Output = super::MultiSelectItems;
8257
8258    fn try_to_v2(self) -> Result<Self::Output> {
8259        Ok(match self {
8260            Self::String(value) => super::MultiSelectItems::String(value.try_to_v2()?),
8261            Self::Other(value) => super::MultiSelectItems::Other(value.try_to_v2()?),
8262            Self::Titled(value) => super::MultiSelectItems::Titled(value.try_to_v2()?),
8263        })
8264    }
8265}
8266
8267#[cfg(feature = "unstable_elicitation")]
8268impl TryToV1 for super::MultiSelectPropertySchema {
8269    type Output = crate::v1::MultiSelectPropertySchema;
8270
8271    fn try_to_v1(self) -> Result<Self::Output> {
8272        let Self {
8273            title,
8274            description,
8275            min_items,
8276            max_items,
8277            items,
8278            default,
8279            meta,
8280        } = self;
8281        Ok(crate::v1::MultiSelectPropertySchema {
8282            title: title.try_to_v1()?,
8283            description: description.try_to_v1()?,
8284            min_items: min_items.try_to_v1()?,
8285            max_items: max_items.try_to_v1()?,
8286            items: items.try_to_v1()?,
8287            default: default.try_to_v1()?,
8288            meta: meta.try_to_v1()?,
8289        })
8290    }
8291}
8292
8293#[cfg(feature = "unstable_elicitation")]
8294impl TryToV2 for crate::v1::MultiSelectPropertySchema {
8295    type Output = super::MultiSelectPropertySchema;
8296
8297    fn try_to_v2(self) -> Result<Self::Output> {
8298        let Self {
8299            title,
8300            description,
8301            min_items,
8302            max_items,
8303            items,
8304            default,
8305            meta,
8306        } = self;
8307        Ok(super::MultiSelectPropertySchema {
8308            title: title.try_to_v2()?,
8309            description: description.try_to_v2()?,
8310            min_items: min_items.try_to_v2()?,
8311            max_items: max_items.try_to_v2()?,
8312            items: items.try_to_v2()?,
8313            default: default.try_to_v2()?,
8314            meta: meta.try_to_v2()?,
8315        })
8316    }
8317}
8318
8319#[cfg(feature = "unstable_elicitation")]
8320impl TryToV1 for super::ElicitationPropertySchema {
8321    type Output = crate::v1::ElicitationPropertySchema;
8322
8323    fn try_to_v1(self) -> Result<Self::Output> {
8324        Ok(match self {
8325            Self::String(value) => crate::v1::ElicitationPropertySchema::String(value.try_to_v1()?),
8326            Self::Number(value) => crate::v1::ElicitationPropertySchema::Number(value.try_to_v1()?),
8327            Self::Integer(value) => {
8328                crate::v1::ElicitationPropertySchema::Integer(value.try_to_v1()?)
8329            }
8330            Self::Boolean(value) => {
8331                crate::v1::ElicitationPropertySchema::Boolean(value.try_to_v1()?)
8332            }
8333            Self::Array(value) => crate::v1::ElicitationPropertySchema::Array(value.try_to_v1()?),
8334            Self::Other(value) => crate::v1::ElicitationPropertySchema::Other(value.try_to_v1()?),
8335        })
8336    }
8337}
8338
8339#[cfg(feature = "unstable_elicitation")]
8340impl TryToV2 for crate::v1::ElicitationPropertySchema {
8341    type Output = super::ElicitationPropertySchema;
8342
8343    fn try_to_v2(self) -> Result<Self::Output> {
8344        Ok(match self {
8345            Self::String(value) => super::ElicitationPropertySchema::String(value.try_to_v2()?),
8346            Self::Number(value) => super::ElicitationPropertySchema::Number(value.try_to_v2()?),
8347            Self::Integer(value) => super::ElicitationPropertySchema::Integer(value.try_to_v2()?),
8348            Self::Boolean(value) => super::ElicitationPropertySchema::Boolean(value.try_to_v2()?),
8349            Self::Array(value) => super::ElicitationPropertySchema::Array(value.try_to_v2()?),
8350            Self::Other(value) => super::ElicitationPropertySchema::Other(value.try_to_v2()?),
8351        })
8352    }
8353}
8354
8355#[cfg(feature = "unstable_elicitation")]
8356impl TryToV1 for super::OtherElicitationPropertySchema {
8357    type Output = crate::v1::OtherElicitationPropertySchema;
8358
8359    fn try_to_v1(self) -> Result<Self::Output> {
8360        let Self { type_, fields } = self;
8361        Ok(crate::v1::OtherElicitationPropertySchema {
8362            type_: type_.try_to_v1()?,
8363            fields: fields.try_to_v1()?,
8364        })
8365    }
8366}
8367
8368#[cfg(feature = "unstable_elicitation")]
8369impl TryToV2 for crate::v1::OtherElicitationPropertySchema {
8370    type Output = super::OtherElicitationPropertySchema;
8371
8372    fn try_to_v2(self) -> Result<Self::Output> {
8373        let Self { type_, fields } = self;
8374        Ok(super::OtherElicitationPropertySchema {
8375            type_: type_.try_to_v2()?,
8376            fields: fields.try_to_v2()?,
8377        })
8378    }
8379}
8380
8381#[cfg(feature = "unstable_elicitation")]
8382impl TryToV1 for super::ElicitationSchema {
8383    type Output = crate::v1::ElicitationSchema;
8384
8385    fn try_to_v1(self) -> Result<Self::Output> {
8386        let Self {
8387            type_,
8388            title,
8389            properties,
8390            required,
8391            description,
8392            meta,
8393        } = self;
8394        Ok(crate::v1::ElicitationSchema {
8395            type_: type_.try_to_v1()?,
8396            title: title.try_to_v1()?,
8397            properties: properties.try_to_v1()?,
8398            required: required.try_to_v1()?,
8399            description: description.try_to_v1()?,
8400            meta: meta.try_to_v1()?,
8401        })
8402    }
8403}
8404
8405#[cfg(feature = "unstable_elicitation")]
8406impl TryToV2 for crate::v1::ElicitationSchema {
8407    type Output = super::ElicitationSchema;
8408
8409    fn try_to_v2(self) -> Result<Self::Output> {
8410        let Self {
8411            type_,
8412            title,
8413            properties,
8414            required,
8415            description,
8416            meta,
8417        } = self;
8418        Ok(super::ElicitationSchema {
8419            type_: type_.try_to_v2()?,
8420            title: title.try_to_v2()?,
8421            properties: properties.try_to_v2()?,
8422            required: required.try_to_v2()?,
8423            description: description.try_to_v2()?,
8424            meta: meta.try_to_v2()?,
8425        })
8426    }
8427}
8428
8429#[cfg(feature = "unstable_elicitation")]
8430impl TryToV1 for super::ElicitationCapabilities {
8431    type Output = crate::v1::ElicitationCapabilities;
8432
8433    fn try_to_v1(self) -> Result<Self::Output> {
8434        let Self { form, url, meta } = self;
8435        Ok(crate::v1::ElicitationCapabilities {
8436            form: form.try_to_v1()?,
8437            url: url.try_to_v1()?,
8438            meta: meta.try_to_v1()?,
8439        })
8440    }
8441}
8442
8443#[cfg(feature = "unstable_elicitation")]
8444impl TryToV2 for crate::v1::ElicitationCapabilities {
8445    type Output = super::ElicitationCapabilities;
8446
8447    fn try_to_v2(self) -> Result<Self::Output> {
8448        let Self { form, url, meta } = self;
8449        Ok(super::ElicitationCapabilities {
8450            form: form.try_to_v2()?,
8451            url: url.try_to_v2()?,
8452            meta: meta.try_to_v2()?,
8453        })
8454    }
8455}
8456
8457#[cfg(feature = "unstable_elicitation")]
8458impl TryToV1 for super::ElicitationFormCapabilities {
8459    type Output = crate::v1::ElicitationFormCapabilities;
8460
8461    fn try_to_v1(self) -> Result<Self::Output> {
8462        let Self { meta } = self;
8463        Ok(crate::v1::ElicitationFormCapabilities {
8464            meta: meta.try_to_v1()?,
8465        })
8466    }
8467}
8468
8469#[cfg(feature = "unstable_elicitation")]
8470impl TryToV2 for crate::v1::ElicitationFormCapabilities {
8471    type Output = super::ElicitationFormCapabilities;
8472
8473    fn try_to_v2(self) -> Result<Self::Output> {
8474        let Self { meta } = self;
8475        Ok(super::ElicitationFormCapabilities {
8476            meta: meta.try_to_v2()?,
8477        })
8478    }
8479}
8480
8481#[cfg(feature = "unstable_elicitation")]
8482impl TryToV1 for super::ElicitationUrlCapabilities {
8483    type Output = crate::v1::ElicitationUrlCapabilities;
8484
8485    fn try_to_v1(self) -> Result<Self::Output> {
8486        let Self { meta } = self;
8487        Ok(crate::v1::ElicitationUrlCapabilities {
8488            meta: meta.try_to_v1()?,
8489        })
8490    }
8491}
8492
8493#[cfg(feature = "unstable_elicitation")]
8494impl TryToV2 for crate::v1::ElicitationUrlCapabilities {
8495    type Output = super::ElicitationUrlCapabilities;
8496
8497    fn try_to_v2(self) -> Result<Self::Output> {
8498        let Self { meta } = self;
8499        Ok(super::ElicitationUrlCapabilities {
8500            meta: meta.try_to_v2()?,
8501        })
8502    }
8503}
8504
8505#[cfg(feature = "unstable_elicitation")]
8506impl TryToV1 for super::ElicitationScope {
8507    type Output = crate::v1::ElicitationScope;
8508
8509    fn try_to_v1(self) -> Result<Self::Output> {
8510        Ok(match self {
8511            Self::Session(value) => crate::v1::ElicitationScope::Session(value.try_to_v1()?),
8512            Self::Request(value) => crate::v1::ElicitationScope::Request(value.try_to_v1()?),
8513        })
8514    }
8515}
8516
8517#[cfg(feature = "unstable_elicitation")]
8518impl TryToV2 for crate::v1::ElicitationScope {
8519    type Output = super::ElicitationScope;
8520
8521    fn try_to_v2(self) -> Result<Self::Output> {
8522        Ok(match self {
8523            Self::Session(value) => super::ElicitationScope::Session(value.try_to_v2()?),
8524            Self::Request(value) => super::ElicitationScope::Request(value.try_to_v2()?),
8525        })
8526    }
8527}
8528
8529#[cfg(feature = "unstable_elicitation")]
8530impl TryToV1 for super::ElicitationSessionScope {
8531    type Output = crate::v1::ElicitationSessionScope;
8532
8533    fn try_to_v1(self) -> Result<Self::Output> {
8534        let Self {
8535            session_id,
8536            tool_call_id,
8537        } = self;
8538        Ok(crate::v1::ElicitationSessionScope {
8539            session_id: session_id.try_to_v1()?,
8540            tool_call_id: tool_call_id.try_to_v1()?,
8541        })
8542    }
8543}
8544
8545#[cfg(feature = "unstable_elicitation")]
8546impl TryToV2 for crate::v1::ElicitationSessionScope {
8547    type Output = super::ElicitationSessionScope;
8548
8549    fn try_to_v2(self) -> Result<Self::Output> {
8550        let Self {
8551            session_id,
8552            tool_call_id,
8553        } = self;
8554        Ok(super::ElicitationSessionScope {
8555            session_id: session_id.try_to_v2()?,
8556            tool_call_id: tool_call_id.try_to_v2()?,
8557        })
8558    }
8559}
8560
8561#[cfg(feature = "unstable_elicitation")]
8562impl TryToV1 for super::ElicitationRequestScope {
8563    type Output = crate::v1::ElicitationRequestScope;
8564
8565    fn try_to_v1(self) -> Result<Self::Output> {
8566        let Self { request_id } = self;
8567        Ok(crate::v1::ElicitationRequestScope {
8568            request_id: request_id.try_to_v1()?,
8569        })
8570    }
8571}
8572
8573#[cfg(feature = "unstable_elicitation")]
8574impl TryToV2 for crate::v1::ElicitationRequestScope {
8575    type Output = super::ElicitationRequestScope;
8576
8577    fn try_to_v2(self) -> Result<Self::Output> {
8578        let Self { request_id } = self;
8579        Ok(super::ElicitationRequestScope {
8580            request_id: request_id.try_to_v2()?,
8581        })
8582    }
8583}
8584
8585#[cfg(feature = "unstable_elicitation")]
8586impl TryToV1 for super::CreateElicitationRequest {
8587    type Output = crate::v1::CreateElicitationRequest;
8588
8589    fn try_to_v1(self) -> Result<Self::Output> {
8590        let Self {
8591            mode,
8592            message,
8593            meta,
8594        } = self;
8595        Ok(crate::v1::CreateElicitationRequest {
8596            mode: mode.try_to_v1()?,
8597            message: message.try_to_v1()?,
8598            meta: meta.try_to_v1()?,
8599        })
8600    }
8601}
8602
8603#[cfg(feature = "unstable_elicitation")]
8604impl TryToV2 for crate::v1::CreateElicitationRequest {
8605    type Output = super::CreateElicitationRequest;
8606
8607    fn try_to_v2(self) -> Result<Self::Output> {
8608        let Self {
8609            mode,
8610            message,
8611            meta,
8612        } = self;
8613        Ok(super::CreateElicitationRequest {
8614            mode: mode.try_to_v2()?,
8615            message: message.try_to_v2()?,
8616            meta: meta.try_to_v2()?,
8617        })
8618    }
8619}
8620
8621#[cfg(feature = "unstable_elicitation")]
8622impl TryToV1 for super::ElicitationMode {
8623    type Output = crate::v1::ElicitationMode;
8624
8625    fn try_to_v1(self) -> Result<Self::Output> {
8626        Ok(match self {
8627            Self::Form(value) => crate::v1::ElicitationMode::Form(value.try_to_v1()?),
8628            Self::Url(value) => crate::v1::ElicitationMode::Url(value.try_to_v1()?),
8629            Self::Other(value) => crate::v1::ElicitationMode::Other(value.try_to_v1()?),
8630        })
8631    }
8632}
8633
8634#[cfg(feature = "unstable_elicitation")]
8635impl TryToV2 for crate::v1::ElicitationMode {
8636    type Output = super::ElicitationMode;
8637
8638    fn try_to_v2(self) -> Result<Self::Output> {
8639        Ok(match self {
8640            Self::Form(value) => super::ElicitationMode::Form(value.try_to_v2()?),
8641            Self::Url(value) => super::ElicitationMode::Url(value.try_to_v2()?),
8642            Self::Other(value) => super::ElicitationMode::Other(value.try_to_v2()?),
8643        })
8644    }
8645}
8646
8647#[cfg(feature = "unstable_elicitation")]
8648impl TryToV1 for super::OtherElicitationMode {
8649    type Output = crate::v1::OtherElicitationMode;
8650
8651    fn try_to_v1(self) -> Result<Self::Output> {
8652        let Self {
8653            mode,
8654            scope,
8655            fields,
8656        } = self;
8657        Ok(crate::v1::OtherElicitationMode {
8658            mode: mode.try_to_v1()?,
8659            scope: scope.try_to_v1()?,
8660            fields: fields.try_to_v1()?,
8661        })
8662    }
8663}
8664
8665#[cfg(feature = "unstable_elicitation")]
8666impl TryToV2 for crate::v1::OtherElicitationMode {
8667    type Output = super::OtherElicitationMode;
8668
8669    fn try_to_v2(self) -> Result<Self::Output> {
8670        let Self {
8671            mode,
8672            scope,
8673            fields,
8674        } = self;
8675        Ok(super::OtherElicitationMode {
8676            mode: mode.try_to_v2()?,
8677            scope: scope.try_to_v2()?,
8678            fields: fields.try_to_v2()?,
8679        })
8680    }
8681}
8682
8683#[cfg(feature = "unstable_elicitation")]
8684impl TryToV1 for super::ElicitationFormMode {
8685    type Output = crate::v1::ElicitationFormMode;
8686
8687    fn try_to_v1(self) -> Result<Self::Output> {
8688        let Self {
8689            scope,
8690            requested_schema,
8691        } = self;
8692        Ok(crate::v1::ElicitationFormMode {
8693            scope: scope.try_to_v1()?,
8694            requested_schema: requested_schema.try_to_v1()?,
8695        })
8696    }
8697}
8698
8699#[cfg(feature = "unstable_elicitation")]
8700impl TryToV2 for crate::v1::ElicitationFormMode {
8701    type Output = super::ElicitationFormMode;
8702
8703    fn try_to_v2(self) -> Result<Self::Output> {
8704        let Self {
8705            scope,
8706            requested_schema,
8707        } = self;
8708        Ok(super::ElicitationFormMode {
8709            scope: scope.try_to_v2()?,
8710            requested_schema: requested_schema.try_to_v2()?,
8711        })
8712    }
8713}
8714
8715#[cfg(feature = "unstable_elicitation")]
8716impl TryToV1 for super::ElicitationUrlMode {
8717    type Output = crate::v1::ElicitationUrlMode;
8718
8719    fn try_to_v1(self) -> Result<Self::Output> {
8720        let Self {
8721            scope,
8722            elicitation_id,
8723            url,
8724        } = self;
8725        Ok(crate::v1::ElicitationUrlMode {
8726            scope: scope.try_to_v1()?,
8727            elicitation_id: elicitation_id.try_to_v1()?,
8728            url: url.try_to_v1()?,
8729        })
8730    }
8731}
8732
8733#[cfg(feature = "unstable_elicitation")]
8734impl TryToV2 for crate::v1::ElicitationUrlMode {
8735    type Output = super::ElicitationUrlMode;
8736
8737    fn try_to_v2(self) -> Result<Self::Output> {
8738        let Self {
8739            scope,
8740            elicitation_id,
8741            url,
8742        } = self;
8743        Ok(super::ElicitationUrlMode {
8744            scope: scope.try_to_v2()?,
8745            elicitation_id: elicitation_id.try_to_v2()?,
8746            url: url.try_to_v2()?,
8747        })
8748    }
8749}
8750
8751#[cfg(feature = "unstable_elicitation")]
8752impl TryToV1 for super::CreateElicitationResponse {
8753    type Output = crate::v1::CreateElicitationResponse;
8754
8755    fn try_to_v1(self) -> Result<Self::Output> {
8756        let Self { action, meta } = self;
8757        Ok(crate::v1::CreateElicitationResponse {
8758            action: action.try_to_v1()?,
8759            meta: meta.try_to_v1()?,
8760        })
8761    }
8762}
8763
8764#[cfg(feature = "unstable_elicitation")]
8765impl TryToV2 for crate::v1::CreateElicitationResponse {
8766    type Output = super::CreateElicitationResponse;
8767
8768    fn try_to_v2(self) -> Result<Self::Output> {
8769        let Self { action, meta } = self;
8770        Ok(super::CreateElicitationResponse {
8771            action: action.try_to_v2()?,
8772            meta: meta.try_to_v2()?,
8773        })
8774    }
8775}
8776
8777#[cfg(feature = "unstable_elicitation")]
8778impl TryToV1 for super::ElicitationAction {
8779    type Output = crate::v1::ElicitationAction;
8780
8781    fn try_to_v1(self) -> Result<Self::Output> {
8782        Ok(match self {
8783            Self::Accept(value) => crate::v1::ElicitationAction::Accept(value.try_to_v1()?),
8784            Self::Decline => crate::v1::ElicitationAction::Decline,
8785            Self::Cancel => crate::v1::ElicitationAction::Cancel,
8786            Self::Other(value) => crate::v1::ElicitationAction::Other(value.try_to_v1()?),
8787        })
8788    }
8789}
8790
8791#[cfg(feature = "unstable_elicitation")]
8792impl TryToV2 for crate::v1::ElicitationAction {
8793    type Output = super::ElicitationAction;
8794
8795    fn try_to_v2(self) -> Result<Self::Output> {
8796        Ok(match self {
8797            Self::Accept(value) => super::ElicitationAction::Accept(value.try_to_v2()?),
8798            Self::Decline => super::ElicitationAction::Decline,
8799            Self::Cancel => super::ElicitationAction::Cancel,
8800            Self::Other(value) => super::ElicitationAction::Other(value.try_to_v2()?),
8801        })
8802    }
8803}
8804
8805#[cfg(feature = "unstable_elicitation")]
8806impl TryToV1 for super::OtherElicitationAction {
8807    type Output = crate::v1::OtherElicitationAction;
8808
8809    fn try_to_v1(self) -> Result<Self::Output> {
8810        let Self { action, fields } = self;
8811        Ok(crate::v1::OtherElicitationAction {
8812            action: action.try_to_v1()?,
8813            fields: fields.try_to_v1()?,
8814        })
8815    }
8816}
8817
8818#[cfg(feature = "unstable_elicitation")]
8819impl TryToV2 for crate::v1::OtherElicitationAction {
8820    type Output = super::OtherElicitationAction;
8821
8822    fn try_to_v2(self) -> Result<Self::Output> {
8823        let Self { action, fields } = self;
8824        Ok(super::OtherElicitationAction {
8825            action: action.try_to_v2()?,
8826            fields: fields.try_to_v2()?,
8827        })
8828    }
8829}
8830
8831#[cfg(feature = "unstable_elicitation")]
8832impl TryToV1 for super::ElicitationAcceptAction {
8833    type Output = crate::v1::ElicitationAcceptAction;
8834
8835    fn try_to_v1(self) -> Result<Self::Output> {
8836        let Self { content } = self;
8837        Ok(crate::v1::ElicitationAcceptAction {
8838            content: content.try_to_v1()?,
8839        })
8840    }
8841}
8842
8843#[cfg(feature = "unstable_elicitation")]
8844impl TryToV2 for crate::v1::ElicitationAcceptAction {
8845    type Output = super::ElicitationAcceptAction;
8846
8847    fn try_to_v2(self) -> Result<Self::Output> {
8848        let Self { content } = self;
8849        Ok(super::ElicitationAcceptAction {
8850            content: content.try_to_v2()?,
8851        })
8852    }
8853}
8854
8855#[cfg(feature = "unstable_elicitation")]
8856impl TryToV1 for super::ElicitationContentValue {
8857    type Output = crate::v1::ElicitationContentValue;
8858
8859    fn try_to_v1(self) -> Result<Self::Output> {
8860        Ok(match self {
8861            Self::String(value) => crate::v1::ElicitationContentValue::String(value.try_to_v1()?),
8862            Self::Integer(value) => crate::v1::ElicitationContentValue::Integer(value.try_to_v1()?),
8863            Self::Number(value) => crate::v1::ElicitationContentValue::Number(value.try_to_v1()?),
8864            Self::Boolean(value) => crate::v1::ElicitationContentValue::Boolean(value.try_to_v1()?),
8865            Self::StringArray(value) => {
8866                crate::v1::ElicitationContentValue::StringArray(value.try_to_v1()?)
8867            }
8868        })
8869    }
8870}
8871
8872#[cfg(feature = "unstable_elicitation")]
8873impl TryToV2 for crate::v1::ElicitationContentValue {
8874    type Output = super::ElicitationContentValue;
8875
8876    fn try_to_v2(self) -> Result<Self::Output> {
8877        Ok(match self {
8878            Self::String(value) => super::ElicitationContentValue::String(value.try_to_v2()?),
8879            Self::Integer(value) => super::ElicitationContentValue::Integer(value.try_to_v2()?),
8880            Self::Number(value) => super::ElicitationContentValue::Number(value.try_to_v2()?),
8881            Self::Boolean(value) => super::ElicitationContentValue::Boolean(value.try_to_v2()?),
8882            Self::StringArray(value) => {
8883                super::ElicitationContentValue::StringArray(value.try_to_v2()?)
8884            }
8885        })
8886    }
8887}
8888
8889#[cfg(feature = "unstable_elicitation")]
8890impl TryToV1 for super::CompleteElicitationNotification {
8891    type Output = crate::v1::CompleteElicitationNotification;
8892
8893    fn try_to_v1(self) -> Result<Self::Output> {
8894        let Self {
8895            elicitation_id,
8896            meta,
8897        } = self;
8898        Ok(crate::v1::CompleteElicitationNotification {
8899            elicitation_id: elicitation_id.try_to_v1()?,
8900            meta: meta.try_to_v1()?,
8901        })
8902    }
8903}
8904
8905#[cfg(feature = "unstable_elicitation")]
8906impl TryToV2 for crate::v1::CompleteElicitationNotification {
8907    type Output = super::CompleteElicitationNotification;
8908
8909    fn try_to_v2(self) -> Result<Self::Output> {
8910        let Self {
8911            elicitation_id,
8912            meta,
8913        } = self;
8914        Ok(super::CompleteElicitationNotification {
8915            elicitation_id: elicitation_id.try_to_v2()?,
8916            meta: meta.try_to_v2()?,
8917        })
8918    }
8919}
8920
8921impl TryToV1 for super::ContentBlock {
8922    type Output = crate::v1::ContentBlock;
8923
8924    fn try_to_v1(self) -> Result<Self::Output> {
8925        Ok(match self {
8926            Self::Text(value) => crate::v1::ContentBlock::Text(value.try_to_v1()?),
8927            Self::Image(value) => crate::v1::ContentBlock::Image(value.try_to_v1()?),
8928            Self::Audio(value) => crate::v1::ContentBlock::Audio(value.try_to_v1()?),
8929            Self::ResourceLink(value) => crate::v1::ContentBlock::ResourceLink(value.try_to_v1()?),
8930            Self::Resource(value) => crate::v1::ContentBlock::Resource(value.try_to_v1()?),
8931            Self::Other(value) => {
8932                return Err(unknown_v2_enum_variant("ContentBlock", &value.type_));
8933            }
8934        })
8935    }
8936}
8937
8938impl TryToV2 for crate::v1::ContentBlock {
8939    type Output = super::ContentBlock;
8940
8941    fn try_to_v2(self) -> Result<Self::Output> {
8942        Ok(match self {
8943            Self::Text(value) => super::ContentBlock::Text(value.try_to_v2()?),
8944            Self::Image(value) => super::ContentBlock::Image(value.try_to_v2()?),
8945            Self::Audio(value) => super::ContentBlock::Audio(value.try_to_v2()?),
8946            Self::ResourceLink(value) => super::ContentBlock::ResourceLink(value.try_to_v2()?),
8947            Self::Resource(value) => super::ContentBlock::Resource(value.try_to_v2()?),
8948        })
8949    }
8950}
8951
8952impl TryToV1 for super::TextContent {
8953    type Output = crate::v1::TextContent;
8954
8955    fn try_to_v1(self) -> Result<Self::Output> {
8956        let Self {
8957            annotations,
8958            text,
8959            meta,
8960        } = self;
8961        Ok(crate::v1::TextContent {
8962            annotations: annotations.try_to_v1()?,
8963            text: text.try_to_v1()?,
8964            meta: meta.try_to_v1()?,
8965        })
8966    }
8967}
8968
8969impl TryToV2 for crate::v1::TextContent {
8970    type Output = super::TextContent;
8971
8972    fn try_to_v2(self) -> Result<Self::Output> {
8973        let Self {
8974            annotations,
8975            text,
8976            meta,
8977        } = self;
8978        Ok(super::TextContent {
8979            annotations: annotations.try_to_v2()?,
8980            text: text.try_to_v2()?,
8981            meta: meta.try_to_v2()?,
8982        })
8983    }
8984}
8985
8986impl TryToV1 for super::ImageContent {
8987    type Output = crate::v1::ImageContent;
8988
8989    fn try_to_v1(self) -> Result<Self::Output> {
8990        let Self {
8991            annotations,
8992            data,
8993            mime_type,
8994            uri,
8995            meta,
8996        } = self;
8997        Ok(crate::v1::ImageContent {
8998            annotations: annotations.try_to_v1()?,
8999            data: data.try_to_v1()?,
9000            mime_type: mime_type.try_to_v1()?,
9001            uri: uri.try_to_v1()?,
9002            meta: meta.try_to_v1()?,
9003        })
9004    }
9005}
9006
9007impl TryToV2 for crate::v1::ImageContent {
9008    type Output = super::ImageContent;
9009
9010    fn try_to_v2(self) -> Result<Self::Output> {
9011        let Self {
9012            annotations,
9013            data,
9014            mime_type,
9015            uri,
9016            meta,
9017        } = self;
9018        Ok(super::ImageContent {
9019            annotations: annotations.try_to_v2()?,
9020            data: data.try_to_v2()?,
9021            mime_type: super::MediaType::new(mime_type),
9022            uri: uri.try_to_v2()?,
9023            meta: meta.try_to_v2()?,
9024        })
9025    }
9026}
9027
9028impl TryToV1 for super::AudioContent {
9029    type Output = crate::v1::AudioContent;
9030
9031    fn try_to_v1(self) -> Result<Self::Output> {
9032        let Self {
9033            annotations,
9034            data,
9035            mime_type,
9036            meta,
9037        } = self;
9038        Ok(crate::v1::AudioContent {
9039            annotations: annotations.try_to_v1()?,
9040            data: data.try_to_v1()?,
9041            mime_type: mime_type.try_to_v1()?,
9042            meta: meta.try_to_v1()?,
9043        })
9044    }
9045}
9046
9047impl TryToV2 for crate::v1::AudioContent {
9048    type Output = super::AudioContent;
9049
9050    fn try_to_v2(self) -> Result<Self::Output> {
9051        let Self {
9052            annotations,
9053            data,
9054            mime_type,
9055            meta,
9056        } = self;
9057        Ok(super::AudioContent {
9058            annotations: annotations.try_to_v2()?,
9059            data: data.try_to_v2()?,
9060            mime_type: super::MediaType::new(mime_type),
9061            meta: meta.try_to_v2()?,
9062        })
9063    }
9064}
9065
9066impl TryToV1 for super::EmbeddedResource {
9067    type Output = crate::v1::EmbeddedResource;
9068
9069    fn try_to_v1(self) -> Result<Self::Output> {
9070        let Self {
9071            annotations,
9072            resource,
9073            meta,
9074        } = self;
9075        Ok(crate::v1::EmbeddedResource {
9076            annotations: annotations.try_to_v1()?,
9077            resource: resource.try_to_v1()?,
9078            meta: meta.try_to_v1()?,
9079        })
9080    }
9081}
9082
9083impl TryToV2 for crate::v1::EmbeddedResource {
9084    type Output = super::EmbeddedResource;
9085
9086    fn try_to_v2(self) -> Result<Self::Output> {
9087        let Self {
9088            annotations,
9089            resource,
9090            meta,
9091        } = self;
9092        Ok(super::EmbeddedResource {
9093            annotations: annotations.try_to_v2()?,
9094            resource: resource.try_to_v2()?,
9095            meta: meta.try_to_v2()?,
9096        })
9097    }
9098}
9099
9100impl TryToV1 for super::EmbeddedResourceResource {
9101    type Output = crate::v1::EmbeddedResourceResource;
9102
9103    fn try_to_v1(self) -> Result<Self::Output> {
9104        Ok(match self {
9105            Self::TextResourceContents(value) => {
9106                crate::v1::EmbeddedResourceResource::TextResourceContents(value.try_to_v1()?)
9107            }
9108            Self::BlobResourceContents(value) => {
9109                crate::v1::EmbeddedResourceResource::BlobResourceContents(value.try_to_v1()?)
9110            }
9111        })
9112    }
9113}
9114
9115impl TryToV2 for crate::v1::EmbeddedResourceResource {
9116    type Output = super::EmbeddedResourceResource;
9117
9118    fn try_to_v2(self) -> Result<Self::Output> {
9119        Ok(match self {
9120            Self::TextResourceContents(value) => {
9121                super::EmbeddedResourceResource::TextResourceContents(value.try_to_v2()?)
9122            }
9123            Self::BlobResourceContents(value) => {
9124                super::EmbeddedResourceResource::BlobResourceContents(value.try_to_v2()?)
9125            }
9126        })
9127    }
9128}
9129
9130impl TryToV1 for super::TextResourceContents {
9131    type Output = crate::v1::TextResourceContents;
9132
9133    fn try_to_v1(self) -> Result<Self::Output> {
9134        let Self {
9135            mime_type,
9136            text,
9137            uri,
9138            meta,
9139        } = self;
9140        Ok(crate::v1::TextResourceContents {
9141            mime_type: mime_type.try_to_v1()?,
9142            text: text.try_to_v1()?,
9143            uri: uri.try_to_v1()?,
9144            meta: meta.try_to_v1()?,
9145        })
9146    }
9147}
9148
9149impl TryToV2 for crate::v1::TextResourceContents {
9150    type Output = super::TextResourceContents;
9151
9152    fn try_to_v2(self) -> Result<Self::Output> {
9153        let Self {
9154            mime_type,
9155            text,
9156            uri,
9157            meta,
9158        } = self;
9159        Ok(super::TextResourceContents {
9160            mime_type: mime_type.map(super::MediaType::new),
9161            text: text.try_to_v2()?,
9162            uri: uri.try_to_v2()?,
9163            meta: meta.try_to_v2()?,
9164        })
9165    }
9166}
9167
9168impl TryToV1 for super::BlobResourceContents {
9169    type Output = crate::v1::BlobResourceContents;
9170
9171    fn try_to_v1(self) -> Result<Self::Output> {
9172        let Self {
9173            blob,
9174            mime_type,
9175            uri,
9176            meta,
9177        } = self;
9178        Ok(crate::v1::BlobResourceContents {
9179            blob: blob.try_to_v1()?,
9180            mime_type: mime_type.try_to_v1()?,
9181            uri: uri.try_to_v1()?,
9182            meta: meta.try_to_v1()?,
9183        })
9184    }
9185}
9186
9187impl TryToV2 for crate::v1::BlobResourceContents {
9188    type Output = super::BlobResourceContents;
9189
9190    fn try_to_v2(self) -> Result<Self::Output> {
9191        let Self {
9192            blob,
9193            mime_type,
9194            uri,
9195            meta,
9196        } = self;
9197        Ok(super::BlobResourceContents {
9198            blob: blob.try_to_v2()?,
9199            mime_type: mime_type.map(super::MediaType::new),
9200            uri: uri.try_to_v2()?,
9201            meta: meta.try_to_v2()?,
9202        })
9203    }
9204}
9205
9206impl TryToV1 for super::ResourceLink {
9207    type Output = crate::v1::ResourceLink;
9208
9209    fn try_to_v1(self) -> Result<Self::Output> {
9210        let Self {
9211            annotations,
9212            description,
9213            icons,
9214            mime_type,
9215            name,
9216            size,
9217            title,
9218            uri,
9219            meta,
9220        } = self;
9221
9222        if matches!(icons.as_ref(), Some(icons) if !icons.is_empty()) {
9223            return Err(ProtocolConversionError::new(
9224                "v2 ResourceLink.icons cannot be represented in v1",
9225            ));
9226        }
9227
9228        Ok(crate::v1::ResourceLink {
9229            annotations: annotations.try_to_v1()?,
9230            description: description.try_to_v1()?,
9231            mime_type: mime_type.try_to_v1()?,
9232            name: name.try_to_v1()?,
9233            size: size.try_to_v1()?,
9234            title: title.try_to_v1()?,
9235            uri: uri.try_to_v1()?,
9236            meta: meta.try_to_v1()?,
9237        })
9238    }
9239}
9240
9241impl TryToV2 for crate::v1::ResourceLink {
9242    type Output = super::ResourceLink;
9243
9244    fn try_to_v2(self) -> Result<Self::Output> {
9245        let Self {
9246            annotations,
9247            description,
9248            mime_type,
9249            name,
9250            size,
9251            title,
9252            uri,
9253            meta,
9254        } = self;
9255        Ok(super::ResourceLink {
9256            annotations: annotations.try_to_v2()?,
9257            description: description.try_to_v2()?,
9258            icons: None,
9259            mime_type: mime_type.map(super::MediaType::new),
9260            name: name.try_to_v2()?,
9261            size: size.try_to_v2()?,
9262            title: title.try_to_v2()?,
9263            uri: uri.try_to_v2()?,
9264            meta: meta.try_to_v2()?,
9265        })
9266    }
9267}
9268
9269impl TryToV1 for super::Annotations {
9270    type Output = crate::v1::Annotations;
9271
9272    fn try_to_v1(self) -> Result<Self::Output> {
9273        let Self {
9274            audience,
9275            last_modified,
9276            priority,
9277            meta,
9278        } = self;
9279        Ok(crate::v1::Annotations {
9280            audience: audience.try_to_v1()?,
9281            last_modified: last_modified.try_to_v1()?,
9282            priority: priority.try_to_v1()?,
9283            meta: meta.try_to_v1()?,
9284        })
9285    }
9286}
9287
9288impl TryToV2 for crate::v1::Annotations {
9289    type Output = super::Annotations;
9290
9291    fn try_to_v2(self) -> Result<Self::Output> {
9292        let Self {
9293            audience,
9294            last_modified,
9295            priority,
9296            meta,
9297        } = self;
9298        Ok(super::Annotations {
9299            audience: audience.try_to_v2()?,
9300            last_modified: last_modified.try_to_v2()?,
9301            priority: priority.try_to_v2()?,
9302            meta: meta.try_to_v2()?,
9303        })
9304    }
9305}
9306
9307impl TryToV1 for super::Role {
9308    type Output = crate::v1::Role;
9309
9310    fn try_to_v1(self) -> Result<Self::Output> {
9311        Ok(match self {
9312            Self::Assistant => crate::v1::Role::Assistant,
9313            Self::User => crate::v1::Role::User,
9314            Self::Other(value) => return Err(unknown_v2_enum_variant("Role", &value)),
9315        })
9316    }
9317}
9318
9319impl TryToV2 for crate::v1::Role {
9320    type Output = super::Role;
9321
9322    fn try_to_v2(self) -> Result<Self::Output> {
9323        Ok(match self {
9324            Self::Assistant => super::Role::Assistant,
9325            Self::User => super::Role::User,
9326        })
9327    }
9328}
9329
9330#[cfg(test)]
9331mod tests {
9332    use super::*;
9333    use crate::{v1, v2};
9334
9335    /// Round-trip a v1 value through v2 and back, asserting equality.
9336    ///
9337    /// This catches dropped fields, renamed fields, and missing enum
9338    /// variants in either direction of the conversion as soon as v1 and v2
9339    /// diverge.
9340    fn assert_v1_round_trip<T1, T2>(value: T1)
9341    where
9342        T1: TryToV2<Output = T2> + Clone + std::fmt::Debug + PartialEq,
9343        T2: TryFrom<T1>,
9344        ProtocolConversionError: From<<T2 as TryFrom<T1>>::Error>,
9345        T1: TryFrom<T2>,
9346        ProtocolConversionError: From<<T1 as TryFrom<T2>>::Error>,
9347    {
9348        let original = value.clone();
9349        let as_v2: T2 = try_v1_to_v2(value).expect("v1 -> v2 conversion failed");
9350        let back: T1 = try_v2_to_v1(as_v2).expect("v2 -> v1 conversion failed");
9351        assert_eq!(
9352            original, back,
9353            "value did not survive v1 -> v2 -> v1 round trip"
9354        );
9355    }
9356
9357    /// Round-trip a v2 value through v1 and back, asserting equality.
9358    fn assert_v2_round_trip<T2, T1>(value: T2)
9359    where
9360        T2: TryToV1<Output = T1> + Clone + std::fmt::Debug + PartialEq,
9361        T1: TryFrom<T2>,
9362        ProtocolConversionError: From<<T1 as TryFrom<T2>>::Error>,
9363        T2: TryFrom<T1>,
9364        ProtocolConversionError: From<<T2 as TryFrom<T1>>::Error>,
9365    {
9366        let original = value.clone();
9367        let as_v1: T1 = try_v2_to_v1(value).expect("v2 -> v1 conversion failed");
9368        let back: T2 = try_v1_to_v2(as_v1).expect("v1 -> v2 conversion failed");
9369        assert_eq!(
9370            original, back,
9371            "value did not survive v2 -> v1 -> v2 round trip"
9372        );
9373    }
9374
9375    /// While v1 and v2 are structurally identical, JSON produced by either
9376    /// module must be byte-equal after a conversion. This is a cheap insurance
9377    /// against accidental field renames or shape drift in conversions.
9378    ///
9379    /// Starts from a v1 value, converts forward to v2 and asserts JSON
9380    /// equality, then converts back to v1 and asserts JSON equality again.
9381    /// Catches shape drift in both directions of the conversion.
9382    fn assert_json_eq_after_v1_to_v2<T1, T2>(value: T1)
9383    where
9384        T1: TryToV2<Output = T2> + serde::Serialize + Clone,
9385        T2: TryFrom<T1> + serde::Serialize,
9386        ProtocolConversionError: From<<T2 as TryFrom<T1>>::Error>,
9387        T1: TryFrom<T2> + serde::Serialize,
9388        ProtocolConversionError: From<<T1 as TryFrom<T2>>::Error>,
9389    {
9390        let v1_json = serde_json::to_value(&value).expect("v1 serialize");
9391        let as_v2: T2 = try_v1_to_v2(value).expect("v1 -> v2 conversion");
9392        let v2_json = serde_json::to_value(&as_v2).expect("v2 serialize");
9393        assert_eq!(
9394            v1_json, v2_json,
9395            "JSON shape diverged after v1 -> v2 conversion"
9396        );
9397
9398        let back_to_v1: T1 = try_v2_to_v1(as_v2).expect("v2 -> v1 conversion");
9399        let v1_json_after =
9400            serde_json::to_value(&back_to_v1).expect("v1 serialize after round trip");
9401        assert_eq!(
9402            v2_json, v1_json_after,
9403            "JSON shape diverged after v2 -> v1 conversion"
9404        );
9405    }
9406
9407    /// Mirror of [`assert_json_eq_after_v1_to_v2`] that starts from a v2 value.
9408    /// Useful when the natural starting point is a v2 type (for example when
9409    /// the type only exists today in v2's draft API surface).
9410    fn assert_json_eq_after_v2_to_v1<T2, T1>(value: T2)
9411    where
9412        T2: TryToV1<Output = T1> + serde::Serialize + Clone,
9413        T1: TryFrom<T2> + serde::Serialize,
9414        ProtocolConversionError: From<<T1 as TryFrom<T2>>::Error>,
9415        T2: TryFrom<T1> + serde::Serialize,
9416        ProtocolConversionError: From<<T2 as TryFrom<T1>>::Error>,
9417    {
9418        let v2_json = serde_json::to_value(&value).expect("v2 serialize");
9419        let as_v1: T1 = try_v2_to_v1(value).expect("v2 -> v1 conversion");
9420        let v1_json = serde_json::to_value(&as_v1).expect("v1 serialize");
9421        assert_eq!(
9422            v2_json, v1_json,
9423            "JSON shape diverged after v2 -> v1 conversion"
9424        );
9425
9426        let back_to_v2: T2 = try_v1_to_v2(as_v1).expect("v1 -> v2 conversion");
9427        let v2_json_after =
9428            serde_json::to_value(&back_to_v2).expect("v2 serialize after round trip");
9429        assert_eq!(
9430            v1_json, v2_json_after,
9431            "JSON shape diverged after v1 -> v2 conversion"
9432        );
9433    }
9434
9435    fn assert_v2_to_v1_error<T>(value: T, expected: &str)
9436    where
9437        T: TryToV1,
9438        T::Output: TryFrom<T> + std::fmt::Debug,
9439        ProtocolConversionError: From<<T::Output as TryFrom<T>>::Error>,
9440    {
9441        let error = try_v2_to_v1::<T, T::Output>(value).unwrap_err();
9442        assert_eq!(error.message(), expected);
9443    }
9444
9445    fn assert_v2_session_update_to_v1_error(value: v2::SessionUpdate, expected: &str) {
9446        let error = try_v2_to_v1_many::<_, v1::SessionUpdate>(value).unwrap_err();
9447        assert_eq!(error.message(), expected);
9448    }
9449
9450    fn assert_v1_to_v2_error<T>(value: T, expected: &str)
9451    where
9452        T: TryToV2,
9453        T::Output: TryFrom<T> + std::fmt::Debug,
9454        ProtocolConversionError: From<<T::Output as TryFrom<T>>::Error>,
9455    {
9456        let error = try_v1_to_v2::<T, T::Output>(value).unwrap_err();
9457        assert_eq!(error.message(), expected);
9458    }
9459
9460    fn v1_baseline_agent_capabilities() -> v1::AgentCapabilities {
9461        v1::AgentCapabilities::new()
9462            .load_session(true)
9463            .session_capabilities(
9464                v1::SessionCapabilities::new()
9465                    .list(v1::SessionListCapabilities::new())
9466                    .resume(v1::SessionResumeCapabilities::new())
9467                    .close(v1::SessionCloseCapabilities::new()),
9468            )
9469    }
9470
9471    fn v2_baseline_agent_capabilities() -> v2::AgentCapabilities {
9472        v2::AgentCapabilities::new().session(v2::SessionCapabilities::new())
9473    }
9474
9475    fn v1_test_auth_method() -> v1::AuthMethod {
9476        v1::AuthMethod::Agent(v1::AuthMethodAgent::new("agent", "Agent"))
9477    }
9478
9479    fn v2_test_auth_method() -> v2::AuthMethod {
9480        v2::AuthMethod::Agent(v2::AuthMethodAgent::new("agent", "Agent"))
9481    }
9482
9483    #[test]
9484    fn infallible_leaf_conversions_support_from_and_try_helpers() {
9485        let v1_session: v1::SessionId = v2::SessionId::new("sess").into();
9486        assert_eq!(v1_session, v1::SessionId::new("sess"));
9487
9488        let v2_session: v2::SessionId =
9489            try_v1_to_v2(v1_session).expect("infallible v1 session id -> v2");
9490        assert_eq!(v2_session, v2::SessionId::new("sess"));
9491
9492        let v2_status: v2::ToolCallStatus = v1::ToolCallStatus::Completed.into();
9493        assert_eq!(v2_status, v2::ToolCallStatus::Completed);
9494
9495        let v1_code: v1::ErrorCode = v2::ErrorCode::Other(-32099).into();
9496        assert_eq!(v1_code, v1::ErrorCode::Other(-32099));
9497    }
9498
9499    #[test]
9500    fn round_trips_session_config_option_categories() {
9501        for category in [
9502            v1::SessionConfigOptionCategory::Mode,
9503            v1::SessionConfigOptionCategory::Model,
9504            v1::SessionConfigOptionCategory::ModelConfig,
9505            v1::SessionConfigOptionCategory::ThoughtLevel,
9506            v1::SessionConfigOptionCategory::Other("_custom_category".to_string()),
9507        ] {
9508            assert_v1_round_trip::<v1::SessionConfigOptionCategory, v2::SessionConfigOptionCategory>(
9509                category,
9510            );
9511        }
9512
9513        for category in [
9514            v2::SessionConfigOptionCategory::Mode,
9515            v2::SessionConfigOptionCategory::Model,
9516            v2::SessionConfigOptionCategory::ModelConfig,
9517            v2::SessionConfigOptionCategory::ThoughtLevel,
9518            v2::SessionConfigOptionCategory::Other("_custom_category".to_string()),
9519        ] {
9520            assert_v2_round_trip::<v2::SessionConfigOptionCategory, v1::SessionConfigOptionCategory>(
9521                category,
9522            );
9523        }
9524    }
9525
9526    #[test]
9527    fn converts_v2_initialize_request_to_v1_without_serde() {
9528        let request = v2::InitializeRequest::new(
9529            ProtocolVersion::V2,
9530            v2::Implementation::new("test-client", "1.0.0"),
9531        );
9532
9533        let converted: v1::InitializeRequest = try_v2_to_v1(request).unwrap();
9534
9535        assert_eq!(converted.protocol_version, ProtocolVersion::V2);
9536        assert_eq!(
9537            converted
9538                .client_info
9539                .as_ref()
9540                .map(|info| info.name.as_str()),
9541            Some("test-client")
9542        );
9543    }
9544
9545    #[test]
9546    fn v1_initialize_request_without_client_info_does_not_convert_to_v2() {
9547        let request = v1::InitializeRequest::new(ProtocolVersion::V1);
9548
9549        assert_v1_to_v2_error(
9550            request,
9551            "v1 InitializeRequest without `clientInfo` cannot be represented in v2",
9552        );
9553    }
9554
9555    #[test]
9556    fn v1_initialize_response_without_agent_info_does_not_convert_to_v2() {
9557        let response = v1::InitializeResponse::new(ProtocolVersion::V1);
9558
9559        assert_v1_to_v2_error(
9560            response,
9561            "v1 InitializeResponse without `agentInfo` cannot be represented in v2",
9562        );
9563    }
9564
9565    #[test]
9566    fn round_trips_initialize_request() {
9567        let client_capabilities = v1::ClientCapabilities::new().session(
9568            v1::ClientSessionCapabilities::new().config_options(
9569                v1::SessionConfigOptionsCapabilities::new()
9570                    .boolean(v1::BooleanConfigOptionCapabilities::new()),
9571            ),
9572        );
9573
9574        let request = v1::InitializeRequest::new(ProtocolVersion::V1)
9575            .client_capabilities(client_capabilities)
9576            .client_info(v1::Implementation::new("test-client", "1.0.0").title("Test Client"));
9577
9578        assert_v1_round_trip::<v1::InitializeRequest, v2::InitializeRequest>(request.clone());
9579        let converted: v2::InitializeRequest =
9580            try_v1_to_v2(request).expect("v1 -> v2 conversion failed");
9581        let converted_capabilities =
9582            serde_json::to_value(&converted.capabilities).expect("v2 serialize");
9583        assert_eq!(converted_capabilities.get("fs"), None);
9584        assert_eq!(converted_capabilities.get("terminal"), None);
9585        let converted_json = serde_json::to_value(&converted).expect("v2 serialize");
9586        assert_eq!(converted_json.get("clientInfo"), None);
9587        assert_eq!(converted_json.get("implementation"), None);
9588        assert!(converted_json.get("info").is_some());
9589    }
9590
9591    #[test]
9592    fn round_trips_initialize_response() {
9593        let response = v1::InitializeResponse::new(ProtocolVersion::V1)
9594            .agent_capabilities(
9595                v1_baseline_agent_capabilities()
9596                    .auth(v1::AgentAuthCapabilities::new().logout(v1::LogoutCapabilities::new())),
9597            )
9598            .auth_methods(vec![v1_test_auth_method()])
9599            .agent_info(v1::Implementation::new("test-agent", "2.0.0").title("Test Agent"));
9600        assert_v1_round_trip::<v1::InitializeResponse, v2::InitializeResponse>(response.clone());
9601        let converted: v2::InitializeResponse =
9602            try_v1_to_v2(response).expect("v1 -> v2 conversion failed");
9603        let converted_json = serde_json::to_value(&converted).expect("v2 serialize");
9604        assert_eq!(converted_json.get("agentCapabilities"), None);
9605        assert!(converted_json.get("capabilities").is_some());
9606        assert_eq!(converted_json.get("agentInfo"), None);
9607        assert_eq!(converted_json.get("implementation"), None);
9608        assert!(converted_json.get("info").is_some());
9609        assert_eq!(converted_json.pointer("/capabilities/loadSession"), None);
9610    }
9611
9612    #[test]
9613    fn required_v2_session_methods_convert_to_v1_capability_markers() {
9614        let v1_capabilities = v1::AgentCapabilities::new()
9615            .load_session(true)
9616            .session_capabilities(
9617                v1::SessionCapabilities::new()
9618                    .list(v1::SessionListCapabilities::new())
9619                    .resume(v1::SessionResumeCapabilities::new())
9620                    .close(v1::SessionCloseCapabilities::new()),
9621            );
9622
9623        let v2_capabilities: v2::AgentCapabilities =
9624            try_v1_to_v2(v1_capabilities).expect("v1 -> v2 conversion");
9625        let session = v2_capabilities
9626            .session
9627            .as_ref()
9628            .expect("v1 capabilities imply v2 session support");
9629        assert!(session.delete.is_none());
9630        let v2_json = serde_json::to_value(&v2_capabilities).expect("v2 serialize");
9631        assert_eq!(v2_json.get("loadSession"), None);
9632        assert_eq!(v2_json.pointer("/session/load"), None);
9633        assert_eq!(v2_json.pointer("/session/list"), None);
9634        assert_eq!(v2_json.pointer("/session/resume"), None);
9635        assert_eq!(v2_json.pointer("/session/close"), None);
9636
9637        let v1_after: v1::AgentCapabilities =
9638            try_v2_to_v1(v2_capabilities).expect("v2 -> v1 conversion");
9639        assert!(v1_after.load_session);
9640        assert!(v1_after.session_capabilities.list.is_some());
9641        assert!(v1_after.session_capabilities.resume.is_some());
9642        assert!(v1_after.session_capabilities.close.is_some());
9643
9644        assert_v1_to_v2_error(
9645            v1::AgentCapabilities::new().load_session(true),
9646            "v1 SessionCapabilities.list cannot be represented in v2",
9647        );
9648        assert_v1_to_v2_error(
9649            v1::AgentCapabilities::new().session_capabilities(
9650                v1::SessionCapabilities::new()
9651                    .list(v1::SessionListCapabilities::new())
9652                    .resume(v1::SessionResumeCapabilities::new())
9653                    .close(v1::SessionCloseCapabilities::new()),
9654            ),
9655            "v1 AgentCapabilities.loadSession cannot be represented in v2",
9656        );
9657    }
9658
9659    #[test]
9660    fn v2_agent_capabilities_without_session_do_not_convert_to_v1() {
9661        let error = v1::AgentCapabilities::try_from(v2::AgentCapabilities::new()).unwrap_err();
9662        assert_eq!(
9663            error.message(),
9664            "v2 AgentCapabilities without `session` cannot be represented in v1"
9665        );
9666    }
9667
9668    #[test]
9669    fn initialize_auth_methods_control_logout_conversion() {
9670        let auth_meta =
9671            serde_json::Map::from_iter([("extension".to_string(), serde_json::Value::Bool(true))]);
9672        let without_auth = v2::InitializeResponse::new(
9673            ProtocolVersion::V2,
9674            v2::Implementation::new("test-agent", "2.0.0"),
9675        )
9676        .capabilities(
9677            v2_baseline_agent_capabilities()
9678                .auth(v2::AgentAuthCapabilities::new().meta(auth_meta.clone())),
9679        );
9680        let v1_without_auth: v1::InitializeResponse =
9681            try_v2_to_v1(without_auth).expect("v2 without auth methods -> v1");
9682        assert!(v1_without_auth.auth_methods.is_empty());
9683        assert!(v1_without_auth.agent_capabilities.auth.logout.is_none());
9684        assert_eq!(
9685            v1_without_auth.agent_capabilities.auth.meta.as_ref(),
9686            Some(&auth_meta)
9687        );
9688
9689        let v2_without_auth: v2::InitializeResponse =
9690            try_v1_to_v2(v1_without_auth).expect("v1 without auth methods -> v2");
9691        assert!(v2_without_auth.auth_methods.is_empty());
9692        assert_eq!(
9693            v2_without_auth.capabilities.auth.and_then(|auth| auth.meta),
9694            Some(auth_meta)
9695        );
9696
9697        let with_auth = v2::InitializeResponse::new(
9698            ProtocolVersion::V2,
9699            v2::Implementation::new("test-agent", "2.0.0"),
9700        )
9701        .capabilities(v2_baseline_agent_capabilities())
9702        .auth_methods(vec![v2_test_auth_method()]);
9703        let v1_with_auth: v1::InitializeResponse =
9704            try_v2_to_v1(with_auth).expect("v2 with auth methods -> v1");
9705        assert_eq!(v1_with_auth.auth_methods.len(), 1);
9706        assert!(v1_with_auth.agent_capabilities.auth.logout.is_some());
9707
9708        let v1_with_auth = v1::InitializeResponse::new(ProtocolVersion::V1)
9709            .agent_capabilities(
9710                v1_baseline_agent_capabilities()
9711                    .auth(v1::AgentAuthCapabilities::new().logout(v1::LogoutCapabilities::new())),
9712            )
9713            .auth_methods(vec![v1_test_auth_method()])
9714            .agent_info(v1::Implementation::new("test-agent", "2.0.0"));
9715        let v2_with_auth: v2::InitializeResponse =
9716            try_v1_to_v2(v1_with_auth).expect("v1 with auth methods -> v2");
9717        assert_eq!(v2_with_auth.auth_methods.len(), 1);
9718    }
9719
9720    #[test]
9721    fn mismatched_v1_auth_methods_and_logout_marker_do_not_convert_to_v2() {
9722        let methods_without_logout = v1::InitializeResponse::new(ProtocolVersion::V1)
9723            .agent_capabilities(v1_baseline_agent_capabilities())
9724            .auth_methods(vec![v1_test_auth_method()])
9725            .agent_info(v1::Implementation::new("test-agent", "2.0.0"));
9726        assert_v1_to_v2_error(
9727            methods_without_logout,
9728            "v1 InitializeResponse with non-empty `authMethods` and no \
9729             `agentCapabilities.auth.logout` cannot be represented in v2",
9730        );
9731
9732        let logout_without_methods = v1::InitializeResponse::new(ProtocolVersion::V1)
9733            .agent_capabilities(
9734                v1_baseline_agent_capabilities()
9735                    .auth(v1::AgentAuthCapabilities::new().logout(v1::LogoutCapabilities::new())),
9736            )
9737            .agent_info(v1::Implementation::new("test-agent", "2.0.0"));
9738        assert_v1_to_v2_error(
9739            logout_without_methods,
9740            "v1 InitializeResponse with `agentCapabilities.auth.logout` and empty \
9741             `authMethods` cannot be represented in v2",
9742        );
9743
9744        let logout_meta =
9745            serde_json::Map::from_iter([("marker".to_string(), serde_json::Value::Bool(true))]);
9746        let logout_marker_with_meta = v1::InitializeResponse::new(ProtocolVersion::V1)
9747            .agent_capabilities(
9748                v1_baseline_agent_capabilities().auth(
9749                    v1::AgentAuthCapabilities::new()
9750                        .logout(v1::LogoutCapabilities::new().meta(logout_meta)),
9751                ),
9752            )
9753            .auth_methods(vec![v1_test_auth_method()])
9754            .agent_info(v1::Implementation::new("test-agent", "2.0.0"));
9755        assert_v1_to_v2_error(
9756            logout_marker_with_meta,
9757            "v1 InitializeResponse.agentCapabilities.auth.logout metadata cannot be represented \
9758             in v2",
9759        );
9760    }
9761
9762    #[test]
9763    fn agent_auth_capabilities_do_not_encode_logout_support() {
9764        let v2_auth = v2::AgentAuthCapabilities::new();
9765        let v2_json = serde_json::to_value(&v2_auth).expect("v2 serialize");
9766        assert_eq!(v2_json.get("logout"), None);
9767
9768        let v1_auth: v1::AgentAuthCapabilities =
9769            try_v2_to_v1(v2_auth).expect("v2 -> v1 conversion");
9770        assert!(v1_auth.logout.is_none());
9771
9772        let v2_auth: v2::AgentAuthCapabilities =
9773            try_v1_to_v2(v1::AgentAuthCapabilities::new()).expect("v1 -> v2 conversion");
9774        let v2_json = serde_json::to_value(&v2_auth).expect("v2 serialize");
9775        assert_eq!(v2_json.get("logout"), None);
9776
9777        assert_v1_to_v2_error(
9778            v1::AgentAuthCapabilities::new().logout(v1::LogoutCapabilities::new()),
9779            "v1 AgentAuthCapabilities.logout cannot be represented in v2",
9780        );
9781    }
9782
9783    #[test]
9784    fn v2_session_capabilities_convert_to_v1_agent_capability_parts() {
9785        let parts = v2::SessionCapabilities::new()
9786            .prompt(v2::PromptCapabilities::new().image(v2::PromptImageCapabilities::new()))
9787            .mcp(v2::McpCapabilities::new().http(v2::McpHttpCapabilities::new()))
9788            .try_into_v1_parts()
9789            .expect("v2 session capabilities -> v1 parts");
9790
9791        assert!(parts.session_capabilities.list.is_some());
9792        assert!(parts.session_capabilities.resume.is_some());
9793        assert!(parts.session_capabilities.close.is_some());
9794        assert!(parts.prompt_capabilities.image);
9795        assert!(parts.load_session);
9796        assert!(parts.mcp_capabilities.http);
9797    }
9798
9799    #[test]
9800    fn v1_prompt_capability_bools_convert_to_v2_objects() {
9801        let v1_capabilities = v1::PromptCapabilities::new()
9802            .image(true)
9803            .audio(true)
9804            .embedded_context(true);
9805
9806        let v2_capabilities: v2::PromptCapabilities =
9807            try_v1_to_v2(v1_capabilities).expect("v1 -> v2 conversion");
9808        let v2_json = serde_json::to_value(&v2_capabilities).expect("v2 serialize");
9809        assert_eq!(v2_json.pointer("/image"), Some(&serde_json::json!({})));
9810        assert_eq!(v2_json.pointer("/audio"), Some(&serde_json::json!({})));
9811        assert_eq!(
9812            v2_json.pointer("/embeddedContext"),
9813            Some(&serde_json::json!({}))
9814        );
9815
9816        let v1_after: v1::PromptCapabilities =
9817            try_v2_to_v1(v2_capabilities).expect("v2 -> v1 conversion");
9818        assert!(v1_after.image);
9819        assert!(v1_after.audio);
9820        assert!(v1_after.embedded_context);
9821    }
9822
9823    #[test]
9824    fn v1_mcp_capabilities_convert_to_v2_transport_objects() {
9825        let v1_capabilities = v1::McpCapabilities::new().http(true);
9826
9827        let v2_capabilities: v2::McpCapabilities =
9828            try_v1_to_v2(v1_capabilities).expect("v1 -> v2 conversion");
9829        let v2_json = serde_json::to_value(&v2_capabilities).expect("v2 serialize");
9830        assert_eq!(v2_json.pointer("/stdio"), Some(&serde_json::json!({})));
9831        assert_eq!(v2_json.pointer("/http"), Some(&serde_json::json!({})));
9832        assert_eq!(v2_json.pointer("/sse"), None);
9833
9834        let v1_after: v1::McpCapabilities =
9835            try_v2_to_v1(v2_capabilities).expect("v2 -> v1 conversion");
9836        assert!(v1_after.http);
9837        assert!(!v1_after.sse);
9838
9839        assert_v1_to_v2_error(
9840            v1::McpCapabilities::new().sse(true),
9841            "v1 McpCapabilities.sse cannot be represented in v2",
9842        );
9843    }
9844
9845    #[cfg(feature = "unstable_mcp_over_acp")]
9846    #[test]
9847    fn v1_mcp_acp_capability_bool_converts_to_v2_object() {
9848        let v1_capabilities = v1::McpCapabilities::new().acp(true);
9849
9850        let v2_capabilities: v2::McpCapabilities =
9851            try_v1_to_v2(v1_capabilities).expect("v1 -> v2 conversion");
9852        let v2_json = serde_json::to_value(&v2_capabilities).expect("v2 serialize");
9853        assert_eq!(v2_json.pointer("/acp"), Some(&serde_json::json!({})));
9854
9855        let v1_after: v1::McpCapabilities =
9856            try_v2_to_v1(v2_capabilities).expect("v2 -> v1 conversion");
9857        assert!(v1_after.acp);
9858    }
9859
9860    #[cfg(feature = "unstable_auth_methods")]
9861    #[test]
9862    fn v1_auth_terminal_capability_bool_converts_to_v2_object() {
9863        let v1_capabilities = v1::AuthCapabilities::new().terminal(true);
9864
9865        let v2_capabilities: v2::AuthCapabilities =
9866            try_v1_to_v2(v1_capabilities).expect("v1 -> v2 conversion");
9867        let v2_json = serde_json::to_value(&v2_capabilities).expect("v2 serialize");
9868        assert_eq!(v2_json.pointer("/terminal"), Some(&serde_json::json!({})));
9869
9870        let v1_after: v1::AuthCapabilities =
9871            try_v2_to_v1(v2_capabilities).expect("v2 -> v1 conversion");
9872        assert!(v1_after.terminal);
9873    }
9874
9875    #[cfg(feature = "unstable_auth_methods")]
9876    #[test]
9877    fn auth_method_terminal_env_converts_between_map_and_variable_array() {
9878        let mut env = HashMap::new();
9879        env.insert("TERM".to_string(), "xterm-256color".to_string());
9880        env.insert("API_KEY".to_string(), "secret".to_string());
9881
9882        let v1_method = v1::AuthMethodTerminal::new("tui-auth", "Terminal Auth").env(env);
9883        let v2_method: v2::AuthMethodTerminal =
9884            try_v1_to_v2(v1_method).expect("v1 -> v2 conversion");
9885        let v2_json = serde_json::to_value(&v2_method).expect("v2 serialize");
9886        assert_eq!(
9887            v2_json.pointer("/env"),
9888            Some(&serde_json::json!([
9889                {
9890                    "name": "API_KEY",
9891                    "value": "secret"
9892                },
9893                {
9894                    "name": "TERM",
9895                    "value": "xterm-256color"
9896                }
9897            ]))
9898        );
9899
9900        let v1_after: v1::AuthMethodTerminal =
9901            try_v2_to_v1(v2_method).expect("v2 -> v1 conversion");
9902        assert_eq!(
9903            v1_after.env.get("TERM").map(String::as_str),
9904            Some("xterm-256color")
9905        );
9906        assert_eq!(
9907            v1_after.env.get("API_KEY").map(String::as_str),
9908            Some("secret")
9909        );
9910    }
9911
9912    #[cfg(feature = "unstable_auth_methods")]
9913    #[test]
9914    fn auth_method_terminal_duplicate_env_names_do_not_convert_to_v1() {
9915        let v2_method = v2::AuthMethodTerminal::new("tui-auth", "Terminal Auth").env(vec![
9916            v2::EnvVariable::new("TERM", "xterm"),
9917            v2::EnvVariable::new("TERM", "xterm-256color"),
9918        ]);
9919
9920        assert_v2_to_v1_error(
9921            v2_method,
9922            "v2 AuthMethodTerminal env variable `TERM` is duplicated and cannot be represented in v1",
9923        );
9924    }
9925
9926    #[test]
9927    fn v1_client_fs_and_terminal_capabilities_do_not_convert_to_v2() {
9928        assert_v1_to_v2_error(
9929            v1::ClientCapabilities::new().fs(v1::FileSystemCapabilities::new()
9930                .read_text_file(true)
9931                .write_text_file(true)),
9932            "v1 ClientCapabilities.fs cannot be represented in v2",
9933        );
9934        assert_v1_to_v2_error(
9935            v1::ClientCapabilities::new().terminal(true),
9936            "v1 ClientCapabilities.terminal cannot be represented in v2",
9937        );
9938    }
9939
9940    #[test]
9941    fn v2_client_capabilities_default_to_v1_boolean_config_option_support() {
9942        let v2_capabilities = v2::ClientCapabilities::new();
9943
9944        let v1_capabilities: v1::ClientCapabilities =
9945            try_v2_to_v1(v2_capabilities).expect("v2 -> v1 conversion");
9946
9947        assert!(
9948            v1_capabilities
9949                .session
9950                .and_then(|session| session.config_options)
9951                .and_then(|config_options| config_options.boolean)
9952                .is_some()
9953        );
9954    }
9955
9956    #[test]
9957    fn v1_terminal_tool_call_content_does_not_convert_to_v2() {
9958        assert_v1_to_v2_error(
9959            v1::ToolCallContent::Terminal(v1::Terminal::new("term")),
9960            "v1 ToolCallContent variant `terminal` cannot be represented in v2",
9961        );
9962    }
9963
9964    #[test]
9965    fn v1_mcp_sse_transport_does_not_convert_to_v2() {
9966        assert_v1_to_v2_error(
9967            v1::McpServer::Sse(v1::McpServerSse::new("events", "https://example.com/sse")),
9968            "v1 McpServer variant `sse` cannot be represented in v2",
9969        );
9970    }
9971
9972    #[test]
9973    fn v2_unknown_mcp_transport_does_not_convert_to_v1() {
9974        assert_v2_to_v1_error(
9975            v2::McpServer::Other(v2::OtherMcpServer::new("websocket", BTreeMap::default())),
9976            "v2 McpServer variant `websocket` cannot be represented in v1",
9977        );
9978    }
9979
9980    #[test]
9981    fn round_trips_new_session_request_with_mcp_variants() {
9982        let request = v1::NewSessionRequest::new("/workspace").mcp_servers(vec![
9983            v1::McpServer::Stdio(v1::McpServerStdio::new("local", "/usr/bin/mcp")),
9984            v1::McpServer::Http(v1::McpServerHttp::new("remote", "https://example.com")),
9985        ]);
9986
9987        assert_v1_round_trip::<v1::NewSessionRequest, v2::NewSessionRequest>(request.clone());
9988
9989        let v2_request: v2::NewSessionRequest = try_v1_to_v2(request).expect("v1 -> v2 conversion");
9990        assert_eq!(
9991            serde_json::to_value(&v2_request).expect("v2 serialize"),
9992            serde_json::json!({
9993                "cwd": "/workspace",
9994                "mcpServers": [
9995                    {
9996                        "type": "stdio",
9997                        "name": "local",
9998                        "command": "/usr/bin/mcp"
9999                    },
10000                    {
10001                        "type": "http",
10002                        "name": "remote",
10003                        "url": "https://example.com"
10004                    }
10005                ]
10006            })
10007        );
10008    }
10009
10010    #[test]
10011    fn round_trips_prompt_request_with_content_variants() {
10012        let prompt = vec![
10013            v1::ContentBlock::Text(v1::TextContent::new("hello")),
10014            v1::ContentBlock::Image(v1::ImageContent::new("data", "image/png")),
10015            v1::ContentBlock::ResourceLink(v1::ResourceLink::new("file.txt", "file:///file.txt")),
10016        ];
10017        let request = v1::PromptRequest::new("sess_1", prompt);
10018        assert_v1_round_trip::<v1::PromptRequest, v2::PromptRequest>(request.clone());
10019        assert_json_eq_after_v1_to_v2::<v1::PromptRequest, v2::PromptRequest>(request);
10020    }
10021
10022    #[cfg(feature = "unstable_elicitation")]
10023    #[test]
10024    fn round_trips_elicitation_property_schema_unknown_type() {
10025        let v1_schema = v1::ElicitationSchema::new().property(
10026            "location",
10027            v1::ElicitationPropertySchema::Other(v1::OtherElicitationPropertySchema::new(
10028                "_location",
10029                std::collections::BTreeMap::from([(
10030                    "precision".to_string(),
10031                    serde_json::json!("city"),
10032                )]),
10033            )),
10034            false,
10035        );
10036
10037        assert_v1_round_trip::<v1::ElicitationSchema, v2::ElicitationSchema>(v1_schema.clone());
10038        assert_json_eq_after_v1_to_v2::<v1::ElicitationSchema, v2::ElicitationSchema>(v1_schema);
10039
10040        let v2_schema = v2::ElicitationSchema::new().property(
10041            "location",
10042            v2::ElicitationPropertySchema::Other(v2::OtherElicitationPropertySchema::new(
10043                "_location",
10044                std::collections::BTreeMap::from([(
10045                    "precision".to_string(),
10046                    serde_json::json!("city"),
10047                )]),
10048            )),
10049            false,
10050        );
10051
10052        assert_v2_round_trip::<v2::ElicitationSchema, v1::ElicitationSchema>(v2_schema);
10053    }
10054
10055    #[cfg(feature = "unstable_elicitation")]
10056    #[test]
10057    fn round_trips_multi_select_items_unknown_type() {
10058        let v1_items = v1::MultiSelectItems::Other(v1::OtherMultiSelectItems::new(
10059            "_token",
10060            std::collections::BTreeMap::from([
10061                ("format".to_string(), serde_json::json!("workspace")),
10062                (
10063                    "anyOf".to_string(),
10064                    serde_json::json!([{ "const": "repo", "title": "Repository" }]),
10065                ),
10066            ]),
10067        ));
10068
10069        assert_v1_round_trip::<v1::MultiSelectItems, v2::MultiSelectItems>(v1_items.clone());
10070        assert_json_eq_after_v1_to_v2::<v1::MultiSelectItems, v2::MultiSelectItems>(v1_items);
10071
10072        let v2_items = v2::MultiSelectItems::Other(v2::OtherMultiSelectItems::new(
10073            "_token",
10074            std::collections::BTreeMap::from([
10075                ("format".to_string(), serde_json::json!("workspace")),
10076                (
10077                    "anyOf".to_string(),
10078                    serde_json::json!([{ "const": "repo", "title": "Repository" }]),
10079                ),
10080            ]),
10081        ));
10082
10083        assert_v2_round_trip::<v2::MultiSelectItems, v1::MultiSelectItems>(v2_items);
10084    }
10085
10086    #[cfg(feature = "unstable_elicitation")]
10087    #[test]
10088    fn round_trips_elicitation_mode_unknown_type() {
10089        let v1_request = v1::CreateElicitationRequest::new(
10090            v1::OtherElicitationMode::new(
10091                "_browser",
10092                v1::ElicitationRequestScope::new(v1::RequestId::Number(42)),
10093                std::collections::BTreeMap::from([(
10094                    "target".to_string(),
10095                    serde_json::json!("login"),
10096                )]),
10097            ),
10098            "Open a browser window",
10099        );
10100
10101        assert_v1_round_trip::<v1::CreateElicitationRequest, v2::CreateElicitationRequest>(
10102            v1_request.clone(),
10103        );
10104        assert_json_eq_after_v1_to_v2::<v1::CreateElicitationRequest, v2::CreateElicitationRequest>(
10105            v1_request,
10106        );
10107
10108        let v2_request = v2::CreateElicitationRequest::new(
10109            v2::OtherElicitationMode::new(
10110                "_browser",
10111                v2::ElicitationRequestScope::new(v2::RequestId::Number(42)),
10112                std::collections::BTreeMap::from([(
10113                    "target".to_string(),
10114                    serde_json::json!("login"),
10115                )]),
10116            ),
10117            "Open a browser window",
10118        );
10119
10120        assert_v2_round_trip::<v2::CreateElicitationRequest, v1::CreateElicitationRequest>(
10121            v2_request,
10122        );
10123    }
10124
10125    #[cfg(feature = "unstable_elicitation")]
10126    #[test]
10127    fn round_trips_elicitation_action_unknown_type() {
10128        let v1_response = v1::CreateElicitationResponse::new(v1::OtherElicitationAction::new(
10129            "_defer",
10130            std::collections::BTreeMap::from([
10131                ("reason".to_string(), serde_json::json!("waiting")),
10132                ("retryAfterMs".to_string(), serde_json::json!(1000)),
10133            ]),
10134        ));
10135
10136        assert_v1_round_trip::<v1::CreateElicitationResponse, v2::CreateElicitationResponse>(
10137            v1_response.clone(),
10138        );
10139        assert_json_eq_after_v1_to_v2::<v1::CreateElicitationResponse, v2::CreateElicitationResponse>(
10140            v1_response,
10141        );
10142
10143        let v2_response = v2::CreateElicitationResponse::new(v2::OtherElicitationAction::new(
10144            "_defer",
10145            std::collections::BTreeMap::from([
10146                ("reason".to_string(), serde_json::json!("waiting")),
10147                ("retryAfterMs".to_string(), serde_json::json!(1000)),
10148            ]),
10149        ));
10150
10151        assert_v2_round_trip::<v2::CreateElicitationResponse, v1::CreateElicitationResponse>(
10152            v2_response,
10153        );
10154    }
10155
10156    #[test]
10157    fn prompt_responses_do_not_convert_across_v1_v2_lifecycle_boundary() {
10158        assert_v2_to_v1_error(
10159            v2::PromptResponse::new(),
10160            "v2 PromptResponse cannot be represented in v1 because v2 reports completion with state_update session updates",
10161        );
10162        assert_v1_to_v2_error(
10163            v1::PromptResponse::new(v1::StopReason::EndTurn),
10164            "v1 PromptResponse cannot be represented in v2 by itself because v2 reports completion with state_update session updates",
10165        );
10166    }
10167
10168    #[test]
10169    fn v1_tool_call_converts_to_v2_upsert_with_diff_and_locations_one_way() {
10170        let tool_call = v1::ToolCall::new("tc_1", "editing files")
10171            .kind(v1::ToolKind::Edit)
10172            .status(v1::ToolCallStatus::InProgress)
10173            .content(vec![v1::ToolCallContent::Diff(
10174                v1::Diff::new("/path", "new contents").old_text("old contents"),
10175            )])
10176            .locations(vec![v1::ToolCallLocation::new("/path").line(42)])
10177            .raw_input(serde_json::json!({"foo": "bar"}))
10178            .raw_output(serde_json::json!({"ok": true}));
10179
10180        let converted: v2::ToolCallUpdate = try_v1_to_v2(tool_call).expect("v1 -> v2 conversion");
10181        assert_eq!(
10182            serde_json::to_value(&converted).expect("v2 serialize"),
10183            serde_json::json!({
10184                "toolCallId": "tc_1",
10185                "title": "editing files",
10186                "kind": "edit",
10187                "status": "in_progress",
10188                "content": [
10189                    {
10190                        "type": "diff",
10191                        "changes": [
10192                            {
10193                                "operation": "modify",
10194                                "path": "/path",
10195                                "fileType": "text"
10196                            }
10197                        ],
10198                        "patch": {
10199                            "format": "git_patch",
10200                            "text": "diff --git /path /path\n--- /path\n+++ /path\n@@ -1 +1 @@\n-old contents\n\\ No newline at end of file\n+new contents\n\\ No newline at end of file\n"
10201                        }
10202                    }
10203                ],
10204                "locations": [
10205                    {
10206                        "path": "/path",
10207                        "line": 42
10208                    }
10209                ],
10210                "rawInput": {
10211                    "foo": "bar"
10212                },
10213                "rawOutput": {
10214                    "ok": true
10215                }
10216            })
10217        );
10218
10219        assert_v2_to_v1_error(
10220            converted,
10221            "v2 Diff cannot be represented in v1 because v1 requires oldText/newText while v2 carries Git --patch text and structured changes",
10222        );
10223    }
10224
10225    #[test]
10226    fn v1_tool_call_update_round_trips_through_v2_tool_call_update_upsert() {
10227        let update = v1::ToolCallUpdate::new(
10228            "tc",
10229            v1::ToolCallUpdateFields::new()
10230                .status(v1::ToolCallStatus::Completed)
10231                .content(Vec::new()),
10232        );
10233
10234        assert_v1_round_trip::<v1::ToolCallUpdate, v2::ToolCallUpdate>(update.clone());
10235        assert_json_eq_after_v1_to_v2::<v1::ToolCallUpdate, v2::ToolCallUpdate>(update);
10236    }
10237
10238    #[test]
10239    fn v2_entity_meta_null_does_not_convert_to_v1() {
10240        assert_v2_to_v1_error(
10241            v2::SessionInfoUpdate::new().meta(None::<v2::Meta>),
10242            "v2 SessionInfoUpdate with null _meta cannot be represented in v1",
10243        );
10244        assert_v2_to_v1_error(
10245            v2::ToolCallUpdate::new("tc").meta(None::<v2::Meta>),
10246            "v2 ToolCallUpdate with null _meta cannot be represented in v1",
10247        );
10248    }
10249
10250    #[test]
10251    fn round_trips_session_notification_for_unchanged_update_kinds() {
10252        fn content_chunk(text: &str, message_id: &str) -> v1::ContentChunk {
10253            let chunk = v1::ContentChunk::new(v1::ContentBlock::Text(v1::TextContent::new(text)));
10254            chunk.message_id(message_id)
10255        }
10256
10257        let cases: Vec<v1::SessionUpdate> = vec![
10258            v1::SessionUpdate::UserMessageChunk(content_chunk("u", "msg_user")),
10259            v1::SessionUpdate::AgentMessageChunk(content_chunk("a", "msg_agent")),
10260            v1::SessionUpdate::AgentThoughtChunk(content_chunk("t", "msg_thought")),
10261            v1::SessionUpdate::SessionInfoUpdate(v1::SessionInfoUpdate::new().title("hi")),
10262            v1::SessionUpdate::UsageUpdate(
10263                v1::UsageUpdate::new(53_000, 200_000).cost(v1::Cost::new(0.045, "USD")),
10264            ),
10265        ];
10266        for update in cases {
10267            let notification = v1::SessionNotification::new("sess", update);
10268            let original_json = serde_json::to_value(&notification).expect("v1 serialize");
10269            let as_v2: v2::UpdateSessionNotification =
10270                try_v1_to_v2(notification.clone()).expect("v1 -> v2 conversion");
10271            let v2_json = serde_json::to_value(&as_v2).expect("v2 serialize");
10272            assert_eq!(
10273                original_json, v2_json,
10274                "JSON shape diverged after v1 -> v2 conversion"
10275            );
10276
10277            let back = try_v2_to_v1_many(as_v2).expect("v2 -> v1 conversion");
10278            assert_eq!(back, vec![notification]);
10279            let back_json = serde_json::to_value(&back[0]).expect("v1 serialize after round trip");
10280            assert_eq!(
10281                original_json, back_json,
10282                "JSON shape diverged after v2 -> v1 conversion"
10283            );
10284        }
10285    }
10286
10287    #[test]
10288    fn v1_tool_call_session_updates_convert_to_unified_v2_tool_call_update() {
10289        let create = v1::SessionNotification::new(
10290            "sess",
10291            v1::SessionUpdate::ToolCall(v1::ToolCall::new("tc", "title")),
10292        );
10293        let create_v2: v2::UpdateSessionNotification =
10294            try_v1_to_v2(create).expect("v1 -> v2 conversion");
10295        assert!(matches!(
10296            create_v2.update,
10297            v2::SessionUpdate::ToolCallUpdate(_)
10298        ));
10299        assert_eq!(
10300            serde_json::to_value(&create_v2).expect("v2 serialize"),
10301            serde_json::json!({
10302                "sessionId": "sess",
10303                "update": {
10304                    "sessionUpdate": "tool_call_update",
10305                    "toolCallId": "tc",
10306                    "title": "title"
10307                }
10308            })
10309        );
10310
10311        let update = v1::SessionNotification::new(
10312            "sess",
10313            v1::SessionUpdate::ToolCallUpdate(v1::ToolCallUpdate::new(
10314                "tc",
10315                v1::ToolCallUpdateFields::new().status(v1::ToolCallStatus::Completed),
10316            )),
10317        );
10318        let update_v2: v2::UpdateSessionNotification =
10319            try_v1_to_v2(update).expect("v1 -> v2 conversion");
10320        assert!(matches!(
10321            update_v2.update,
10322            v2::SessionUpdate::ToolCallUpdate(_)
10323        ));
10324        assert_eq!(
10325            serde_json::to_value(&update_v2).expect("v2 serialize"),
10326            serde_json::json!({
10327                "sessionId": "sess",
10328                "update": {
10329                    "sessionUpdate": "tool_call_update",
10330                    "toolCallId": "tc",
10331                    "status": "completed"
10332                }
10333            })
10334        );
10335    }
10336
10337    #[test]
10338    fn v2_full_messages_convert_to_v1_message_chunks() {
10339        let mut meta = v2::Meta::new();
10340        meta.insert("source".to_string(), serde_json::json!("full"));
10341
10342        let chunks = try_v2_to_v1_many(v2::SessionUpdate::UserMessage(
10343            v2::UserMessage::new("msg_user")
10344                .content(vec![
10345                    v2::ContentBlock::Text(v2::TextContent::new("hello")),
10346                    v2::ContentBlock::Text(v2::TextContent::new("world")),
10347                ])
10348                .meta(meta.clone()),
10349        ))
10350        .expect("v2 -> v1 conversion");
10351        assert_eq!(
10352            chunks,
10353            vec![
10354                v1::SessionUpdate::UserMessageChunk(
10355                    v1::ContentChunk::new(v1::ContentBlock::Text(v1::TextContent::new("hello")))
10356                        .message_id("msg_user")
10357                        .meta(meta.clone())
10358                ),
10359                v1::SessionUpdate::UserMessageChunk(
10360                    v1::ContentChunk::new(v1::ContentBlock::Text(v1::TextContent::new("world")))
10361                        .message_id("msg_user")
10362                        .meta(meta)
10363                ),
10364            ]
10365        );
10366
10367        assert_eq!(
10368            try_v2_to_v1_many(v2::SessionUpdate::AgentMessage(
10369                v2::AgentMessage::new("msg_agent")
10370                    .content(vec![v2::ContentBlock::Text(v2::TextContent::new("hello"))])
10371            ))
10372            .expect("v2 -> v1 conversion"),
10373            vec![v1::SessionUpdate::AgentMessageChunk(
10374                v1::ContentChunk::new(v1::ContentBlock::Text(v1::TextContent::new("hello")))
10375                    .message_id("msg_agent")
10376            )]
10377        );
10378
10379        assert_eq!(
10380            try_v2_to_v1_many(v2::SessionUpdate::AgentThought(
10381                v2::AgentThought::new("msg_thought").content(vec![v2::ContentBlock::Text(
10382                    v2::TextContent::new("thinking")
10383                )])
10384            ))
10385            .expect("v2 -> v1 conversion"),
10386            vec![v1::SessionUpdate::AgentThoughtChunk(
10387                v1::ContentChunk::new(v1::ContentBlock::Text(v1::TextContent::new("thinking")))
10388                    .message_id("msg_thought")
10389            )]
10390        );
10391    }
10392
10393    #[test]
10394    fn v2_full_message_session_notification_fans_out_to_v1_chunk_notifications() {
10395        let notification = v2::UpdateSessionNotification::new(
10396            "sess",
10397            v2::SessionUpdate::AgentMessage(v2::AgentMessage::new("msg_agent").content(vec![
10398                v2::ContentBlock::Text(v2::TextContent::new("hello")),
10399                v2::ContentBlock::Text(v2::TextContent::new("world")),
10400            ])),
10401        );
10402
10403        let notifications =
10404            Vec::<v1::SessionNotification>::try_from(notification).expect("v2 -> v1 conversion");
10405        assert_eq!(
10406            notifications,
10407            vec![
10408                v1::SessionNotification::new(
10409                    "sess",
10410                    v1::SessionUpdate::AgentMessageChunk(
10411                        v1::ContentChunk::new(v1::ContentBlock::Text(v1::TextContent::new(
10412                            "hello"
10413                        )))
10414                        .message_id("msg_agent")
10415                    )
10416                ),
10417                v1::SessionNotification::new(
10418                    "sess",
10419                    v1::SessionUpdate::AgentMessageChunk(
10420                        v1::ContentChunk::new(v1::ContentBlock::Text(v1::TextContent::new(
10421                            "world"
10422                        )))
10423                        .message_id("msg_agent")
10424                    )
10425                ),
10426            ]
10427        );
10428    }
10429
10430    #[test]
10431    fn v2_message_patches_and_clears_do_not_convert_to_v1_chunks() {
10432        assert_v2_session_update_to_v1_error(
10433            v2::SessionUpdate::AgentMessage(v2::AgentMessage::new("msg_agent")),
10434            "v2 SessionUpdate variant `agent_message` without content cannot be represented in v1 chunks",
10435        );
10436
10437        assert_v2_session_update_to_v1_error(
10438            v2::SessionUpdate::AgentMessage(
10439                v2::AgentMessage::new("msg_agent").content(None::<Vec<v2::ContentBlock>>),
10440            ),
10441            "v2 SessionUpdate variant `agent_message` with null content cannot be represented in v1 chunks",
10442        );
10443
10444        assert_v2_session_update_to_v1_error(
10445            v2::SessionUpdate::AgentMessage(
10446                v2::AgentMessage::new("msg_agent").content(Vec::<v2::ContentBlock>::new()),
10447            ),
10448            "v2 SessionUpdate variant `agent_message` with empty content cannot be represented in v1 chunks",
10449        );
10450
10451        assert_v2_session_update_to_v1_error(
10452            v2::SessionUpdate::AgentMessage(
10453                v2::AgentMessage::new("msg_agent")
10454                    .content(vec![v2::ContentBlock::Text(v2::TextContent::new("hello"))])
10455                    .meta(None::<v2::Meta>),
10456            ),
10457            "v2 SessionUpdate variant `agent_message` with null _meta cannot be represented in v1 chunks",
10458        );
10459    }
10460
10461    #[test]
10462    fn v2_tool_call_content_chunk_does_not_convert_to_v1_replacement_update() {
10463        assert_v2_session_update_to_v1_error(
10464            v2::SessionUpdate::ToolCallContentChunk(v2::ToolCallContentChunk::new(
10465                "tc_1",
10466                v2::ContentBlock::Text(v2::TextContent::new("partial output")),
10467            )),
10468            "v2 SessionUpdate variant `tool_call_content_chunk` cannot be represented in v1 because v1 tool-call content updates replace content instead of appending",
10469        );
10470    }
10471
10472    #[test]
10473    fn v2_terminal_session_updates_do_not_convert_to_v1() {
10474        assert_v2_session_update_to_v1_error(
10475            v2::SessionUpdate::TerminalUpdate(v2::TerminalUpdate::new("term_1")),
10476            "v2 SessionUpdate variant `terminal_update` cannot be represented in v1",
10477        );
10478        assert_v2_session_update_to_v1_error(
10479            v2::SessionUpdate::TerminalOutputChunk(v2::TerminalOutputChunk::new(
10480                "term_1", "dGVzdAo=",
10481            )),
10482            "v2 SessionUpdate variant `terminal_output_chunk` cannot be represented in v1",
10483        );
10484    }
10485
10486    #[test]
10487    fn v1_content_chunk_without_message_id_does_not_convert_to_v2() {
10488        assert_v1_to_v2_error(
10489            v1::ContentChunk::new(v1::ContentBlock::Text(v1::TextContent::new("missing"))),
10490            "v1 ContentChunk without messageId cannot be represented in v2",
10491        );
10492    }
10493
10494    #[test]
10495    fn v1_plan_session_update_converts_to_v2_item_plan_update() {
10496        let update = v1::SessionUpdate::Plan(v1::Plan::new(vec![v1::PlanEntry::new(
10497            "step",
10498            v1::PlanEntryPriority::High,
10499            v1::PlanEntryStatus::InProgress,
10500        )]));
10501
10502        let as_v2: v2::SessionUpdate = try_v1_to_v2(update.clone()).unwrap();
10503        assert_eq!(
10504            serde_json::to_value(&as_v2).unwrap(),
10505            serde_json::json!({
10506                "sessionUpdate": "plan_update",
10507                "plan": {
10508                    "type": "items",
10509                    "planId": LEGACY_V1_PLAN_ID,
10510                    "entries": [
10511                        {
10512                            "content": "step",
10513                            "priority": "high",
10514                            "status": "in_progress"
10515                        }
10516                    ]
10517                }
10518            })
10519        );
10520
10521        let back = try_v2_to_v1_many(as_v2).unwrap();
10522        #[cfg(not(feature = "unstable_plan_operations"))]
10523        assert_eq!(back, vec![update]);
10524        #[cfg(feature = "unstable_plan_operations")]
10525        assert!(matches!(
10526            back.as_slice(),
10527            [v1::SessionUpdate::PlanUpdate(_)]
10528        ));
10529    }
10530
10531    #[test]
10532    fn unknown_v2_session_update_does_not_convert_to_v1() {
10533        let update = v2::SessionUpdate::Other(v2::OtherSessionUpdate::new(
10534            "_status_badge",
10535            std::collections::BTreeMap::new(),
10536        ));
10537
10538        assert_v2_session_update_to_v1_error(
10539            update,
10540            "v2 SessionUpdate variant `_status_badge` cannot be represented in v1",
10541        );
10542    }
10543
10544    #[test]
10545    fn v2_state_update_does_not_convert_to_v1() {
10546        assert_v2_session_update_to_v1_error(
10547            v2::SessionUpdate::StateUpdate(v2::StateUpdate::Idle(
10548                v2::IdleStateUpdate::new().stop_reason(v2::StopReason::EndTurn),
10549            )),
10550            "v2 SessionUpdate variant `state_update` cannot be represented in v1 because v1 reports completion in the session/prompt response",
10551        );
10552    }
10553
10554    #[test]
10555    fn v1_current_mode_update_does_not_convert_to_v2() {
10556        assert_v1_to_v2_error(
10557            v1::SessionUpdate::CurrentModeUpdate(v1::CurrentModeUpdate::new("ask")),
10558            "v1 SessionUpdate variant `current_mode_update` cannot be represented in v2",
10559        );
10560    }
10561
10562    #[test]
10563    fn v1_session_response_modes_do_not_convert_to_v2() {
10564        assert_v1_to_v2_error(
10565            v1::NewSessionResponse::new("sess").modes(v1::SessionModeState::new(
10566                "ask",
10567                vec![v1::SessionMode::new("ask", "Ask")],
10568            )),
10569            "v1 NewSessionResponse.modes cannot be represented in v2",
10570        );
10571    }
10572
10573    #[test]
10574    fn v1_session_response_missing_config_options_becomes_empty_v2_vec() {
10575        let new_response: v2::NewSessionResponse =
10576            try_v1_to_v2(v1::NewSessionResponse::new("sess")).unwrap();
10577        assert!(new_response.config_options.is_empty());
10578
10579        let load_response: v2::ResumeSessionResponse =
10580            try_v1_to_v2(v1::LoadSessionResponse::new()).unwrap();
10581        assert!(load_response.config_options.is_empty());
10582
10583        let resume_response: v2::ResumeSessionResponse =
10584            try_v1_to_v2(v1::ResumeSessionResponse::new()).unwrap();
10585        assert!(resume_response.config_options.is_empty());
10586
10587        #[cfg(feature = "unstable_session_fork")]
10588        {
10589            let fork_response: v2::ForkSessionResponse =
10590                try_v1_to_v2(v1::ForkSessionResponse::new("fork")).unwrap();
10591            assert!(fork_response.config_options.is_empty());
10592        }
10593    }
10594
10595    #[test]
10596    fn v1_load_session_request_converts_to_v2_resume_replay_from_start() {
10597        let v2_request: v2::ResumeSessionRequest =
10598            try_v1_to_v2(v1::LoadSessionRequest::new("sess", "/workspace/project")).unwrap();
10599        assert!(matches!(
10600            v2_request.replay_from,
10601            Some(v2::ReplayFrom::Start(_))
10602        ));
10603
10604        let v1_load: v1::LoadSessionRequest = try_v2_to_v1(v2_request).unwrap();
10605        assert_eq!(v1_load.session_id, v1::SessionId::new("sess"));
10606        assert_eq!(v1_load.cwd, PathBuf::from("/workspace/project"));
10607    }
10608
10609    #[test]
10610    fn v2_resume_without_replay_maps_to_v1_resume_request() {
10611        let v1_request: v1::ResumeSessionRequest =
10612            try_v2_to_v1(v2::ResumeSessionRequest::new("sess", "/workspace/project")).unwrap();
10613        assert_eq!(v1_request.session_id, v1::SessionId::new("sess"));
10614        assert_eq!(v1_request.cwd, PathBuf::from("/workspace/project"));
10615    }
10616
10617    #[test]
10618    fn v2_session_response_converts_to_v1_without_mode_state() {
10619        let response: v1::NewSessionResponse =
10620            try_v2_to_v1(v2::NewSessionResponse::new("sess")).unwrap();
10621
10622        assert!(response.modes.is_none());
10623        assert!(matches!(
10624            response.config_options,
10625            Some(config_options) if config_options.is_empty()
10626        ));
10627    }
10628
10629    #[test]
10630    fn v2_tool_call_update_unrepresentable_fields_do_not_convert_to_v1() {
10631        let update = v2::ToolCallUpdate::new("tc")
10632            .kind(v2::ToolKind::Unknown("_future_kind".to_string()))
10633            .status(v2::ToolCallStatus::Other("_paused".to_string()))
10634            .content(vec![
10635                v2::ToolCallContent::Other(v2::OtherToolCallContent::new(
10636                    "_chart",
10637                    BTreeMap::default(),
10638                )),
10639                v2::ToolCallContent::Diff(v2::Diff::patch(
10640                    "diff --git /tmp/file.txt /tmp/file.txt\n",
10641                    vec![v2::DiffChange::modify("/tmp/file.txt")],
10642                )),
10643            ]);
10644
10645        assert_v2_to_v1_error(
10646            update,
10647            "v2 ToolKind variant `_future_kind` cannot be represented in v1",
10648        );
10649    }
10650
10651    #[test]
10652    fn v2_collection_conversion_fails_on_unrepresentable_items() {
10653        let response = v2::InitializeResponse::new(
10654            ProtocolVersion::V2,
10655            v2::Implementation::new("test-agent", "2.0.0"),
10656        )
10657        .capabilities(v2::AgentCapabilities::new().session(v2::SessionCapabilities::new()))
10658        .auth_methods(vec![
10659            v2::AuthMethod::Other(v2::OtherAuthMethod::new(
10660                "_oauth",
10661                "oauth",
10662                "OAuth",
10663                BTreeMap::default(),
10664            )),
10665            v2::AuthMethod::Agent(v2::AuthMethodAgent::new("agent", "Agent")),
10666        ]);
10667        assert_v2_to_v1_error(
10668            response,
10669            "v2 AuthMethod variant `_oauth` cannot be represented in v1",
10670        );
10671
10672        let config_update = v2::ConfigOptionUpdate::new(vec![
10673            v2::SessionConfigOption::select(
10674                "mode",
10675                "Mode",
10676                "ask",
10677                vec![v2::SessionConfigSelectOption::new("ask", "Ask")],
10678            ),
10679            v2::SessionConfigOption::new(
10680                "future",
10681                "Future",
10682                v2::SessionConfigKind::Other(v2::OtherSessionConfigKind::new(
10683                    "_slider",
10684                    BTreeMap::default(),
10685                )),
10686            ),
10687        ]);
10688        assert_v2_to_v1_error(
10689            config_update,
10690            "v2 SessionConfigKind variant `_slider` cannot be represented in v1",
10691        );
10692    }
10693
10694    #[test]
10695    fn v2_optional_fields_fail_on_unrepresentable_nested_values() {
10696        let command = v2::AvailableCommand::new("review", "Review changes").input(
10697            v2::AvailableCommandInput::Other(v2::OtherAvailableCommandInput::new(
10698                "_choices",
10699                BTreeMap::default(),
10700            )),
10701        );
10702        assert_v2_to_v1_error(
10703            v2::AvailableCommandsUpdate::new(vec![command]),
10704            "v2 AvailableCommandInput variant `_choices` cannot be represented in v1",
10705        );
10706
10707        let content = v2::TextContent::new("hello").annotations(
10708            v2::Annotations::new()
10709                .audience(vec![v2::Role::Other("_critic".to_string()), v2::Role::User]),
10710        );
10711        assert_v2_to_v1_error(
10712            content,
10713            "v2 Role variant `_critic` cannot be represented in v1",
10714        );
10715    }
10716
10717    #[test]
10718    fn available_command_input_conversion_adds_v2_discriminator() {
10719        let input = v1::AvailableCommandInput::Unstructured(v1::UnstructuredCommandInput::new(
10720            "Describe changes",
10721        ));
10722
10723        let v2_input: v2::AvailableCommandInput = try_v1_to_v2(input.clone()).unwrap();
10724        assert_eq!(
10725            serde_json::to_value(&v2_input).unwrap(),
10726            serde_json::json!({
10727                "type": "text",
10728                "hint": "Describe changes"
10729            })
10730        );
10731
10732        let v1_input: v1::AvailableCommandInput = try_v2_to_v1(v2_input).unwrap();
10733        assert_eq!(v1_input, input);
10734        assert_eq!(
10735            serde_json::to_value(v1_input).unwrap(),
10736            serde_json::json!({
10737                "hint": "Describe changes"
10738            })
10739        );
10740    }
10741
10742    #[test]
10743    fn v2_plan_entries_fail_on_unrepresentable_items_inside_vectors() {
10744        let update = v2::PlanUpdate::new(v2::PlanUpdateContent::items(
10745            "main",
10746            vec![
10747                v2::PlanEntry::new(
10748                    "keep",
10749                    v2::PlanEntryPriority::High,
10750                    v2::PlanEntryStatus::Pending,
10751                ),
10752                v2::PlanEntry::new(
10753                    "drop",
10754                    v2::PlanEntryPriority::Other("_critical".to_string()),
10755                    v2::PlanEntryStatus::Pending,
10756                ),
10757            ],
10758        ));
10759
10760        assert_v2_to_v1_error(
10761            update,
10762            "v2 PlanEntryPriority variant `_critical` cannot be represented in v1",
10763        );
10764    }
10765
10766    #[test]
10767    fn v1_tool_call_update_conversion_fails_on_unrepresentable_vec_items() {
10768        let update = v1::ToolCallUpdate::new(
10769            "tc",
10770            v1::ToolCallUpdateFields::new().content(vec![
10771                v1::ToolCallContent::Terminal(v1::Terminal::new("term")),
10772                v1::ToolCallContent::Diff(v1::Diff::new("/tmp/file.txt", "new")),
10773            ]),
10774        );
10775
10776        assert_v1_to_v2_error(
10777            update,
10778            "v1 ToolCallContent variant `terminal` cannot be represented in v2",
10779        );
10780    }
10781
10782    #[test]
10783    fn v2_terminal_content_does_not_convert_to_v1_client_terminal_content() {
10784        assert_v2_to_v1_error(
10785            v2::ToolCallContent::Terminal(v2::Terminal::new("term_1")),
10786            "v2 ToolCallContent variant `terminal` cannot be represented in v1 because v1 terminal content refers to a client-created terminal",
10787        );
10788    }
10789
10790    #[test]
10791    fn v2_command_permission_subject_does_not_convert_to_v1() {
10792        assert_v2_to_v1_error(
10793            v2::RequestPermissionRequest::new("session-id", "Run cargo test?", Vec::new()).subject(
10794                v2::RequestPermissionSubject::from(v2::CommandPermissionSubject::new(
10795                    "cargo test",
10796                    "/workspace/project",
10797                )),
10798            ),
10799            "v2 RequestPermissionSubject variant `command` cannot be represented in v1",
10800        );
10801    }
10802
10803    #[test]
10804    fn v2_resource_link_icons_do_not_convert_to_v1() {
10805        assert_v2_to_v1_error(
10806            v2::ResourceLink::new("file.txt", "file:///file.txt")
10807                .icons(vec![v2::Icon::new("https://example.com/icon.png")]),
10808            "v2 ResourceLink.icons cannot be represented in v1",
10809        );
10810    }
10811
10812    #[test]
10813    fn unknown_v2_raw_fallbacks_do_not_convert_to_v1() {
10814        assert_v2_to_v1_error(
10815            v2::ContentBlock::Other(v2::OtherContentBlock::new(
10816                "_widget",
10817                std::collections::BTreeMap::new(),
10818            )),
10819            "v2 ContentBlock variant `_widget` cannot be represented in v1",
10820        );
10821        assert_v2_to_v1_error(
10822            v2::ToolCallContent::Other(v2::OtherToolCallContent::new(
10823                "_chart",
10824                std::collections::BTreeMap::new(),
10825            )),
10826            "v2 ToolCallContent variant `_chart` cannot be represented in v1",
10827        );
10828        assert_v2_to_v1_error(
10829            v2::AvailableCommandInput::Other(v2::OtherAvailableCommandInput::new(
10830                "_choices",
10831                std::collections::BTreeMap::new(),
10832            )),
10833            "v2 AvailableCommandInput variant `_choices` cannot be represented in v1",
10834        );
10835        assert_v2_to_v1_error(
10836            v2::RequestPermissionRequest::new("session-id", "Permission requested", Vec::new())
10837                .subject(v2::RequestPermissionSubject::Other(
10838                    v2::OtherRequestPermissionSubject::new(
10839                        "_review",
10840                        std::collections::BTreeMap::new(),
10841                    ),
10842                )),
10843            "v2 RequestPermissionSubject variant `_review` cannot be represented in v1",
10844        );
10845        assert_v2_to_v1_error(
10846            v2::RequestPermissionRequest::new("session-id", "Permission requested", Vec::new()),
10847            "v2 RequestPermissionRequest without `subject` cannot be represented in v1",
10848        );
10849        assert_v2_to_v1_error(
10850            v2::RequestPermissionOutcome::Other(v2::OtherRequestPermissionOutcome::new(
10851                "_defer",
10852                std::collections::BTreeMap::new(),
10853            )),
10854            "v2 RequestPermissionOutcome variant `_defer` cannot be represented in v1",
10855        );
10856        assert_v2_to_v1_error(
10857            v2::SessionConfigKind::Other(v2::OtherSessionConfigKind::new(
10858                "_slider",
10859                std::collections::BTreeMap::new(),
10860            )),
10861            "v2 SessionConfigKind variant `_slider` cannot be represented in v1",
10862        );
10863        assert_v2_to_v1_error(
10864            v2::AuthMethod::Other(v2::OtherAuthMethod::new(
10865                "_oauth",
10866                "oauth",
10867                "OAuth",
10868                std::collections::BTreeMap::new(),
10869            )),
10870            "v2 AuthMethod variant `_oauth` cannot be represented in v1",
10871        );
10872        assert_v2_to_v1_error(
10873            v2::PlanUpdate::new(v2::PlanUpdateContent::Other(
10874                v2::OtherPlanUpdateContent::new(
10875                    "_timeline",
10876                    "plan-1",
10877                    std::collections::BTreeMap::new(),
10878                ),
10879            )),
10880            "v2 PlanUpdateContent variant `_timeline` cannot be represented in v1",
10881        );
10882        #[cfg(feature = "unstable_nes")]
10883        assert_v2_to_v1_error(
10884            v2::NesSuggestion::Other(v2::OtherNesSuggestion::new(
10885                "_preview",
10886                "preview-1",
10887                std::collections::BTreeMap::new(),
10888            )),
10889            "v2 NesSuggestion variant `_preview` cannot be represented in v1",
10890        );
10891    }
10892
10893    #[test]
10894    fn round_trips_request_permission_outcomes() {
10895        let cancelled = v1::RequestPermissionResponse::new(v1::RequestPermissionOutcome::Cancelled);
10896        assert_v1_round_trip::<v1::RequestPermissionResponse, v2::RequestPermissionResponse>(
10897            cancelled,
10898        );
10899
10900        let selected = v1::RequestPermissionResponse::new(v1::RequestPermissionOutcome::Selected(
10901            v1::SelectedPermissionOutcome::new("opt_1"),
10902        ));
10903        assert_v1_round_trip::<v1::RequestPermissionResponse, v2::RequestPermissionResponse>(
10904            selected,
10905        );
10906    }
10907
10908    #[test]
10909    fn converts_v1_request_permission_request_with_required_v2_title() {
10910        let titled = v1::RequestPermissionRequest::new(
10911            "session-id",
10912            v1::ToolCallUpdate::new("call_1", v1::ToolCallUpdateFields::new().title("Read file")),
10913            Vec::new(),
10914        );
10915
10916        let converted: v2::RequestPermissionRequest = try_v1_to_v2(titled).unwrap();
10917        assert_eq!(converted.title, "Read file");
10918        let Some(v2::RequestPermissionSubject::ToolCall(subject)) = converted.subject else {
10919            panic!("expected tool-call permission subject");
10920        };
10921        assert_eq!(subject.tool_call.tool_call_id.to_string(), "call_1");
10922
10923        let fallback = v1::RequestPermissionRequest::new(
10924            "session-id",
10925            v1::ToolCallUpdate::new("call_2", v1::ToolCallUpdateFields::new()),
10926            Vec::new(),
10927        );
10928
10929        assert_v1_to_v2_error(
10930            fallback,
10931            "v1 RequestPermissionRequest without a tool-call title cannot be represented in v2",
10932        );
10933    }
10934
10935    #[test]
10936    fn round_trips_error_with_data_payload() {
10937        let err = v1::Error::invalid_params().data(serde_json::json!({
10938            "reason": "missing field",
10939            "field": "sessionId",
10940        }));
10941        assert_v1_round_trip::<v1::Error, v2::Error>(err);
10942    }
10943
10944    #[test]
10945    fn round_trips_v2_value_back_through_v1() {
10946        // Same coverage but starting from v2, to exercise v2 -> v1 conversion.
10947        let request = v2::PromptRequest::new(
10948            "sess_2",
10949            vec![v2::ContentBlock::Text(v2::TextContent::new("hi"))],
10950        );
10951        assert_v2_round_trip::<v2::PromptRequest, v1::PromptRequest>(request.clone());
10952        assert_json_eq_after_v2_to_v1::<v2::PromptRequest, v1::PromptRequest>(request);
10953    }
10954
10955    #[test]
10956    fn protocol_version_constants_remain_explicit() {
10957        assert_eq!(ProtocolVersion::V1.as_u16(), 1);
10958        assert_eq!(ProtocolVersion::V2.as_u16(), 2);
10959    }
10960
10961    /// `?` bubbles a [`ProtocolConversionError`] into a [`v1::Error`] without
10962    /// loss of message, mapped onto the internal-error code.
10963    #[test]
10964    fn protocol_conversion_error_maps_into_v1_error() {
10965        fn run() -> std::result::Result<(), v1::Error> {
10966            // Synthesize a conversion error so we don't have to wait for v2
10967            // to actually diverge before exercising the `?` path.
10968            Err(ProtocolConversionError::new("missing required field"))?;
10969            unreachable!();
10970        }
10971
10972        let err = run().unwrap_err();
10973        assert_eq!(err.code, v1::ErrorCode::InternalError);
10974        assert_eq!(
10975            err.data,
10976            Some(serde_json::Value::String(
10977                "missing required field".to_string()
10978            ))
10979        );
10980    }
10981
10982    /// Mirror of the v1 test for the v2 [`Error`] type.
10983    #[test]
10984    fn protocol_conversion_error_maps_into_v2_error() {
10985        fn run() -> std::result::Result<(), v2::Error> {
10986            Err(ProtocolConversionError::new("missing required field"))?;
10987            unreachable!();
10988        }
10989
10990        let err = run().unwrap_err();
10991        assert_eq!(err.code, v2::ErrorCode::InternalError);
10992        assert_eq!(
10993            err.data,
10994            Some(serde_json::Value::String(
10995                "missing required field".to_string()
10996            ))
10997        );
10998    }
10999}