Skip to main content

agent_client_protocol/role/
acp.rs

1use std::{fmt::Debug, future::Future, hash::Hash};
2
3#[cfg(feature = "unstable_protocol_v2")]
4use futures::{StreamExt as _, future};
5#[cfg(feature = "unstable_protocol_v2")]
6use serde::{Serialize, de::DeserializeOwned};
7
8#[cfg(feature = "unstable_protocol_v2")]
9use crate::RawJsonRpcId;
10use crate::jsonrpc::{Builder, handlers::NullHandler, run::NullRun};
11#[cfg(feature = "unstable_protocol_v2")]
12use crate::jsonrpc::{TransportFrame, raw_is_response_only_shape};
13use crate::role::{HasPeer, RemoteStyle};
14use crate::util::MatchDispatchFrom;
15#[cfg(feature = "unstable_protocol_v2")]
16use crate::v1::schema::InitializeRequest;
17use crate::v1::schema::PROXY_METHOD_NAMES;
18use crate::v1::schema::SessionId;
19#[cfg(feature = "unstable_protocol_v2")]
20use crate::{
21    Channel, RawJsonRpcError, RawJsonRpcMessage, RawJsonRpcParams,
22    RawJsonRpcResponse as RpcResponse,
23};
24#[cfg(feature = "unstable_protocol_v2")]
25use crate::{ConnectTo, DynConnectTo};
26use crate::{ConnectionTo, Dispatch, HandleDispatchFrom, Handled, Role, RoleId};
27#[cfg(feature = "unstable_protocol_v2")]
28use crate::{schema::ProtocolVersion, v2::schema as v2};
29
30#[derive(serde::Deserialize)]
31struct NewSessionResponseEnvelope {
32    #[serde(rename = "sessionId")]
33    session_id: SessionId,
34}
35
36/// The client role - typically an IDE or CLI that controls an agent.
37///
38/// Clients send prompts and receive responses from agents.
39#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
40pub struct Client;
41
42impl Role for Client {
43    type Counterpart = Agent;
44
45    fn default_handle_dispatch_from(
46        &self,
47        message: Dispatch,
48        _connection: ConnectionTo<Client>,
49    ) -> impl Future<Output = Result<Handled<Dispatch>, crate::Error>> + Send {
50        std::future::ready(Ok(Handled::No {
51            message,
52            retry: false,
53        }))
54    }
55
56    fn role_id(&self) -> RoleId {
57        RoleId::from_singleton(self)
58    }
59
60    fn counterpart(&self) -> Self::Counterpart {
61        Agent
62    }
63}
64
65impl Client {
66    /// Create a client builder that uses the ACP protocol v1 API.
67    ///
68    /// Callbacks receive a [`v1::ConnectionTo`](crate::v1::ConnectionTo) and
69    /// typed handlers receive v1 request handles. With the
70    /// `unstable_protocol_v2` feature, use `Client::v2` for a protocol v2
71    /// client, or `Client::protocol_connector` to support both.
72    pub fn v1(self) -> crate::v1::Builder<Client> {
73        Builder::new(self).v1_client()
74    }
75
76    /// Create a client builder that requires an ACP protocol v2 agent.
77    ///
78    /// Initialize the connection with
79    /// [`v2::ConnectionTo::send_initialize`](crate::v2::ConnectionTo::send_initialize).
80    /// If the agent selects v1, it resolves to
81    /// [`InitializeOutcome::LowerVersion`](crate::v2::InitializeOutcome::LowerVersion)
82    /// rather than an error, and the connection stays uninitialized: fall back
83    /// to a v1 client implementation if that is acceptable. A plain
84    /// `send_request` of a v2 `InitializeRequest` resolves with an error
85    /// instead. To let the SDK do the fallback, use
86    /// [`Client::protocol_connector`].
87    ///
88    /// Requires the `unstable_protocol_v2` crate feature.
89    #[cfg(feature = "unstable_protocol_v2")]
90    pub fn v2(self) -> crate::v2::Builder<Client> {
91        Builder::new(self).v2_client()
92    }
93
94    /// Create a connector that chooses between configured protocol implementations.
95    ///
96    /// Add implementation factories with [`ClientProtocolConnector::with_v1`]
97    /// and [`ClientProtocolConnector::with_v2`]. The resulting connector starts
98    /// the highest configured protocol implementation. If a v2 implementation
99    /// successfully negotiates v1 and a v1 implementation is configured, the
100    /// connector reuses the connection only when the v1 implementation's
101    /// complete `initialize` parameters match what the agent already saw;
102    /// otherwise it opens a fresh agent connection and restarts with v1.
103    ///
104    /// Requires the `unstable_protocol_v2` crate feature while protocol v2
105    /// stabilizes.
106    #[cfg(feature = "unstable_protocol_v2")]
107    #[must_use]
108    pub fn protocol_connector(self) -> ClientProtocolConnector {
109        ClientProtocolConnector::new()
110    }
111}
112
113/// Client connector that opens an agent connection with a configured protocol implementation.
114///
115/// Use [`Client::protocol_connector`] to start the builder, then add each
116/// supported protocol version independently. Implementations and the agent
117/// connection are provided as factories because fallback from v2 to v1 may
118/// require a fresh connection initialized by the v1 implementation.
119///
120/// The `with_v1` and `with_v2` slots take any `ConnectTo<Agent>` factory; nothing checks that an
121/// implementation speaks the slot's version. Put a `.v1()` implementation in
122/// `with_v1` and a `.v2()` implementation in `with_v2`.
123#[cfg(feature = "unstable_protocol_v2")]
124#[derive(Debug, Default)]
125pub struct ClientProtocolConnector {
126    v1: Option<DynConnectToFactory<Agent>>,
127    v2: Option<DynConnectToFactory<Agent>>,
128}
129
130#[cfg(feature = "unstable_protocol_v2")]
131impl ClientProtocolConnector {
132    /// Create an empty client protocol connector.
133    #[must_use]
134    pub fn new() -> Self {
135        Self::default()
136    }
137
138    /// Return this connector with an ACP v1 implementation factory configured.
139    #[must_use]
140    pub fn with_v1<C>(mut self, client: impl FnMut() -> C + Send + 'static) -> Self
141    where
142        C: ConnectTo<Agent>,
143    {
144        self.v1 = Some(DynConnectToFactory::new(client));
145        self
146    }
147
148    /// Return this connector with an ACP v2 implementation factory configured.
149    #[must_use]
150    pub fn with_v2<C>(mut self, client: impl FnMut() -> C + Send + 'static) -> Self
151    where
152        C: ConnectTo<Agent>,
153    {
154        self.v2 = Some(DynConnectToFactory::new(client));
155        self
156    }
157
158    /// Connect to an agent produced by `agent` using the highest configured
159    /// compatible protocol implementation.
160    ///
161    /// # Errors
162    ///
163    /// Returns Invalid request (`-32600`) if no implementation is configured.
164    /// Propagates failures while exchanging initialization messages or driving
165    /// the selected client and agent connections.
166    pub async fn connect_to<C>(
167        mut self,
168        mut agent: impl FnMut() -> C + Send + 'static,
169    ) -> Result<(), crate::Error>
170    where
171        C: ConnectTo<Client>,
172    {
173        match (self.v1.as_mut(), self.v2.as_mut()) {
174            (None, None) => Err(crate::Error::invalid_request()
175                .data("client protocol connector has no configured ACP protocol implementations")),
176            (Some(v1), None) => {
177                connect_client_protocol(ClientProtocol::V1, v1.create(), agent()).await
178            }
179            (v1, Some(v2)) => {
180                let client = v2.create();
181                let agent_connection = RunningProtocolPeer::new(agent());
182                let (client, initialize) =
183                    start_client_protocol(ClientProtocol::V2, client).await?;
184                // This normalization is only a probe for the connection-reuse
185                // optimization. A request that cannot be represented in v1
186                // can still be valid v2 traffic and must reach the agent.
187                let v2_initialize_as_v1 = normalize_v2_initialize_params_for_reuse(&initialize);
188                let (client, agent_connection, initialize_response) =
189                    send_initialize_and_receive(client, agent_connection, initialize).await?;
190
191                if initialize_response_negotiated_v1(&initialize_response)
192                    && let Some(v1) = v1
193                {
194                    let fallback_client = v1.create();
195                    let (fallback_client, fallback_initialize) =
196                        start_client_protocol(ClientProtocol::V1, fallback_client).await?;
197                    let (id, v1_initialize) = initialize_request_parts(&fallback_initialize)?;
198                    parse_initialize_params::<InitializeRequest>(v1_initialize)?;
199
200                    if v2_initialize_as_v1
201                        .as_ref()
202                        .is_ok_and(|v2_initialize| v2_initialize == v1_initialize)
203                    {
204                        let fallback_response = initialize_response.with_id(id.clone());
205                        // The v2 implementation will never receive its initialize response once
206                        // the matching v1 implementation takes over this connection. Drop its
207                        // future and channels before running the v1 session so any resources it
208                        // owns are released promptly.
209                        drop(client);
210                        fallback_client.send(fallback_response)?;
211                        return pipe_protocol_peers_until_done(fallback_client, agent_connection)
212                            .await;
213                    }
214
215                    // Neither probe can continue on the replacement connection. Release both
216                    // client implementations and the original agent connection before starting
217                    // the real v1 session so they cannot retain resources for its lifetime.
218                    drop((
219                        client,
220                        fallback_client,
221                        agent_connection,
222                        initialize_response,
223                    ));
224                    return connect_client_protocol(ClientProtocol::V1, v1.create(), agent()).await;
225                }
226
227                client.send(initialize_response.into_message())?;
228                pipe_protocol_peers_until_done(client, agent_connection).await
229            }
230        }
231    }
232}
233
234#[cfg(feature = "unstable_protocol_v2")]
235struct DynConnectToFactory<R: Role> {
236    inner: Box<dyn FnMut() -> DynConnectTo<R> + Send>,
237}
238
239#[cfg(feature = "unstable_protocol_v2")]
240impl<R: Role> DynConnectToFactory<R> {
241    fn new<C>(mut factory: impl FnMut() -> C + Send + 'static) -> Self
242    where
243        C: ConnectTo<R>,
244    {
245        Self {
246            inner: Box::new(move || DynConnectTo::new(factory())),
247        }
248    }
249
250    fn create(&mut self) -> DynConnectTo<R> {
251        (self.inner)()
252    }
253}
254
255#[cfg(feature = "unstable_protocol_v2")]
256impl<R: Role> Debug for DynConnectToFactory<R> {
257    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
258        f.debug_struct("DynConnectToFactory")
259            .finish_non_exhaustive()
260    }
261}
262
263impl HasPeer<Client> for Client {
264    fn remote_style(&self, _peer: Client) -> RemoteStyle {
265        RemoteStyle::Counterpart
266    }
267}
268
269/// The agent role - typically an LLM that responds to prompts.
270///
271/// Agents receive prompts from clients and respond with answers,
272/// potentially invoking tools along the way.
273#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
274pub struct Agent;
275
276impl Role for Agent {
277    type Counterpart = Client;
278
279    fn role_id(&self) -> RoleId {
280        RoleId::from_singleton(self)
281    }
282
283    fn counterpart(&self) -> Self::Counterpart {
284        Client
285    }
286
287    async fn default_handle_dispatch_from(
288        &self,
289        message: Dispatch,
290        connection: ConnectionTo<Agent>,
291    ) -> Result<Handled<Dispatch>, crate::Error> {
292        MatchDispatchFrom::new(message, &connection)
293            .if_dispatch_from(Agent, async |message: Dispatch| {
294                // Stable v1 session helpers install a dynamic handler after
295                // `session/new`. Retry session messages to close the race
296                // between the response and that registration. An unguarded
297                // connection (`Builder::new`) can use the v1 helpers through
298                // `into_protocol::<V1>()`, so it retries too.
299                //
300                // The incoming actor bounds this retry: it parks at most
301                // `MAX_PARKED_MESSAGES`, and parks a request only while a
302                // deactivated session handler awaits removal or replacement.
303                // Any other unhandled request is answered with `-32601`.
304                //
305                // Every other version (v2 and later) uses typed handlers
306                // installed before the connection starts. Retrying an
307                // unhandled message there would retain it forever because no
308                // per-session dynamic handler is expected.
309                let retry = message.has_session_id()
310                    && connection
311                        .protocol_version()
312                        .is_none_or(|version| version == crate::schema::ProtocolVersion::V1);
313                Ok(Handled::No { message, retry })
314            })
315            .await
316            .done()
317    }
318}
319
320impl Agent {
321    /// Create an agent builder that uses the ACP protocol v1 API.
322    ///
323    /// Callbacks receive a [`v1::ConnectionTo`](crate::v1::ConnectionTo) and
324    /// typed handlers receive v1 request handles. With the
325    /// `unstable_protocol_v2` feature, use `Agent::v2` for a protocol v2
326    /// agent, or `Agent::protocol_router` to serve both.
327    pub fn v1(self) -> crate::v1::Builder<Agent> {
328        Builder::new(self).v1_agent()
329    }
330
331    /// Create an agent builder that uses the ACP protocol v2 API.
332    ///
333    /// This builder selects protocol v2 for clients requesting v2 or a newer
334    /// version. A request for exactly v2 must be a valid v2 initialize
335    /// request. A request for a newer version is accepted with what parses
336    /// under v2: unparsable capabilities and `_meta` are dropped, and a missing
337    /// or malformed `info` is replaced by an implementation named `unknown`
338    /// with version `unknown`. Use [`Self::protocol_router`] with a v1
339    /// implementation for v1 clients.
340    ///
341    /// The client may repeat `initialize` after the previous one completed
342    /// and before it sends any other request. Each repeat is negotiated like
343    /// the first one and dispatched to the initialize handler, and the latest
344    /// successful one is authoritative. A repeat requesting a version below v2
345    /// gets `-32022` (Unsupported protocol version), as a first request would.
346    /// A repeat after any other request or while an initialize is in flight
347    /// is rejected with `-32600`. A repeat that fails keeps the previous
348    /// initialization in place. Requests with a `null` id are rejected with
349    /// `-32600`.
350    ///
351    /// An initialized agent without a handler for `tool_call/cancel` or
352    /// `terminal/cancel` answers them with `-32602` (Invalid params), not
353    /// `-32601` (Method not found): the spec answers a request for an unknown
354    /// or non-cancellable tool call or terminal with `-32602`, and an agent
355    /// that handles neither method cancels nothing. A typed handler or a
356    /// catch-all handler for these requests takes precedence.
357    ///
358    /// Requires the `unstable_protocol_v2` crate feature.
359    #[cfg(feature = "unstable_protocol_v2")]
360    pub fn v2(self) -> crate::v2::Builder<Agent> {
361        Builder::new(self).v2_agent()
362    }
363
364    /// Create a router that chooses between configured protocol implementations.
365    ///
366    /// Add implementations with [`AgentProtocolRouter::with_v1`] and
367    /// [`AgentProtocolRouter::with_v2`].
368    /// The resulting router reads the initial
369    /// `initialize` request and selects a version-specific implementation. A
370    /// request for v2 or newer selects the v2 implementation. With a v1
371    /// implementation configured, everything else, including a request below
372    /// v1 and a missing or malformed first request, is handed unchanged to the
373    /// v1 implementation, so a v1 client sees exactly the behavior of the v1
374    /// implementation alone (including v1's fallback-to-latest rule). A
375    /// v2-only router rejects a request below v2 with `-32022`. The router
376    /// does not convert traffic after initialization.
377    ///
378    /// The selected implementation owns the connection. A repeated
379    /// `initialize` is forwarded to it and is never re-routed, so it is
380    /// negotiated like a first request against the selected version alone. A
381    /// v2 implementation answers a repeat requesting v1 with `-32022` listing
382    /// only v2, since the connection cannot switch to the v1 API, and the v2
383    /// initialization stays in effect. A v1 implementation selects v1 for a
384    /// repeat requesting a newer version. A first `initialize` with a
385    /// `null` id that would select v2 is rejected with `-32600`, like any
386    /// other invalid first request.
387    ///
388    /// A rejected first message, including a version mismatch (`-32022`),
389    /// leaves the connection uninitialized and open: the client may send
390    /// `initialize` again, for example after correcting its parameters.
391    /// Notifications before initialization are ignored.
392    ///
393    /// Requires the `unstable_protocol_v2` crate feature while protocol v2
394    /// stabilizes.
395    #[cfg(feature = "unstable_protocol_v2")]
396    #[must_use]
397    pub fn protocol_router(self) -> AgentProtocolRouter {
398        AgentProtocolRouter::new()
399    }
400}
401
402/// Agent component that routes each connection to a configured protocol implementation.
403///
404/// Use [`Agent::protocol_router`] to start the builder, then add each supported
405/// protocol version independently. The selected implementation owns the
406/// connection after the initial `initialize` negotiation.
407///
408/// The `with_v1` and `with_v2` slots take any `ConnectTo<Client>`; nothing checks that an
409/// implementation speaks the slot's version. Put a `.v1()` implementation in
410/// `with_v1` and a `.v2()` implementation in `with_v2`.
411#[cfg(feature = "unstable_protocol_v2")]
412#[derive(Debug, Default)]
413pub struct AgentProtocolRouter {
414    v1: Option<DynConnectTo<Client>>,
415    v2: Option<DynConnectTo<Client>>,
416}
417
418#[cfg(feature = "unstable_protocol_v2")]
419impl AgentProtocolRouter {
420    /// Create an empty agent protocol router.
421    #[must_use]
422    pub fn new() -> Self {
423        Self::default()
424    }
425
426    /// Return this router with an ACP v1 implementation configured.
427    #[must_use]
428    pub fn with_v1(mut self, agent: impl ConnectTo<Client>) -> Self {
429        self.v1 = Some(DynConnectTo::new(agent));
430        self
431    }
432
433    /// Return this router with an ACP v2 implementation configured.
434    #[must_use]
435    pub fn with_v2(mut self, agent: impl ConnectTo<Client>) -> Self {
436        self.v2 = Some(DynConnectTo::new(agent));
437        self
438    }
439}
440
441#[cfg(feature = "unstable_protocol_v2")]
442impl ConnectTo<Client> for AgentProtocolRouter {
443    async fn connect_to(self, client: impl ConnectTo<Agent>) -> Result<(), crate::Error> {
444        let supported = SupportedProtocols {
445            v1: self.v1.is_some(),
446            v2: self.v2.is_some(),
447        };
448        let client = RunningProtocolPeer::new(client);
449        let Some((first_frame, client, selected)) =
450            select_protocol_peer(client, "initialize", supported).await?
451        else {
452            return Ok(());
453        };
454        let agent = selected
455            .take_agent(self)
456            .expect("the router only selects a configured implementation");
457
458        let agent = RunningProtocolPeer::new(agent);
459        agent.send_frame(first_frame)?;
460        pipe_protocol_peers_until_done(client, agent).await
461    }
462}
463
464/// Read frames from `peer` until an `initialize_method` request selects a
465/// configured protocol version, and return that request's frame, the peer and
466/// the selection. Returns `None` if the peer closes first.
467///
468/// A failed initialize leaves the connection uninitialized, and the peer may
469/// send `initialize_method` again. Each rejected frame is answered and the
470/// loop keeps reading, so [`AgentProtocolRouter`] and [`ProxyProtocolRouter`]
471/// treat rejections the same way.
472#[cfg(feature = "unstable_protocol_v2")]
473async fn select_protocol_peer(
474    mut peer: RunningProtocolPeer,
475    initialize_method: &str,
476    supported: SupportedProtocols,
477) -> Result<Option<(TransportFrame, RunningProtocolPeer, SelectedProtocol)>, crate::Error> {
478    loop {
479        let Some((mut frame, next_peer)) = peer.next_frame().await? else {
480            return Ok(None);
481        };
482        peer = next_peer;
483        let message = match initialize_message_mut(&mut frame) {
484            Ok(Some(message)) => message,
485            Ok(None) => continue,
486            // A malformed frame, such as invalid JSON or a batch, gets the
487            // frame's own error with `id: null`, exactly as a v1 connection
488            // answers it. It selects no version, so the peer can still
489            // initialize either one.
490            Err(error) => {
491                send_initialize_error(&peer.tx, &frame, error)?;
492                continue;
493            }
494        };
495        let selected = match select_initialize_protocol(message, initialize_method, supported) {
496            Ok(selected) => selected,
497            // A v1 implementation answers any other message that does not
498            // select v2 itself, exactly as it would without the router.
499            Err(_)
500                if supported.v1 && !requests_protocol_v2(message, initialize_method, supported) =>
501            {
502                SelectedProtocol::V1
503            }
504            Err(error) => {
505                send_initialize_error(&peer.tx, &frame, error)?;
506                continue;
507            }
508        };
509        if !selected.is_configured(supported) {
510            send_initialize_error(&peer.tx, &frame, selected.unsupported_error(supported))?;
511            continue;
512        }
513        return Ok(Some((frame, peer, selected)));
514    }
515}
516
517#[cfg(feature = "unstable_protocol_v2")]
518#[derive(Debug, Clone, Copy, PartialEq, Eq)]
519enum SelectedProtocol {
520    V1,
521    V2,
522}
523
524#[cfg(feature = "unstable_protocol_v2")]
525impl SelectedProtocol {
526    fn take_agent(self, agent: AgentProtocolRouter) -> Option<DynConnectTo<Client>> {
527        match self {
528            Self::V1 => agent.v1,
529            Self::V2 => agent.v2,
530        }
531    }
532
533    fn is_configured(self, supported: SupportedProtocols) -> bool {
534        match self {
535            Self::V1 => supported.v1,
536            Self::V2 => supported.v2,
537        }
538    }
539
540    fn version(self) -> ProtocolVersion {
541        match self {
542            Self::V1 => ProtocolVersion::V1,
543            Self::V2 => ProtocolVersion::V2,
544        }
545    }
546
547    fn name(self) -> &'static str {
548        match self {
549            Self::V1 => "1",
550            Self::V2 => "2",
551        }
552    }
553
554    fn unsupported_error(self, supported: SupportedProtocols) -> crate::Error {
555        crate::Error::invalid_request().data(format!(
556            "ACP protocol version {} is not configured; this endpoint supports {}",
557            self.name(),
558            supported.description()
559        ))
560    }
561}
562
563#[cfg(feature = "unstable_protocol_v2")]
564#[derive(Debug, Clone, Copy, PartialEq, Eq)]
565struct SupportedProtocols {
566    v1: bool,
567    v2: bool,
568}
569
570#[cfg(feature = "unstable_protocol_v2")]
571impl SupportedProtocols {
572    fn select(self, requested: ProtocolVersion) -> Option<SelectedProtocol> {
573        if self.v2 && requested >= ProtocolVersion::V2 {
574            return Some(SelectedProtocol::V2);
575        }
576        // Any request that does not select v2 keeps v1's fallback-to-latest
577        // rule, so a v1 implementation behaves as it does without the router.
578        if self.v1 {
579            return Some(SelectedProtocol::V1);
580        }
581
582        None
583    }
584
585    fn versions(self) -> Vec<ProtocolVersion> {
586        [
587            self.v1.then_some(ProtocolVersion::V1),
588            self.v2.then_some(ProtocolVersion::V2),
589        ]
590        .into_iter()
591        .flatten()
592        .collect()
593    }
594
595    fn description(self) -> String {
596        match (self.v1, self.v2) {
597            (true, true) => "ACP protocol versions 1 and 2".into(),
598            (true, false) => "ACP protocol version 1".into(),
599            (false, true) => "ACP protocol version 2".into(),
600            (false, false) => "no ACP protocol versions".into(),
601        }
602    }
603}
604
605/// Select the configured protocol for the first `initialize_method` request
606/// (`initialize` for an agent, `proxy/initialize` for a proxy) and rewrite its
607/// params for the selected version.
608///
609/// Agents and proxies negotiate the same way: the highest configured version
610/// at or below the requested one, v1's fallback-to-latest rule below v1, and a
611/// request for a newer version keeps what parses under the selected one.
612#[cfg(feature = "unstable_protocol_v2")]
613fn select_initialize_protocol(
614    message: &mut RawJsonRpcMessage,
615    initialize_method: &str,
616    supported: SupportedProtocols,
617) -> Result<SelectedProtocol, crate::Error> {
618    let RawJsonRpcMessage::Request(request) = message else {
619        return Err(crate::Error::invalid_request().data(format!(
620            "first ACP message must be a `{initialize_method}` request"
621        )));
622    };
623
624    if request.method.as_ref() != initialize_method {
625        return Err(crate::Error::invalid_request()
626            .data(format!("first ACP request must be `{initialize_method}`")));
627    }
628
629    let Some(RawJsonRpcParams::Object(params)) = &mut request.params else {
630        return Err(invalid_initialize_protocol_version());
631    };
632    let Some(protocol_version) = params.get("protocolVersion") else {
633        return Err(invalid_initialize_protocol_version());
634    };
635
636    let requested = serde_json::from_value::<ProtocolVersion>(protocol_version.clone())
637        .map_err(|_| invalid_initialize_protocol_version())?;
638    let selected = select_configured_protocol(requested, supported)?;
639    // V2 request ids must be strings or integers; v1 still accepts null.
640    if selected == SelectedProtocol::V2 && request.id == RawJsonRpcId::Null {
641        return Err(crate::jsonrpc::raw_id::null_v2_request_id());
642    }
643    rewrite_initialize_params(params, requested, selected)?;
644
645    Ok(selected)
646}
647
648/// The requested protocol version of an `initialize` (or, for a proxy,
649/// `proxy/initialize`) request, if it has a valid one.
650#[cfg(feature = "unstable_protocol_v2")]
651fn requested_initialize_version(
652    message: &RawJsonRpcMessage,
653    initialize_method: &str,
654) -> Option<ProtocolVersion> {
655    let RawJsonRpcMessage::Request(request) = message else {
656        return None;
657    };
658    if request.method.as_ref() != initialize_method {
659        return None;
660    }
661    let Some(RawJsonRpcParams::Object(params)) = &request.params else {
662        return None;
663    };
664    serde_json::from_value(params.get("protocolVersion")?.clone()).ok()
665}
666
667/// Whether `message` is an `initialize_method` request that selects a
668/// configured v2 implementation. Everything else is answered by a configured
669/// v1 implementation.
670#[cfg(feature = "unstable_protocol_v2")]
671fn requests_protocol_v2(
672    message: &RawJsonRpcMessage,
673    initialize_method: &str,
674    supported: SupportedProtocols,
675) -> bool {
676    supported.v2
677        && requested_initialize_version(message, initialize_method)
678            .is_some_and(|requested| requested >= ProtocolVersion::V2)
679}
680
681#[cfg(feature = "unstable_protocol_v2")]
682fn initialize_request_parts(
683    message: &RawJsonRpcMessage,
684) -> crate::Result<(&RawJsonRpcId, &serde_json::Map<String, serde_json::Value>)> {
685    let RawJsonRpcMessage::Request(request) = message else {
686        return Err(
687            crate::Error::invalid_request().data("first ACP message must be an initialize request")
688        );
689    };
690
691    if request.method.as_ref() != "initialize" {
692        return Err(crate::Error::invalid_request().data("first ACP request must be initialize"));
693    }
694
695    let Some(RawJsonRpcParams::Object(params)) = &request.params else {
696        return Err(invalid_initialize_protocol_version());
697    };
698    if !params.contains_key("protocolVersion") {
699        return Err(invalid_initialize_protocol_version());
700    }
701    Ok((&request.id, params))
702}
703
704#[cfg(feature = "unstable_protocol_v2")]
705fn normalize_v2_initialize_params_for_reuse(
706    message: &RawJsonRpcMessage,
707) -> Result<serde_json::Map<String, serde_json::Value>, crate::Error> {
708    let (_, params) = initialize_request_parts(message)?;
709    let requested = params
710        .get("protocolVersion")
711        .cloned()
712        .ok_or_else(invalid_initialize_protocol_version)
713        .and_then(|version| {
714            serde_json::from_value::<ProtocolVersion>(version)
715                .map_err(|_| invalid_initialize_protocol_version())
716        })?;
717    if requested == ProtocolVersion::V1 {
718        parse_initialize_params::<InitializeRequest>(params)?;
719        return Ok(params.clone());
720    }
721    normalize_v2_initialize_params_for_v1(params, true)
722}
723
724#[cfg(feature = "unstable_protocol_v2")]
725fn rewrite_initialize_params(
726    params: &mut serde_json::Map<String, serde_json::Value>,
727    requested: ProtocolVersion,
728    selected: SelectedProtocol,
729) -> Result<(), crate::Error> {
730    // Validate exact-version initialization without replacing its raw
731    // parameters. Reserializing through the SDK's pinned schema would discard
732    // fields added by newer compatible peers.
733    if requested == selected.version() {
734        match selected {
735            SelectedProtocol::V1 => {
736                parse_initialize_params::<InitializeRequest>(params)?;
737            }
738            SelectedProtocol::V2 => {
739                parse_initialize_params::<v2::InitializeRequest>(params)?;
740            }
741        }
742        return Ok(());
743    }
744
745    match selected {
746        SelectedProtocol::V1 => {
747            if requested > ProtocolVersion::V1 {
748                *params = normalize_v2_initialize_params_for_v1(params, false)?;
749            } else {
750                let mut initialize = parse_initialize_params::<InitializeRequest>(params)?;
751                initialize.protocol_version = ProtocolVersion::V1;
752                *params = serialize_initialize_params(initialize)?;
753            }
754            Ok(())
755        }
756        SelectedProtocol::V2 => {
757            // The request was written for a newer version. Keep what parses
758            // under v2 instead of rejecting it, as a standalone v2 agent does.
759            *params = crate::jsonrpc::normalize_newer_v2_initialize_request(params)?;
760            Ok(())
761        }
762    }
763}
764
765#[cfg(feature = "unstable_protocol_v2")]
766fn normalize_v2_initialize_params_for_v1(
767    params: &serde_json::Map<String, serde_json::Value>,
768    require_lossless: bool,
769) -> Result<serde_json::Map<String, serde_json::Value>, crate::Error> {
770    if !require_lossless {
771        return crate::jsonrpc::normalize_v1_initialize_request(&serde_json::Value::Object(
772            params.clone(),
773        ));
774    }
775    // The connection-reuse probe additionally requires lossless v2
776    // canonicalization. Normal v1 routing above uses the same bootstrap as a
777    // standalone v1 agent, even when the v2 schema is not compiled in.
778    let initialize = parse_initialize_params::<v2::InitializeRequest>(params)?;
779    let mut target = serialize_initialize_params(initialize)?;
780    if require_lossless && target != *params {
781        return Err(invalid_initialize_params(
782            "v2 initialize parameters are not losslessly representable in v1",
783        ));
784    }
785
786    target.insert(
787        "protocolVersion".into(),
788        serde_json::to_value(ProtocolVersion::V1).map_err(crate::Error::into_internal_error)?,
789    );
790    let info = target
791        .remove("info")
792        .ok_or_else(|| invalid_initialize_params("v2 InitializeRequest.info is required"))?;
793    target.insert("clientInfo".into(), info);
794    let capabilities = target
795        .remove("capabilities")
796        .and_then(|capabilities| capabilities.as_object().cloned())
797        .ok_or_else(|| {
798            crate::util::internal_error("v2 initialize capabilities did not serialize as an object")
799        })?;
800    let mut capabilities = capabilities;
801    if let Some(auth) = capabilities
802        .get_mut("auth")
803        .and_then(serde_json::Value::as_object_mut)
804    {
805        let terminal = auth.remove("terminal");
806        if require_lossless
807            && terminal
808                .as_ref()
809                .and_then(serde_json::Value::as_object)
810                .is_some_and(|terminal| terminal.contains_key("_meta"))
811        {
812            return Err(invalid_initialize_params(
813                "v2 terminal authentication metadata is not representable in v1",
814            ));
815        }
816        auth.insert("terminal".into(), terminal.is_some().into());
817    }
818    capabilities.insert(
819        "session".into(),
820        serde_json::json!({ "configOptions": { "boolean": {} } }),
821    );
822    target.insert("clientCapabilities".into(), capabilities.into());
823
824    let initialize = parse_initialize_params::<InitializeRequest>(&target)?;
825    let normalized = serialize_initialize_params(initialize)?;
826    if require_lossless && !json_object_contains(&normalized, &target) {
827        return Err(invalid_initialize_params(
828            "v2 initialize parameters are not losslessly representable in v1",
829        ));
830    }
831    Ok(normalized)
832}
833
834#[cfg(all(test, feature = "unstable_protocol_v2"))]
835mod initialize_normalization_tests {
836    use super::*;
837
838    fn v2_initialize_params() -> serde_json::Map<String, serde_json::Value> {
839        let value = serde_json::to_value(v2::InitializeRequest::new(
840            ProtocolVersion::V2,
841            v2::Implementation::new("test-client", "1.0.0"),
842        ))
843        .expect("serialize v2 initialize request");
844        value
845            .as_object()
846            .expect("initialize params serialize as an object")
847            .clone()
848    }
849
850    #[test]
851    fn v2_tolerant_fields_are_canonicalized_before_v1_normalization() {
852        let mut params = v2_initialize_params();
853        params.insert(
854            "capabilities".into(),
855            serde_json::Value::String("malformed".into()),
856        );
857        params.insert(
858            "_meta".into(),
859            serde_json::Value::String("malformed".into()),
860        );
861
862        let normalized = normalize_v2_initialize_params_for_v1(&params, false)
863            .expect("tolerant v2 fields should normalize through their defaults");
864        let normalized = serde_json::Value::Object(normalized);
865
866        assert!(normalized.get("_meta").is_none());
867        assert_eq!(
868            normalized.pointer("/clientCapabilities/session/configOptions/boolean"),
869            Some(&serde_json::json!({}))
870        );
871    }
872
873    #[test]
874    fn noncanonical_v2_fields_disable_reuse_but_not_v1_routing() {
875        let mut params = v2_initialize_params();
876        params
877            .get_mut("info")
878            .and_then(serde_json::Value::as_object_mut)
879            .expect("v2 initialize info is an object")
880            .insert("buildCommit".into(), serde_json::json!("abc123"));
881
882        normalize_v2_initialize_params_for_v1(&params, false)
883            .expect("v1 routing may ignore parameters unavailable in v1");
884        normalize_v2_initialize_params_for_v1(&params, true)
885            .expect_err("connection reuse requires lossless normalization");
886    }
887
888    #[test]
889    fn v1_reuse_probe_preserves_raw_initialize_params() {
890        let mut params = v2_initialize_params();
891        params.insert(
892            "protocolVersion".into(),
893            serde_json::json!(ProtocolVersion::V1),
894        );
895        let message = RawJsonRpcMessage::request(
896            "initialize".into(),
897            serde_json::Value::Object(params.clone()),
898            RawJsonRpcId::Number(1),
899        )
900        .expect("build initialize request");
901
902        let normalized = normalize_v2_initialize_params_for_reuse(&message)
903            .expect("v1-shaped initialize request should be valid");
904
905        assert_eq!(normalized, params);
906    }
907
908    #[test]
909    fn null_v2_terminal_marker_meta_is_omitted_before_v1_normalization() {
910        let mut params = v2_initialize_params();
911        params.insert(
912            "capabilities".into(),
913            serde_json::json!({
914                "auth": {
915                    "terminal": { "_meta": null }
916                }
917            }),
918        );
919
920        let normalized = normalize_v2_initialize_params_for_v1(&params, false)
921            .expect("null marker metadata is equivalent to omission");
922        let normalized = serde_json::Value::Object(normalized);
923
924        assert_eq!(
925            normalized.pointer("/clientCapabilities/auth/terminal"),
926            Some(&serde_json::Value::Bool(true))
927        );
928    }
929
930    #[test]
931    fn terminal_marker_metadata_disables_reuse_but_not_v1_routing() {
932        let mut params = v2_initialize_params();
933        params.insert(
934            "capabilities".into(),
935            serde_json::json!({
936                "auth": {
937                    "terminal": {
938                        "_meta": { "source": "test" }
939                    }
940                }
941            }),
942        );
943
944        normalize_v2_initialize_params_for_v1(&params, false)
945            .expect("v1 routing may discard terminal marker metadata");
946        normalize_v2_initialize_params_for_v1(&params, true)
947            .expect_err("connection reuse must preserve terminal marker metadata");
948    }
949}
950
951#[cfg(feature = "unstable_protocol_v2")]
952fn parse_initialize_params<T: DeserializeOwned>(
953    params: &serde_json::Map<String, serde_json::Value>,
954) -> Result<T, crate::Error> {
955    serde_json::from_value(serde_json::Value::Object(params.clone()))
956        .map_err(invalid_initialize_params)
957}
958
959#[cfg(feature = "unstable_protocol_v2")]
960fn serialize_initialize_params(
961    initialize: impl Serialize,
962) -> Result<serde_json::Map<String, serde_json::Value>, crate::Error> {
963    let value = serde_json::to_value(initialize).map_err(crate::Error::into_internal_error)?;
964    let serde_json::Value::Object(object) = value else {
965        return Err(crate::util::internal_error(
966            "initialize params did not serialize to an object",
967        ));
968    };
969    Ok(object)
970}
971
972#[cfg(feature = "unstable_protocol_v2")]
973fn json_object_contains(
974    actual: &serde_json::Map<String, serde_json::Value>,
975    expected: &serde_json::Map<String, serde_json::Value>,
976) -> bool {
977    fn contains(actual: &serde_json::Value, expected: &serde_json::Value) -> bool {
978        match (actual, expected) {
979            (serde_json::Value::Object(actual), serde_json::Value::Object(expected)) => expected
980                .iter()
981                .all(|(key, value)| actual.get(key).is_some_and(|item| contains(item, value))),
982            _ => actual == expected,
983        }
984    }
985
986    expected
987        .iter()
988        .all(|(key, value)| actual.get(key).is_some_and(|item| contains(item, value)))
989}
990
991#[cfg(feature = "unstable_protocol_v2")]
992fn select_configured_protocol(
993    requested: ProtocolVersion,
994    supported: SupportedProtocols,
995) -> Result<SelectedProtocol, crate::Error> {
996    supported.select(requested).ok_or_else(|| {
997        crate::v2::schema::Error::unsupported_protocol_version(requested, &supported.versions())
998            .into()
999    })
1000}
1001
1002#[cfg(feature = "unstable_protocol_v2")]
1003fn invalid_initialize_protocol_version() -> crate::Error {
1004    crate::Error::invalid_params()
1005        .data("initialize.protocolVersion must be a valid ACP protocol version")
1006}
1007
1008#[cfg(feature = "unstable_protocol_v2")]
1009fn invalid_initialize_params(error: impl ToString) -> crate::Error {
1010    crate::Error::invalid_params().data(format!("invalid initialize params: {}", error.to_string()))
1011}
1012
1013#[cfg(feature = "unstable_protocol_v2")]
1014fn send_initialize_error(
1015    tx: &futures::channel::mpsc::UnboundedSender<TransportFrame>,
1016    frame: &TransportFrame,
1017    error: crate::Error,
1018) -> Result<(), crate::Error> {
1019    fn response_for_message(
1020        entry: &RawJsonRpcMessage,
1021        initialize_error: &crate::Error,
1022    ) -> Option<RawJsonRpcMessage> {
1023        match entry {
1024            RawJsonRpcMessage::Request(request) => Some(RawJsonRpcMessage::response(
1025                request.id.clone(),
1026                Err(initialize_error.clone()),
1027            )),
1028            RawJsonRpcMessage::Notification(_) | RawJsonRpcMessage::Response(_) => None,
1029        }
1030    }
1031
1032    let response = match frame {
1033        TransportFrame::Single(entry) => {
1034            let Some(response) = response_for_message(entry, &error) else {
1035                return Ok(());
1036            };
1037            TransportFrame::Single(response)
1038        }
1039        TransportFrame::Malformed { raw, error } if !raw_is_response_only_shape(raw) => {
1040            TransportFrame::Single(RawJsonRpcMessage::response(
1041                RawJsonRpcId::Null,
1042                Err(error.clone()),
1043            ))
1044        }
1045        TransportFrame::Malformed { .. } => return Ok(()),
1046    };
1047
1048    tx.unbounded_send(response)
1049        .map_err(crate::util::internal_error)
1050}
1051
1052#[cfg(feature = "unstable_protocol_v2")]
1053struct RunningProtocolPeer {
1054    rx: futures::channel::mpsc::UnboundedReceiver<TransportFrame>,
1055    tx: futures::channel::mpsc::UnboundedSender<TransportFrame>,
1056    driver: ProtocolPeerDriver,
1057}
1058
1059#[cfg(feature = "unstable_protocol_v2")]
1060enum ProtocolPeerDriver {
1061    Passive,
1062    Active(crate::ConnectionDriver),
1063    Completed {
1064        finish: Option<crate::component::FinishControl>,
1065    },
1066}
1067
1068#[cfg(feature = "unstable_protocol_v2")]
1069impl ProtocolPeerDriver {
1070    fn into_driver(self) -> Option<crate::ConnectionDriver> {
1071        match self {
1072            Self::Passive => None,
1073            Self::Active(driver) => Some(driver),
1074            // Conversion happens only when handing the peer to its final
1075            // bridge, never while reading its remaining queued frames. This
1076            // records actual owned completion, not a passive ready sentinel.
1077            Self::Completed { finish } => Some(match finish {
1078                Some(mut finish) => {
1079                    crate::ConnectionDriver::with_finish(future::ready(Ok(())), move || {
1080                        finish.request();
1081                    })
1082                }
1083                None => crate::ConnectionDriver::new(future::ready(Ok(()))),
1084            }),
1085        }
1086    }
1087}
1088
1089#[cfg(feature = "unstable_protocol_v2")]
1090impl RunningProtocolPeer {
1091    fn new<R: Role>(component: impl ConnectTo<R>) -> Self {
1092        let (Channel { rx, tx }, future) = component.into_channel_and_future();
1093        let driver = match future {
1094            None => ProtocolPeerDriver::Passive,
1095            Some(future) => ProtocolPeerDriver::Active(future),
1096        };
1097        Self { rx, tx, driver }
1098    }
1099
1100    async fn next_frame(self) -> Result<Option<(TransportFrame, Self)>, crate::Error> {
1101        let Self { mut rx, tx, driver } = self;
1102        let ProtocolPeerDriver::Active(mut future) = driver else {
1103            return Ok(rx
1104                .next()
1105                .await
1106                .map(|frame| (frame, Self { rx, tx, driver })));
1107        };
1108
1109        // Poll the owned driver first: a ready error must not be hidden by
1110        // an equally ready frame or clean channel EOF.
1111        match future::select(&mut future, Box::pin(rx.next())).await {
1112            future::Either::Right((Some(frame), _)) => Ok(Some((
1113                frame,
1114                Self {
1115                    rx,
1116                    tx,
1117                    driver: ProtocolPeerDriver::Active(future),
1118                },
1119            ))),
1120            future::Either::Right((None, _)) => {
1121                drop(tx);
1122                future.await?;
1123                Ok(None)
1124            }
1125            future::Either::Left((result, next_message)) => {
1126                result?;
1127                drop(next_message);
1128                // No more output may be accepted from an owned endpoint once
1129                // its driver completes, even if a sender escaped the component.
1130                rx.close();
1131                let Some(frame) = rx.next().await else {
1132                    return Ok(None);
1133                };
1134                Ok(Some((
1135                    frame,
1136                    Self {
1137                        rx,
1138                        tx,
1139                        driver: ProtocolPeerDriver::Completed {
1140                            finish: future.take_finish(),
1141                        },
1142                    },
1143                )))
1144            }
1145        }
1146    }
1147
1148    async fn next_message(self) -> Result<Option<(RawJsonRpcMessage, Self)>, crate::Error> {
1149        let Some((frame, peer)) = self.next_frame().await? else {
1150            return Ok(None);
1151        };
1152        Ok(Some((initialize_message(frame)?, peer)))
1153    }
1154
1155    fn send(&self, message: RawJsonRpcMessage) -> Result<(), crate::Error> {
1156        self.send_frame(TransportFrame::Single(message))
1157    }
1158
1159    fn send_frame(&self, frame: TransportFrame) -> Result<(), crate::Error> {
1160        self.tx
1161            .unbounded_send(frame)
1162            .map_err(crate::util::internal_error)
1163    }
1164}
1165
1166#[cfg(feature = "unstable_protocol_v2")]
1167fn initialize_message(frame: TransportFrame) -> Result<RawJsonRpcMessage, crate::Error> {
1168    match frame {
1169        TransportFrame::Single(message) => Ok(message),
1170        TransportFrame::Malformed { error, .. } => Err(error),
1171    }
1172}
1173
1174#[cfg(feature = "unstable_protocol_v2")]
1175fn initialize_message_mut(
1176    frame: &mut TransportFrame,
1177) -> Result<Option<&mut RawJsonRpcMessage>, crate::Error> {
1178    match frame {
1179        TransportFrame::Single(RawJsonRpcMessage::Response(_)) => Ok(None),
1180        TransportFrame::Single(entry) => Ok(Some(entry)),
1181        TransportFrame::Malformed { raw, .. } if raw_is_response_only_shape(raw) => Ok(None),
1182        TransportFrame::Malformed { error, .. } => Err(error.clone()),
1183    }
1184}
1185
1186// Every protocol router uses the same ownership rule. Passive halves keep
1187// independent lifetimes; owned completion drains output and then either joins
1188// an opposed cooperative driver or cancels opaque work after polling errors.
1189#[cfg(feature = "unstable_protocol_v2")]
1190async fn pipe_protocol_peers_until_done(
1191    left: RunningProtocolPeer,
1192    right: RunningProtocolPeer,
1193) -> Result<(), crate::Error> {
1194    let mut left_driver = left.driver.into_driver();
1195    let mut right_driver = right.driver.into_driver();
1196    let left_passive = left_driver.is_none();
1197    let right_passive = right_driver.is_none();
1198    let left_finish = left_driver
1199        .as_mut()
1200        .and_then(crate::ConnectionDriver::take_finish);
1201    let right_finish = right_driver
1202        .as_mut()
1203        .and_then(crate::ConnectionDriver::take_finish);
1204    let (stop_left_tx, stop_left_rx) = futures::channel::oneshot::channel();
1205    let (stop_right_tx, stop_right_rx) = futures::channel::oneshot::channel();
1206    let stop = async |rx: futures::channel::oneshot::Receiver<()>| {
1207        if rx.await.is_err() {
1208            future::pending::<()>().await;
1209        }
1210    };
1211    let left_to_right = Box::pin(
1212        Channel {
1213            rx: left.rx,
1214            tx: right.tx,
1215        }
1216        .copy_with_driver_until(left_driver, stop(stop_left_rx)),
1217    );
1218    let right_to_left = Box::pin(
1219        Channel {
1220            rx: right.rx,
1221            tx: left.tx,
1222        }
1223        .copy_with_driver_until(right_driver, stop(stop_right_rx)),
1224    );
1225
1226    match future::select(left_to_right, right_to_left).await {
1227        future::Either::Left((result, right_to_left)) => {
1228            result?;
1229            if !left_passive {
1230                let _ = stop_right_tx.send(());
1231            }
1232            if left_passive || right_finish.is_some() {
1233                if !left_passive && let Some(mut finish) = right_finish {
1234                    finish.request();
1235                }
1236                right_to_left.await
1237            } else {
1238                // Without a cooperative finish hook, opposed work may remain
1239                // open indefinitely. Poll ready errors before cancelling it.
1240                crate::util::run_until(right_to_left, future::ready(Ok(()))).await
1241            }
1242        }
1243        future::Either::Right((result, left_to_right)) => {
1244            result?;
1245            if !right_passive {
1246                let _ = stop_left_tx.send(());
1247            }
1248            if right_passive || left_finish.is_some() {
1249                if !right_passive && let Some(mut finish) = left_finish {
1250                    finish.request();
1251                }
1252                left_to_right.await
1253            } else {
1254                crate::util::run_until(left_to_right, future::ready(Ok(()))).await
1255            }
1256        }
1257    }
1258}
1259
1260#[cfg(feature = "unstable_protocol_v2")]
1261#[derive(Debug)]
1262struct InitializeResponse {
1263    id: RawJsonRpcId,
1264    result: Result<serde_json::Value, Box<RawJsonRpcError>>,
1265}
1266
1267#[cfg(feature = "unstable_protocol_v2")]
1268impl InitializeResponse {
1269    fn from_message(message: RawJsonRpcMessage) -> Result<Self, crate::Error> {
1270        match message {
1271            RawJsonRpcMessage::Response(RpcResponse::Result { id, result }) => Ok(Self {
1272                id,
1273                result: Ok(result),
1274            }),
1275            RawJsonRpcMessage::Response(RpcResponse::Error { id, error }) => Ok(Self {
1276                id,
1277                result: Err(error),
1278            }),
1279            message => Err(crate::Error::invalid_request().data(format!(
1280                "first ACP response must be an initialize response, got {message:?}",
1281            ))),
1282        }
1283    }
1284
1285    fn into_message(self) -> RawJsonRpcMessage {
1286        RawJsonRpcMessage::Response(RpcResponse::new(self.id, self.result))
1287    }
1288
1289    fn with_id(self, id: RawJsonRpcId) -> RawJsonRpcMessage {
1290        RawJsonRpcMessage::Response(RpcResponse::new(id, self.result))
1291    }
1292
1293    fn protocol_version(&self) -> Option<ProtocolVersion> {
1294        serde_json::from_value(self.result.as_ref().ok()?.get("protocolVersion")?.clone()).ok()
1295    }
1296}
1297
1298#[cfg(all(test, feature = "unstable_protocol_v2"))]
1299mod raw_initialize_tests {
1300    use super::*;
1301    use serde_json::json;
1302
1303    #[test]
1304    fn initialize_error_forwarding_preserves_raw_fields() {
1305        for data in [
1306            None,
1307            Some(serde_json::Value::Null),
1308            Some(json!({"detail":"kept"})),
1309        ] {
1310            let mut error = json!({
1311                "code":-32000, "message":"peer", "extension":{"retry":true}
1312            });
1313            if let Some(data) = data {
1314                error["data"] = data;
1315            }
1316            let wire = json!({"jsonrpc":"2.0", "id":"original", "error":error});
1317            let response =
1318                InitializeResponse::from_message(serde_json::from_value(wire.clone()).unwrap())
1319                    .unwrap();
1320            assert_eq!(serde_json::to_value(response.into_message()).unwrap(), wire);
1321            let response =
1322                InitializeResponse::from_message(serde_json::from_value(wire).unwrap()).unwrap();
1323            let forwarded = response.with_id(RawJsonRpcId::Str("replacement".into()));
1324            assert_eq!(
1325                serde_json::to_value(forwarded).unwrap(),
1326                json!({"jsonrpc":"2.0", "id":"replacement", "error":error})
1327            );
1328        }
1329    }
1330}
1331
1332#[cfg(feature = "unstable_protocol_v2")]
1333#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1334enum ClientProtocol {
1335    V1,
1336    V2,
1337}
1338
1339#[cfg(feature = "unstable_protocol_v2")]
1340impl ClientProtocol {
1341    fn name(self) -> &'static str {
1342        match self {
1343            Self::V1 => "1",
1344            Self::V2 => "2",
1345        }
1346    }
1347}
1348
1349#[cfg(feature = "unstable_protocol_v2")]
1350async fn start_client_protocol(
1351    protocol: ClientProtocol,
1352    client: DynConnectTo<Agent>,
1353) -> Result<(RunningProtocolPeer, RawJsonRpcMessage), crate::Error> {
1354    let client = RunningProtocolPeer::new(client);
1355    let Some((initialize, client)) = client.next_message().await? else {
1356        return Err(crate::Error::invalid_request().data(format!(
1357            "ACP protocol version {} client implementation ended before initialize",
1358            protocol.name()
1359        )));
1360    };
1361    ensure_client_initialize_request(protocol, &initialize)?;
1362    Ok((client, initialize))
1363}
1364
1365#[cfg(feature = "unstable_protocol_v2")]
1366async fn send_initialize_and_receive(
1367    client: RunningProtocolPeer,
1368    agent: RunningProtocolPeer,
1369    initialize: RawJsonRpcMessage,
1370) -> Result<(RunningProtocolPeer, RunningProtocolPeer, InitializeResponse), crate::Error> {
1371    agent.send(initialize)?;
1372    let Some((response, agent)) = agent.next_message().await? else {
1373        return Err(crate::Error::internal_error().data("agent closed before initialize response"));
1374    };
1375    let response = InitializeResponse::from_message(response)?;
1376    Ok((client, agent, response))
1377}
1378
1379#[cfg(feature = "unstable_protocol_v2")]
1380async fn initialize_client_protocol(
1381    protocol: ClientProtocol,
1382    client: DynConnectTo<Agent>,
1383    agent: impl ConnectTo<Client>,
1384) -> Result<(RunningProtocolPeer, RunningProtocolPeer, InitializeResponse), crate::Error> {
1385    let agent = RunningProtocolPeer::new(agent);
1386    let (client, initialize) = start_client_protocol(protocol, client).await?;
1387    send_initialize_and_receive(client, agent, initialize).await
1388}
1389
1390#[cfg(feature = "unstable_protocol_v2")]
1391async fn connect_client_protocol(
1392    protocol: ClientProtocol,
1393    client: DynConnectTo<Agent>,
1394    agent: impl ConnectTo<Client>,
1395) -> Result<(), crate::Error> {
1396    let (client, agent, initialize_response) =
1397        initialize_client_protocol(protocol, client, agent).await?;
1398    client.send(initialize_response.into_message())?;
1399    pipe_protocol_peers_until_done(client, agent).await
1400}
1401
1402#[cfg(feature = "unstable_protocol_v2")]
1403fn ensure_client_initialize_request(
1404    protocol: ClientProtocol,
1405    message: &RawJsonRpcMessage,
1406) -> Result<(), crate::Error> {
1407    let RawJsonRpcMessage::Request(request) = message else {
1408        return Err(crate::Error::invalid_request().data(format!(
1409            "ACP protocol version {} client implementation must send initialize first",
1410            protocol.name()
1411        )));
1412    };
1413
1414    if request.method.as_ref() != "initialize" {
1415        return Err(crate::Error::invalid_request().data(format!(
1416            "ACP protocol version {} client implementation must send initialize first",
1417            protocol.name()
1418        )));
1419    }
1420
1421    Ok(())
1422}
1423
1424#[cfg(feature = "unstable_protocol_v2")]
1425fn initialize_response_negotiated_v1(response: &InitializeResponse) -> bool {
1426    response.protocol_version() == Some(ProtocolVersion::V1)
1427}
1428
1429impl HasPeer<Agent> for Agent {
1430    fn remote_style(&self, _peer: Agent) -> RemoteStyle {
1431        RemoteStyle::Counterpart
1432    }
1433}
1434
1435/// The proxy role - an intermediary that can intercept and modify messages.
1436///
1437/// Proxies sit between a client and an agent (or another proxy), and can:
1438/// - Add tools via MCP servers
1439/// - Filter or transform messages
1440/// - Inject additional context
1441///
1442/// Proxies connect to a [`Conductor`] which orchestrates the proxy chain.
1443#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
1444pub struct Proxy;
1445
1446impl Role for Proxy {
1447    type Counterpart = Conductor;
1448
1449    fn default_handle_dispatch_from(
1450        &self,
1451        message: crate::Dispatch,
1452        _connection: crate::ConnectionTo<Self>,
1453    ) -> impl Future<Output = Result<crate::Handled<crate::Dispatch>, crate::Error>> + Send {
1454        std::future::ready(Ok(Handled::No {
1455            message,
1456            retry: false,
1457        }))
1458    }
1459
1460    fn role_id(&self) -> RoleId {
1461        RoleId::from_singleton(self)
1462    }
1463
1464    fn counterpart(&self) -> Self::Counterpart {
1465        Conductor
1466    }
1467}
1468
1469impl Proxy {
1470    /// Create a stable protocol v1 connection builder for a proxy.
1471    ///
1472    /// The proxy negotiates `proxy/initialize` the way a v1 agent negotiates
1473    /// `initialize`: it selects v1 for every requested version. A request for
1474    /// a newer version keeps what parses under v1, and one below v1 keeps
1475    /// v1's fallback-to-latest rule.
1476    ///
1477    /// Use `Proxy::v2` for a protocol-v2-only proxy with typed callbacks and
1478    /// wire validation. Protocol-routing infrastructure that deliberately
1479    /// selects a version itself can use the unguarded
1480    /// `Builder::new(Proxy)`.
1481    ///
1482    /// Typed handlers on this builder receive [`V1`](crate::V1) request
1483    /// handles.
1484    pub fn v1(self) -> crate::v1::Builder<Proxy> {
1485        Builder::new(self).v1_proxy()
1486    }
1487
1488    /// Create a proxy builder that uses the ACP protocol v2 API.
1489    ///
1490    /// The proxy negotiates `proxy/initialize` the way a v2 agent negotiates
1491    /// `initialize`: it selects v2 for a request for v2 or newer, keeping what
1492    /// parses under v2 for a newer request, and rejects a request below v2
1493    /// with `-32022`.
1494    /// Fluent callbacks receive [`v2::ConnectionTo<Conductor>`](crate::v2::ConnectionTo), while
1495    /// low-level custom handlers and runners retain the protocol-neutral
1496    /// [`ConnectionTo`] interface.
1497    ///
1498    /// Requires the `unstable_protocol_v2` crate feature.
1499    #[cfg(feature = "unstable_protocol_v2")]
1500    pub fn v2(self) -> crate::v2::Builder<Proxy> {
1501        Builder::new(self).v2_proxy()
1502    }
1503
1504    /// Create a router that chooses between configured proxy implementations.
1505    ///
1506    /// Add implementations with [`ProxyProtocolRouter::with_v1`] and
1507    /// [`ProxyProtocolRouter::with_v2`]. The router reads the initial
1508    /// `proxy/initialize` request and selects an implementation exactly as
1509    /// [`Agent::protocol_router`] does for `initialize`: a request for v2 or
1510    /// newer selects the v2 implementation, keeping what parses under v2 for
1511    /// a newer request. With a v1 implementation configured, everything else
1512    /// is handed to the v1 implementation, which negotiates it as it would
1513    /// without the router. A v2-only router rejects a request below v2 with
1514    /// `-32022`. Like the agent router, it answers each rejected request or
1515    /// malformed frame with an error and keeps reading, so the conductor can
1516    /// send `proxy/initialize` again. A request for exactly the selected
1517    /// version is handed over in the complete, unchanged initial transport
1518    /// frame. The router does not convert later messages.
1519    ///
1520    /// Requires the `unstable_protocol_v2` crate feature while protocol v2
1521    /// stabilizes.
1522    #[cfg(feature = "unstable_protocol_v2")]
1523    #[must_use]
1524    pub fn protocol_router(self) -> ProxyProtocolRouter {
1525        ProxyProtocolRouter::new()
1526    }
1527}
1528
1529/// Proxy component that routes each connection to a configured protocol implementation.
1530///
1531/// Use [`Proxy::protocol_router`] to start the builder, then add stable-v1 and
1532/// draft-v2 proxy implementations independently. Like [`AgentProtocolRouter`],
1533/// it selects the highest configured version at or below the one
1534/// `proxy/initialize` requests.
1535///
1536/// The `with_v1` and `with_v2` slots take any `ConnectTo<Conductor>`; nothing checks that an
1537/// implementation speaks the slot's version. Put a `.v1()` implementation in
1538/// `with_v1` and a `.v2()` implementation in `with_v2`.
1539#[cfg(feature = "unstable_protocol_v2")]
1540#[derive(Debug, Default)]
1541pub struct ProxyProtocolRouter {
1542    v1: Option<DynConnectTo<Conductor>>,
1543    v2: Option<DynConnectTo<Conductor>>,
1544}
1545
1546#[cfg(feature = "unstable_protocol_v2")]
1547impl ProxyProtocolRouter {
1548    /// Create an empty proxy protocol router.
1549    #[must_use]
1550    pub fn new() -> Self {
1551        Self::default()
1552    }
1553
1554    /// Return this router with a stable ACP v1 proxy implementation.
1555    #[must_use]
1556    pub fn with_v1(mut self, proxy: impl ConnectTo<Conductor>) -> Self {
1557        self.v1 = Some(DynConnectTo::new(proxy));
1558        self
1559    }
1560
1561    /// Return this router with a draft ACP v2 proxy implementation.
1562    #[must_use]
1563    pub fn with_v2(mut self, proxy: impl ConnectTo<Conductor>) -> Self {
1564        self.v2 = Some(DynConnectTo::new(proxy));
1565        self
1566    }
1567}
1568
1569#[cfg(feature = "unstable_protocol_v2")]
1570impl ConnectTo<Conductor> for ProxyProtocolRouter {
1571    async fn connect_to(self, conductor: impl ConnectTo<Proxy>) -> Result<(), crate::Error> {
1572        let supported = SupportedProtocols {
1573            v1: self.v1.is_some(),
1574            v2: self.v2.is_some(),
1575        };
1576        let conductor = RunningProtocolPeer::new(conductor);
1577        let Some((first_frame, conductor, selected)) =
1578            select_protocol_peer(conductor, PROXY_METHOD_NAMES.proxy_initialize, supported).await?
1579        else {
1580            return Ok(());
1581        };
1582        let proxy = selected
1583            .take_proxy(self)
1584            .expect("the router only selects a configured implementation");
1585
1586        let proxy = RunningProtocolPeer::new(proxy);
1587        proxy.send_frame(first_frame)?;
1588        pipe_protocol_peers_until_done(conductor, proxy).await
1589    }
1590}
1591
1592#[cfg(feature = "unstable_protocol_v2")]
1593impl SelectedProtocol {
1594    fn take_proxy(self, proxy: ProxyProtocolRouter) -> Option<DynConnectTo<Conductor>> {
1595        match self {
1596            Self::V1 => proxy.v1,
1597            Self::V2 => proxy.v2,
1598        }
1599    }
1600}
1601
1602impl HasPeer<Proxy> for Proxy {
1603    fn remote_style(&self, _peer: Proxy) -> RemoteStyle {
1604        RemoteStyle::Counterpart
1605    }
1606}
1607
1608/// The conductor role - orchestrates proxy chains.
1609///
1610/// Conductors manage connections between clients, proxies, and agents,
1611/// routing messages through the appropriate proxy chain.
1612#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
1613pub struct Conductor;
1614
1615impl Role for Conductor {
1616    type Counterpart = Proxy;
1617
1618    fn role_id(&self) -> RoleId {
1619        RoleId::from_singleton(self)
1620    }
1621
1622    fn counterpart(&self) -> Self::Counterpart {
1623        Proxy
1624    }
1625
1626    async fn default_handle_dispatch_from(
1627        &self,
1628        message: Dispatch,
1629        cx: ConnectionTo<Conductor>,
1630    ) -> Result<Handled<Dispatch>, crate::Error> {
1631        forward_proxy_dispatch(message, cx).await
1632    }
1633}
1634
1635/// Default forwarding for a proxy.
1636///
1637/// `proxy/initialize` has the same wire shape in every protocol version, so
1638/// one untyped path serves v1 and v2 proxies alike. Messages are forwarded
1639/// without being parsed and re-serialized, so fields this SDK does not know
1640/// survive. The connection's protocol guard, if any, has already validated
1641/// them. A `session/new` response installs the session's update routing from
1642/// its raw `sessionId`.
1643async fn forward_proxy_dispatch(
1644    message: Dispatch,
1645    cx: ConnectionTo<Conductor>,
1646) -> Result<Handled<Dispatch>, crate::Error> {
1647    let message = match message {
1648        Dispatch::Request(request, responder) if request.method() == "initialize" => {
1649            responder.respond_with_error(crate::Error::invalid_request().data(format!(
1650                "proxies must be initialized with `{}`",
1651                PROXY_METHOD_NAMES.proxy_initialize
1652            )))?;
1653            return Ok(Handled::Yes);
1654        }
1655        Dispatch::Request(mut request, responder)
1656            if request.method() == PROXY_METHOD_NAMES.proxy_initialize =>
1657        {
1658            request.method = "initialize".to_string();
1659            cx.prepare_request_to(Agent, request)
1660                .forward_response_to(responder)?;
1661            return Ok(Handled::Yes);
1662        }
1663        Dispatch::Request(request, responder) if request.method() == "session/new" => {
1664            let sent = cx
1665                .prepare_request_to(Agent, request)
1666                .forwarded_from(&responder);
1667            sent.on_receiving_result({
1668                let cx = cx.clone();
1669                async move |result| {
1670                    // The result goes back unchanged, as the proxy chains RFD
1671                    // requires, even when no session routing can be installed
1672                    // from it.
1673                    if let Ok(response) = &result
1674                        && let Err(error) = install_proxy_session_routing(&cx, response)
1675                    {
1676                        tracing::warn!(
1677                            error = ?crate::util::redacted_error(error.code),
1678                            "forwarding a `session/new` result without session routing"
1679                        );
1680                    }
1681                    responder.respond_with_result(result)
1682                }
1683            })?;
1684            return Ok(Handled::Yes);
1685        }
1686        message => message,
1687    };
1688
1689    MatchDispatchFrom::new(message, &cx)
1690        .if_dispatch_from(Client, async |message: Dispatch| {
1691            cx.send_proxied_message_to(Agent, message)
1692        })
1693        .await
1694        .if_dispatch_from(Agent, async |message: Dispatch| {
1695            cx.send_proxied_message_to(Client, message)
1696        })
1697        .await
1698        .done()
1699}
1700
1701/// Route the updates of the session a forwarded `session/new` result created.
1702fn install_proxy_session_routing(
1703    cx: &ConnectionTo<Conductor>,
1704    response: &serde_json::Value,
1705) -> Result<(), crate::Error> {
1706    let envelope: NewSessionResponseEnvelope = crate::util::json_cast(response)?;
1707    cx.add_dynamic_handler(ProxySessionMessages::new(envelope.session_id))?
1708        .detach();
1709    Ok(())
1710}
1711
1712impl Conductor {
1713    /// Create a connection builder for a conductor.
1714    pub fn builder(self) -> Builder<Conductor, NullHandler, NullRun> {
1715        Builder::new(self)
1716    }
1717}
1718
1719impl HasPeer<Client> for Conductor {
1720    fn remote_style(&self, _peer: Client) -> RemoteStyle {
1721        RemoteStyle::Predecessor
1722    }
1723}
1724
1725impl HasPeer<Agent> for Conductor {
1726    fn remote_style(&self, _peer: Agent) -> RemoteStyle {
1727        RemoteStyle::Successor
1728    }
1729}
1730
1731/// Dynamic handler that proxies session messages from Agent to Client.
1732///
1733/// This is used internally to handle session message routing after a
1734/// `session.new` request has been forwarded.
1735pub(crate) struct ProxySessionMessages {
1736    session_id: SessionId,
1737}
1738
1739impl ProxySessionMessages {
1740    /// Create a new proxy handler for the given session.
1741    pub fn new(session_id: SessionId) -> Self {
1742        Self { session_id }
1743    }
1744}
1745
1746impl<Counterpart: Role> HandleDispatchFrom<Counterpart> for ProxySessionMessages
1747where
1748    Counterpart: HasPeer<Agent> + HasPeer<Client>,
1749{
1750    async fn handle_dispatch_from(
1751        &mut self,
1752        message: Dispatch,
1753        connection: ConnectionTo<Counterpart>,
1754    ) -> Result<Handled<Dispatch>, crate::Error> {
1755        MatchDispatchFrom::new(message, &connection)
1756            .if_dispatch_from(Agent, async |message| {
1757                // If this is for our session-id, proxy it to the client.
1758                if let Some(session_id) = message.get_session_id()?
1759                    && session_id == self.session_id
1760                {
1761                    connection.send_proxied_message_to(Client, message)?;
1762                    return Ok(Handled::Yes);
1763                }
1764
1765                // Otherwise, leave it alone.
1766                Ok(Handled::No {
1767                    message,
1768                    retry: false,
1769                })
1770            })
1771            .await
1772            .done()
1773    }
1774
1775    fn describe_chain(&self) -> impl std::fmt::Debug {
1776        format!("ProxySessionMessages({})", self.session_id)
1777    }
1778}
1779
1780#[cfg(all(test, feature = "unstable_protocol_v2"))]
1781mod lifetime_tests {
1782    use super::*;
1783    use crate::{ConnectionDriver, UntypedRole};
1784    use futures::FutureExt as _;
1785
1786    fn frame() -> TransportFrame {
1787        TransportFrame::parse_json(r#"{"jsonrpc":"2.0","method":"test/queued","params":{}}"#)
1788    }
1789
1790    #[tokio::test]
1791    async fn passive_initialization_waits_for_a_frame_not_driver_readiness() {
1792        let (channel, remote) = Channel::duplex();
1793        let peer = RunningProtocolPeer::new::<UntypedRole>(channel);
1794        let mut next = Box::pin(peer.next_frame());
1795        assert!(next.as_mut().now_or_never().is_none());
1796
1797        remote.tx.unbounded_send(frame()).unwrap();
1798        let (_, peer) = next.await.unwrap().expect("passive peer remains connected");
1799        assert!(matches!(peer.driver, ProtocolPeerDriver::Passive));
1800    }
1801
1802    #[tokio::test]
1803    async fn owned_peer_preserves_finish_metadata_through_active_and_completed_states() {
1804        let (Channel { rx, tx }, remote) = Channel::duplex();
1805        let (done_tx, done_rx) = futures::channel::oneshot::channel();
1806        let (finish_tx, finish_rx) = futures::channel::oneshot::channel();
1807        let peer = RunningProtocolPeer {
1808            rx,
1809            tx,
1810            driver: ProtocolPeerDriver::Active(ConnectionDriver::with_finish(
1811                async move {
1812                    done_rx.await.unwrap();
1813                    Ok(())
1814                },
1815                move || {
1816                    let _ = finish_tx.send(());
1817                },
1818            )),
1819        };
1820
1821        remote.tx.unbounded_send(frame()).unwrap();
1822        let (_, peer) = peer.next_frame().await.unwrap().unwrap();
1823        assert!(matches!(&peer.driver, ProtocolPeerDriver::Active(_)));
1824
1825        remote.tx.unbounded_send(frame()).unwrap();
1826        done_tx.send(()).unwrap();
1827        let (_, peer) = peer.next_frame().await.unwrap().unwrap();
1828        assert!(matches!(
1829            &peer.driver,
1830            ProtocolPeerDriver::Completed { finish: Some(_) }
1831        ));
1832        let mut driver = peer
1833            .driver
1834            .into_driver()
1835            .expect("completed owned work must not become passive");
1836        assert!(driver.request_finish());
1837        finish_rx.await.unwrap();
1838        driver.await.unwrap();
1839    }
1840
1841    #[tokio::test]
1842    async fn active_initialization_drains_accepted_frames_without_escaped_sender_eof() {
1843        let (Channel { rx, tx }, remote) = Channel::duplex();
1844        remote.tx.unbounded_send(frame()).unwrap();
1845        remote.tx.unbounded_send(frame()).unwrap();
1846        let mut polls = 0;
1847        let driver = ConnectionDriver::new(future::poll_fn(move |_| {
1848            polls += 1;
1849            assert_eq!(polls, 1, "the completed driver must never be re-polled");
1850            std::task::Poll::Ready(Ok(()))
1851        }));
1852        let peer = RunningProtocolPeer {
1853            rx,
1854            tx,
1855            driver: ProtocolPeerDriver::Active(driver),
1856        };
1857
1858        let (_, peer) = peer.next_frame().await.unwrap().unwrap();
1859        assert!(
1860            remote.tx.unbounded_send(frame()).is_err(),
1861            "active completion must reject new output from escaped handles"
1862        );
1863        let (_, peer) = peer.next_frame().await.unwrap().unwrap();
1864        assert!(peer.next_frame().await.unwrap().is_none());
1865    }
1866
1867    #[tokio::test]
1868    async fn ready_initialization_driver_error_beats_queued_frames() {
1869        let (Channel { rx, tx }, remote) = Channel::duplex();
1870        remote.tx.unbounded_send(frame()).unwrap();
1871        let error = crate::Error::internal_error().data("owned initialization failed");
1872        let peer = RunningProtocolPeer {
1873            rx,
1874            tx,
1875            driver: ProtocolPeerDriver::Active(ConnectionDriver::new(future::ready(Err(
1876                error.clone()
1877            )))),
1878        };
1879
1880        match peer.next_frame().await {
1881            Err(actual) => assert_eq!(actual, error),
1882            Ok(_) => panic!("ready driver error must not be hidden by a queued frame"),
1883        }
1884    }
1885
1886    struct QueuedFinalClient;
1887
1888    impl ConnectTo<Agent> for QueuedFinalClient {
1889        async fn connect_to(self, agent: impl ConnectTo<Client>) -> Result<(), crate::Error> {
1890            let (mut channel, driver) = agent.into_channel_and_future();
1891            let foreground = async move {
1892                channel
1893                    .tx
1894                    .unbounded_send(TransportFrame::Single(RawJsonRpcMessage::request(
1895                        "initialize".into(),
1896                        serde_json::json!({ "protocolVersion": 1, "clientCapabilities": {} }),
1897                        RawJsonRpcId::Number(1),
1898                    )?))
1899                    .unwrap();
1900                assert!(channel.rx.next().await.is_some(), "initialize response");
1901                // Exceed the physical writer capacity so only concurrent polling
1902                // of the sink can make this bridge finish.
1903                for index in 0..3 {
1904                    channel
1905                        .tx
1906                        .unbounded_send(TransportFrame::Single(RawJsonRpcMessage::notification(
1907                            "test/final".into(),
1908                            serde_json::json!({ "index": index, "payload": "x".repeat(1024) }),
1909                        )?))
1910                        .unwrap();
1911                }
1912                Ok(())
1913            };
1914            match driver {
1915                Some(driver) => crate::util::run_until(driver, foreground).await,
1916                None => foreground.await,
1917            }
1918        }
1919    }
1920
1921    #[tokio::test]
1922    async fn connector_completion_flushes_byte_streams_without_remote_read_eof() {
1923        use tokio::io::{AsyncBufReadExt as _, AsyncWriteExt as _, BufReader};
1924        use tokio_util::compat::{TokioAsyncReadCompatExt as _, TokioAsyncWriteCompatExt as _};
1925
1926        let (writer, remote_reader) = tokio::io::duplex(64);
1927        let (mut remote_input, reader) = tokio::io::duplex(64);
1928        let physical = crate::ByteStreams::new(writer.compat_write(), reader.compat());
1929        let mut physical = Some(crate::DynConnectTo::<Client>::new(physical));
1930        let connector = tokio::spawn(
1931            ClientProtocolConnector::new()
1932                .with_v1(|| QueuedFinalClient)
1933                .connect_to(move || physical.take().expect("one physical connection")),
1934        );
1935        let mut lines = BufReader::new(remote_reader).lines();
1936
1937        tokio::time::timeout(std::time::Duration::from_secs(5), async {
1938            let initialize = lines
1939                .next_line()
1940                .await
1941                .unwrap()
1942                .expect("initialize request");
1943            let value: serde_json::Value = serde_json::from_str(&initialize).unwrap();
1944            assert_eq!(value["method"], "initialize");
1945            remote_input
1946                .write_all(b"{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{\"protocolVersion\":1}}\n")
1947                .await
1948                .unwrap();
1949            for index in 0..3 {
1950                let line = lines
1951                    .next_line()
1952                    .await
1953                    .unwrap()
1954                    .expect("accepted final output");
1955                let value: serde_json::Value = serde_json::from_str(&line).unwrap();
1956                assert_eq!(value["params"]["index"], index);
1957                assert_eq!(value["params"]["payload"].as_str().unwrap().len(), 1024);
1958            }
1959            connector.await.unwrap().unwrap();
1960            assert!(lines.next_line().await.unwrap().is_none());
1961        })
1962        .await
1963        .expect("physical flush must not wait for independent remote input EOF");
1964        drop(remote_input);
1965    }
1966
1967    #[derive(Default, Debug)]
1968    struct GatedLineSinkState {
1969        pending: Vec<String>,
1970        flushed: Vec<String>,
1971        closed: bool,
1972        dropped: bool,
1973    }
1974
1975    struct GatedLineSink {
1976        state: std::sync::Arc<std::sync::Mutex<GatedLineSinkState>>,
1977        release: futures::channel::oneshot::Receiver<()>,
1978        released: bool,
1979    }
1980
1981    impl futures::Sink<String> for GatedLineSink {
1982        type Error = std::io::Error;
1983
1984        fn poll_ready(
1985            self: std::pin::Pin<&mut Self>,
1986            _: &mut std::task::Context<'_>,
1987        ) -> std::task::Poll<Result<(), Self::Error>> {
1988            std::task::Poll::Ready(Ok(()))
1989        }
1990
1991        fn start_send(self: std::pin::Pin<&mut Self>, line: String) -> Result<(), Self::Error> {
1992            self.state.lock().unwrap().pending.push(line);
1993            Ok(())
1994        }
1995
1996        fn poll_flush(
1997            mut self: std::pin::Pin<&mut Self>,
1998            cx: &mut std::task::Context<'_>,
1999        ) -> std::task::Poll<Result<(), Self::Error>> {
2000            if !self.released {
2001                if std::pin::Pin::new(&mut self.release).poll(cx).is_pending() {
2002                    return std::task::Poll::Pending;
2003                }
2004                self.released = true;
2005            }
2006            let mut state = self.state.lock().unwrap();
2007            let pending = std::mem::take(&mut state.pending);
2008            state.flushed.extend(pending);
2009            std::task::Poll::Ready(Ok(()))
2010        }
2011
2012        fn poll_close(
2013            mut self: std::pin::Pin<&mut Self>,
2014            cx: &mut std::task::Context<'_>,
2015        ) -> std::task::Poll<Result<(), Self::Error>> {
2016            match self.as_mut().poll_flush(cx) {
2017                std::task::Poll::Ready(Ok(())) => {
2018                    self.state.lock().unwrap().closed = true;
2019                    std::task::Poll::Ready(Ok(()))
2020                }
2021                result => result,
2022            }
2023        }
2024    }
2025
2026    impl Drop for GatedLineSink {
2027        fn drop(&mut self) {
2028            self.state.lock().unwrap().dropped = true;
2029        }
2030    }
2031
2032    #[tokio::test]
2033    async fn foreground_completion_flushes_lines_with_already_normalized_remote_input() {
2034        let state = std::sync::Arc::new(std::sync::Mutex::new(GatedLineSinkState::default()));
2035        let (release_tx, release_rx) = futures::channel::oneshot::channel();
2036        let sink = GatedLineSink {
2037            state: state.clone(),
2038            release: release_rx,
2039            released: false,
2040        };
2041        let (remote_input, incoming) = futures::channel::mpsc::unbounded();
2042        remote_input
2043            .unbounded_send(Ok(
2044                r#"{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1}}"#.to_string(),
2045            ))
2046            .unwrap();
2047        remote_input
2048            .unbounded_send(Ok(
2049                r#"{"jsonrpc":"2.0","method":"test/queued","params":{}}"#.to_string(),
2050            ))
2051            .unwrap();
2052        let physical = RunningProtocolPeer::new::<Client>(crate::Lines::new(sink, incoming));
2053        // The real Lines driver reads both ready lines before this returns.
2054        let (initialize, physical) = physical.next_frame().await.unwrap().unwrap();
2055        assert_eq!(
2056            futures::Stream::size_hint(&physical.rx).0,
2057            1,
2058            "trailing input must already be in the original normalized queue"
2059        );
2060
2061        let (Channel { rx, tx }, mut local) = Channel::duplex();
2062        tx.unbounded_send(initialize).unwrap();
2063        let foreground = RunningProtocolPeer {
2064            rx,
2065            tx,
2066            driver: ProtocolPeerDriver::Active(ConnectionDriver::new(async move {
2067                assert!(local.rx.next().await.is_some(), "initialize response");
2068                for index in 0..3 {
2069                    local
2070                        .tx
2071                        .unbounded_send(TransportFrame::Single(RawJsonRpcMessage::notification(
2072                            "test/final".into(),
2073                            serde_json::json!({ "index": index, "payload": "x".repeat(1024) }),
2074                        )?))
2075                        .unwrap();
2076                }
2077                // This owns the foreground input receiver: completion closes it.
2078                drop(local);
2079                Ok(())
2080            })),
2081        };
2082        let mut bridge = Box::pin(pipe_protocol_peers_until_done(foreground, physical));
2083        let early_result = bridge.as_mut().now_or_never();
2084        assert!(
2085            !state.lock().unwrap().pending.is_empty(),
2086            "the real physical writer must accept output before the gated flush"
2087        );
2088        // Never use time to establish the race: only the sink gate controls drain.
2089        let _released = release_tx.send(());
2090        let result = match early_result {
2091            Some(result) => result,
2092            None => tokio::time::timeout(std::time::Duration::from_secs(1), bridge)
2093                .await
2094                .expect("physical drain must not require remote input EOF"),
2095        };
2096        let state = state.lock().unwrap();
2097        assert!(
2098            result.is_ok() && state.flushed.len() == 3 && state.closed,
2099            "accepted output must drain cleanly despite queued remote input: result={result:?}, pending={}, flushed={}, closed={}, dropped={}",
2100            state.pending.len(),
2101            state.flushed.len(),
2102            state.closed,
2103            state.dropped,
2104        );
2105        for (index, line) in state.flushed.iter().enumerate() {
2106            let value: serde_json::Value = serde_json::from_str(line).unwrap();
2107            assert_eq!(value["method"], "test/final");
2108            assert_eq!(value["params"]["index"], index);
2109            assert_eq!(value["params"]["payload"].as_str().unwrap().len(), 1024);
2110        }
2111        drop(remote_input);
2112    }
2113
2114    #[tokio::test]
2115    async fn foreground_completion_keeps_read_errors_during_lines_drain() {
2116        let state = std::sync::Arc::new(std::sync::Mutex::new(GatedLineSinkState::default()));
2117        let (_release_tx, release_rx) = futures::channel::oneshot::channel();
2118        let sink = GatedLineSink {
2119            state: state.clone(),
2120            release: release_rx,
2121            released: false,
2122        };
2123        let (remote_input, incoming) = futures::channel::mpsc::unbounded();
2124        let physical = RunningProtocolPeer::new::<Client>(crate::Lines::new(sink, incoming));
2125        let (Channel { rx, tx }, local) = Channel::duplex();
2126        local.tx.unbounded_send(frame()).unwrap();
2127        drop(local);
2128        let foreground = RunningProtocolPeer {
2129            rx,
2130            tx,
2131            driver: ProtocolPeerDriver::Active(ConnectionDriver::new(future::ready(Ok(())))),
2132        };
2133        let mut bridge = Box::pin(pipe_protocol_peers_until_done(foreground, physical));
2134        assert!(bridge.as_mut().now_or_never().is_none());
2135        assert_eq!(state.lock().unwrap().pending.len(), 1);
2136
2137        // Newly read successful input is irrelevant to the completed foreground,
2138        // but a genuine read failure must still cancel the blocked sink drain.
2139        remote_input
2140            .unbounded_send(Ok(r#"{"jsonrpc":"2.0","method":"late"}"#.to_string()))
2141            .unwrap();
2142        remote_input
2143            .unbounded_send(Err(std::io::Error::other("read failed after foreground")))
2144            .unwrap();
2145        let error = tokio::time::timeout(std::time::Duration::from_secs(1), bridge)
2146            .await
2147            .expect("read failure must not wait for the sink gate")
2148            .expect_err("real read error must win over foreground success");
2149        assert!(
2150            error
2151                .data
2152                .unwrap()
2153                .to_string()
2154                .contains("read failed after foreground"),
2155            "the read error must not become a receiver-gone forwarding error"
2156        );
2157        assert_eq!(state.lock().unwrap().flushed, Vec::<String>::new());
2158    }
2159
2160    #[tokio::test]
2161    async fn foreground_completion_cancels_opposed_opaque_work_in_both_directions() {
2162        for foreground_on_left in [true, false] {
2163            let (Channel { rx, tx }, foreground_remote) = Channel::duplex();
2164            foreground_remote.tx.unbounded_send(frame()).unwrap();
2165            let foreground = RunningProtocolPeer {
2166                rx,
2167                tx,
2168                driver: ProtocolPeerDriver::Active(ConnectionDriver::new(future::ready(Ok(())))),
2169            };
2170            let (Channel { rx, tx }, mut opposed_remote) = Channel::duplex();
2171            let (work_tx, work_rx) = futures::channel::oneshot::channel::<()>();
2172            let opposed = RunningProtocolPeer {
2173                rx,
2174                tx,
2175                driver: ProtocolPeerDriver::Active(ConnectionDriver::new(async move {
2176                    work_rx.await.map_err(crate::util::internal_error)?;
2177                    Ok(())
2178                })),
2179            };
2180            let mut bridge = Box::pin(if foreground_on_left {
2181                pipe_protocol_peers_until_done(foreground, opposed)
2182            } else {
2183                pipe_protocol_peers_until_done(opposed, foreground)
2184            });
2185
2186            assert_eq!(
2187                bridge.as_mut().now_or_never(),
2188                Some(Ok(())),
2189                "finite foreground must not join an opaque pending peer"
2190            );
2191            assert!(work_tx.is_canceled(), "opaque work must be dropped");
2192            assert!(opposed_remote.rx.next().await.is_some());
2193            assert!(opposed_remote.rx.next().await.is_none());
2194        }
2195    }
2196
2197    #[tokio::test]
2198    async fn foreground_completion_does_not_hide_opposed_ready_driver_error() {
2199        let (Channel { rx, tx }, _foreground_remote) = Channel::duplex();
2200        let foreground = RunningProtocolPeer {
2201            rx,
2202            tx,
2203            driver: ProtocolPeerDriver::Active(ConnectionDriver::new(future::ready(Ok(())))),
2204        };
2205        let (Channel { rx, tx }, _opposed_remote) = Channel::duplex();
2206        let error = crate::Error::internal_error().data("opposed driver failed");
2207        let opposed = RunningProtocolPeer {
2208            rx,
2209            tx,
2210            driver: ProtocolPeerDriver::Active(ConnectionDriver::new(future::ready(Err(
2211                error.clone()
2212            )))),
2213        };
2214
2215        assert_eq!(
2216            pipe_protocol_peers_until_done(foreground, opposed).await,
2217            Err(error)
2218        );
2219    }
2220
2221    #[tokio::test]
2222    async fn passive_protocol_bridge_preserves_the_reverse_half_after_eof() {
2223        let (left, mut remote_left) = Channel::duplex();
2224        let (right, mut remote_right) = Channel::duplex();
2225        let mut bridge = Box::pin(pipe_protocol_peers_until_done(
2226            RunningProtocolPeer::new::<UntypedRole>(left),
2227            RunningProtocolPeer::new::<UntypedRole>(right),
2228        ));
2229        remote_left.tx.close_channel();
2230        assert!(bridge.as_mut().now_or_never().is_none());
2231        assert!(remote_right.rx.next().await.is_none());
2232
2233        remote_right.tx.unbounded_send(frame()).unwrap();
2234        remote_right.tx.close_channel();
2235        bridge.await.unwrap();
2236        assert!(remote_left.rx.next().await.is_some());
2237        assert!(remote_left.rx.next().await.is_none());
2238    }
2239}