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