Skip to main content

agent_client_protocol/
jsonrpc.rs

1//! Core JSON-RPC server support.
2
3use agent_client_protocol_schema::v1::{JsonRpcMessage as VersionedJsonRpcMessage, SessionId};
4
5// Types re-exported from crate root
6use serde::{Deserialize, Serialize};
7use std::any::TypeId;
8use std::collections::HashMap;
9use std::fmt::Debug;
10use std::marker::PhantomData;
11use std::panic::Location;
12use std::pin::pin;
13use std::sync::{
14    Arc, Mutex, Weak,
15    atomic::{AtomicBool, AtomicU8, Ordering},
16};
17use uuid::Uuid;
18
19use futures::FutureExt;
20use futures::channel::{mpsc, oneshot};
21use futures::future::{self, BoxFuture, Either};
22use futures::{AsyncRead, AsyncWrite, StreamExt};
23
24pub(crate) mod close;
25mod dynamic_handler;
26pub(crate) mod handlers;
27mod incoming_actor;
28mod outgoing_actor;
29#[cfg(test)]
30mod prepared_request_tests;
31pub(crate) mod protocol;
32mod protocol_compat;
33mod raw_error;
34pub(crate) mod raw_id;
35pub(crate) mod run;
36mod task_actor;
37mod termination;
38mod transport_actor;
39pub(crate) mod v1_connection;
40#[cfg(feature = "unstable_protocol_v2")]
41pub(crate) mod v2_connection;
42
43use crate::jsonrpc::close::{ChainedClose, CloseCallback};
44pub use crate::jsonrpc::close::{HandleConnectionClose, NullClose};
45use crate::jsonrpc::dynamic_handler::DynamicHandlerMessage;
46pub use crate::jsonrpc::handlers::NullHandler;
47use crate::jsonrpc::handlers::{ChainedHandler, NamedHandler};
48use crate::jsonrpc::handlers::{MessageHandler, NotificationHandler, RequestHandler};
49use crate::jsonrpc::outgoing_actor::{OutgoingMessageTx, send_raw_message};
50use crate::jsonrpc::protocol::HandleId;
51#[cfg(feature = "unstable_protocol_v2")]
52pub use crate::jsonrpc::protocol::V2;
53
54#[cfg(feature = "unstable_mcp_over_acp")]
55use crate::Client;
56pub use crate::jsonrpc::protocol::{Protocol, Raw, V1};
57#[cfg(feature = "unstable_protocol_v2")]
58pub(crate) use crate::jsonrpc::protocol_compat::normalize_newer_v2_initialize_request;
59pub(crate) use crate::jsonrpc::protocol_compat::normalize_v1_initialize_request;
60#[cfg(feature = "unstable_protocol_v2")]
61pub use crate::jsonrpc::protocol_compat::{
62    InitializationVersionMismatch, InitializeOutcome, SelectedInitializeResponse,
63};
64use crate::jsonrpc::protocol_compat::{ProtocolCompat, ProtocolMode};
65pub use crate::jsonrpc::raw_error::{RawJsonRpcError, RawJsonRpcResponse};
66pub use crate::jsonrpc::raw_id::RawJsonRpcId;
67use crate::jsonrpc::run::SpawnedRun;
68use crate::jsonrpc::run::{ChainRun, NullRun, RunWithConnectionTo};
69use crate::jsonrpc::task_actor::{Task, TaskTx};
70pub use crate::jsonrpc::termination::{
71    CONNECTION_TERMINATED_REASON, ConnectionTermination, is_connection_terminated,
72};
73use crate::jsonrpc::termination::{
74    TerminationSource, TerminationSources, connection_terminated_error,
75};
76#[cfg(feature = "unstable_mcp_over_acp")]
77use crate::mcp_server::McpServer;
78use crate::role::HasPeer;
79use crate::role::Role;
80use crate::{Agent, ConnectTo, RoleId};
81
82/// One valid JSON-RPC message carried inside a [`TransportFrame`].
83///
84/// Raw messages are the same for every ACP protocol version: IDs are
85/// [`RawJsonRpcId`]s, and method params and response errors are not
86/// interpreted at the transport boundary.
87///
88/// Serializing adds the `"jsonrpc": "2.0"` member, and deserializing requires
89/// it. Requests and notifications keep only `id`, `method` and `params`:
90/// other members of the envelope are dropped. Error responses keep unknown
91/// members of the error object in [`RawJsonRpcError::extra`].
92#[derive(Debug, Clone, PartialEq, Eq)]
93#[allow(
94    clippy::exhaustive_enums,
95    reason = "JSON-RPC defines exactly these message kinds"
96)]
97pub enum RawJsonRpcMessage {
98    /// A JSON-RPC request with an id and expected response.
99    Request(RawJsonRpcRequest),
100    /// A JSON-RPC notification without a response.
101    Notification(RawJsonRpcNotification),
102    /// A JSON-RPC response to a prior request.
103    Response(RawJsonRpcResponse),
104}
105
106/// A JSON-RPC frame exchanged between protocol components and transports.
107///
108/// A frame is one JSON-RPC wire value. Malformed wire input, including a
109/// JSON-RPC batch array, which the SDK does not support, is represented
110/// explicitly; transport failures are reported by the future that drives the
111/// transport rather than sent through a [`Channel`].
112#[derive(Clone, Debug)]
113#[non_exhaustive]
114pub enum TransportFrame {
115    /// One valid JSON-RPC message.
116    Single(RawJsonRpcMessage),
117    /// One malformed or invalid wire value retained for relays.
118    Malformed {
119        /// The original wire representation.
120        raw: String,
121        /// The JSON-RPC error associated with the malformed value.
122        error: crate::Error,
123    },
124}
125
126pub(crate) fn is_response_only_shape(value: &serde_json::Value) -> bool {
127    value.as_object().is_some_and(|object| {
128        !object.contains_key("method")
129            && (object.contains_key("result") || object.contains_key("error"))
130    })
131}
132
133pub(crate) fn raw_is_response_only_shape(raw: &str) -> bool {
134    serde_json::from_str(raw).is_ok_and(|value| is_response_only_shape(&value))
135}
136
137impl TransportFrame {
138    fn inspect_messages(
139        &self,
140        observer: &mut impl FnMut(&RawJsonRpcMessage) -> Result<(), crate::Error>,
141    ) -> Result<(), crate::Error> {
142        match self {
143            Self::Single(message) => observer(message),
144            Self::Malformed { .. } => Ok(()),
145        }
146    }
147}
148
149/// A JSON-RPC request with uninterpreted params.
150///
151/// This is the request without the `jsonrpc` member, which
152/// [`RawJsonRpcMessage`] adds and checks. Other members of the request object
153/// are not kept: a relay that parses and re-serializes a request drops them.
154#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
155#[allow(
156    clippy::exhaustive_structs,
157    reason = "JSON-RPC defines exactly these request members"
158)]
159pub struct RawJsonRpcRequest {
160    /// The ID the response must carry.
161    pub id: RawJsonRpcId,
162    /// The method to invoke.
163    pub method: Arc<str>,
164    /// The params, if any. `None` omits the member.
165    #[serde(default, skip_serializing_if = "Option::is_none")]
166    pub params: Option<RawJsonRpcParams>,
167}
168
169/// A JSON-RPC notification with uninterpreted params.
170///
171/// This is the notification without the `jsonrpc` member, which
172/// [`RawJsonRpcMessage`] adds and checks. Other members of the notification
173/// object are not kept: a relay that parses and re-serializes a notification
174/// drops them.
175#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
176#[allow(
177    clippy::exhaustive_structs,
178    reason = "JSON-RPC defines exactly these notification members"
179)]
180pub struct RawJsonRpcNotification {
181    /// The notification method.
182    pub method: Arc<str>,
183    /// The params, if any. `None` omits the member.
184    #[serde(default, skip_serializing_if = "Option::is_none")]
185    pub params: Option<RawJsonRpcParams>,
186}
187
188impl From<RawJsonRpcRequest> for RawJsonRpcMessage {
189    fn from(request: RawJsonRpcRequest) -> Self {
190        Self::Request(request)
191    }
192}
193
194impl From<RawJsonRpcNotification> for RawJsonRpcMessage {
195    fn from(notification: RawJsonRpcNotification) -> Self {
196        Self::Notification(notification)
197    }
198}
199
200impl From<RawJsonRpcResponse> for RawJsonRpcMessage {
201    fn from(response: RawJsonRpcResponse) -> Self {
202        Self::Response(response)
203    }
204}
205
206/// Raw JSON-RPC request or notification parameters.
207///
208/// JSON-RPC params, when present, must be either an array or an object.
209#[derive(Debug, Clone, PartialEq, Eq)]
210#[allow(
211    clippy::exhaustive_enums,
212    reason = "JSON-RPC params are either an array or an object"
213)]
214pub enum RawJsonRpcParams {
215    /// Positional JSON-RPC params.
216    Array(Vec<serde_json::Value>),
217    /// Named JSON-RPC params.
218    Object(serde_json::Map<String, serde_json::Value>),
219}
220
221impl RawJsonRpcParams {
222    /// Convert a JSON value into JSON-RPC params.
223    pub fn from_value(value: serde_json::Value) -> Result<Option<Self>, crate::Error> {
224        match value {
225            serde_json::Value::Null => Ok(None),
226            serde_json::Value::Array(array) => Ok(Some(Self::Array(array))),
227            serde_json::Value::Object(object) => Ok(Some(Self::Object(object))),
228            _ => {
229                Err(crate::Error::invalid_params()
230                    .data("JSON-RPC params must be an object or array"))
231            }
232        }
233    }
234
235    /// Convert params back into a JSON value.
236    #[must_use]
237    pub fn into_value(self) -> serde_json::Value {
238        match self {
239            Self::Array(array) => serde_json::Value::Array(array),
240            Self::Object(object) => serde_json::Value::Object(object),
241        }
242    }
243}
244
245impl Serialize for RawJsonRpcParams {
246    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
247    where
248        S: serde::Serializer,
249    {
250        match self {
251            Self::Array(array) => array.serialize(serializer),
252            Self::Object(object) => object.serialize(serializer),
253        }
254    }
255}
256
257impl<'de> Deserialize<'de> for RawJsonRpcParams {
258    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
259    where
260        D: serde::Deserializer<'de>,
261    {
262        let value = serde_json::Value::deserialize(deserializer)?;
263        match value {
264            serde_json::Value::Array(array) => Ok(Self::Array(array)),
265            serde_json::Value::Object(object) => Ok(Self::Object(object)),
266            _ => Err(serde::de::Error::custom(
267                "JSON-RPC params must be an object or array",
268            )),
269        }
270    }
271}
272
273impl RawJsonRpcMessage {
274    /// Build a raw JSON-RPC request message.
275    pub fn request(
276        method: String,
277        params: serde_json::Value,
278        id: impl Into<RawJsonRpcId>,
279    ) -> Result<Self, crate::Error> {
280        Ok(Self::Request(RawJsonRpcRequest {
281            id: id.into(),
282            method: Arc::from(method),
283            params: RawJsonRpcParams::from_value(params)?,
284        }))
285    }
286
287    /// Build a raw JSON-RPC notification message.
288    pub fn notification(method: String, params: serde_json::Value) -> Result<Self, crate::Error> {
289        Ok(Self::Notification(RawJsonRpcNotification {
290            method: Arc::from(method),
291            params: RawJsonRpcParams::from_value(params)?,
292        }))
293    }
294
295    /// Build a JSON-RPC response from an ACP result.
296    ///
297    /// For other protocols, construct [`RawJsonRpcResponse`] directly so error
298    /// codes and fields are not interpreted as ACP.
299    #[must_use]
300    pub fn response(
301        id: impl Into<RawJsonRpcId>,
302        response: Result<serde_json::Value, crate::Error>,
303    ) -> Self {
304        Self::Response(RawJsonRpcResponse::new(
305            id,
306            response.map_err(|error| Box::new(error.into())),
307        ))
308    }
309
310    /// The response id, if this is a response.
311    #[must_use]
312    pub fn response_id(&self) -> Option<&RawJsonRpcId> {
313        match self {
314            Self::Response(
315                RawJsonRpcResponse::Result { id, .. } | RawJsonRpcResponse::Error { id, .. },
316            ) => Some(id),
317            Self::Request(_) | Self::Notification(_) => None,
318        }
319    }
320}
321
322impl Serialize for RawJsonRpcMessage {
323    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
324    where
325        S: serde::Serializer,
326    {
327        match self {
328            Self::Request(request) => {
329                VersionedJsonRpcMessage::wrap(request.clone()).serialize(serializer)
330            }
331            Self::Notification(notification) => {
332                VersionedJsonRpcMessage::wrap(notification.clone()).serialize(serializer)
333            }
334            Self::Response(response) => {
335                VersionedJsonRpcMessage::wrap(response.clone()).serialize(serializer)
336            }
337        }
338    }
339}
340
341impl<'de> Deserialize<'de> for RawJsonRpcMessage {
342    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
343    where
344        D: serde::Deserializer<'de>,
345    {
346        let value = serde_json::Value::deserialize(deserializer)?;
347        let Some(object) = value.as_object() else {
348            return Err(serde::de::Error::custom("invalid JSON-RPC message"));
349        };
350
351        let has_method = object.contains_key("method");
352        let has_id = object.contains_key("id");
353        let has_result = object.contains_key("result");
354        let has_error = object.contains_key("error");
355
356        if has_method && !has_result && !has_error {
357            if has_id {
358                let request =
359                    serde_json::from_value::<VersionedJsonRpcMessage<RawJsonRpcRequest>>(value)
360                        .map_err(serde::de::Error::custom)?
361                        .into_inner();
362                Ok(Self::Request(request))
363            } else {
364                let notification = serde_json::from_value::<
365                    VersionedJsonRpcMessage<RawJsonRpcNotification>,
366                >(value)
367                .map_err(serde::de::Error::custom)?
368                .into_inner();
369                Ok(Self::Notification(notification))
370            }
371        } else if !has_method && has_id && has_result != has_error {
372            let response =
373                serde_json::from_value::<VersionedJsonRpcMessage<RawJsonRpcResponse>>(value)
374                    .map_err(serde::de::Error::custom)?
375                    .into_inner();
376            Ok(Self::Response(response))
377        } else {
378            Err(serde::de::Error::custom("invalid JSON-RPC message"))
379        }
380    }
381}
382
383fn params_from_transport(params: Option<RawJsonRpcParams>) -> serde_json::Value {
384    params.map_or(serde_json::Value::Null, RawJsonRpcParams::into_value)
385}
386
387/// Handlers process incoming JSON-RPC messages on a connection.
388///
389/// When messages arrive, they flow through a chain of handlers. Each handler can
390/// either **claim** the message (handle it) or **decline** it (pass to the next handler).
391///
392/// # Message Flow
393///
394/// Messages flow through three layers of handlers in order:
395///
396/// ```text
397/// ┌─────────────────────────────────────────────────────────────────┐
398/// │                     Incoming Message                            │
399/// └─────────────────────────────────────────────────────────────────┘
400///                              │
401///                              ▼
402/// ┌─────────────────────────────────────────────────────────────────┐
403/// │  1. User Handlers (registered via on_receive_request, etc.)     │
404/// │     - Tried in registration order                               │
405/// │     - First handler to return Handled::Yes claims the message   │
406/// └─────────────────────────────────────────────────────────────────┘
407///                              │ Handled::No
408///                              ▼
409/// ┌─────────────────────────────────────────────────────────────────┐
410/// │  2. Dynamic Handlers (added at runtime)                         │
411/// │     - Used for session-specific message handling                │
412/// │     - Added via ConnectionTo::add_dynamic_handler             │
413/// └─────────────────────────────────────────────────────────────────┘
414///                              │ Handled::No
415///                              ▼
416/// ┌─────────────────────────────────────────────────────────────────┐
417/// │  3. Role Default Handler                                        │
418/// │     - Fallback based on the connection's Role                   │
419/// │     - Handles protocol-level messages (e.g., proxy forwarding)  │
420/// └─────────────────────────────────────────────────────────────────┘
421///                              │ Handled::No
422///                              ▼
423/// ┌─────────────────────────────────────────────────────────────────┐
424/// │  Unhandled: requests error, notifications ignored               │
425/// └─────────────────────────────────────────────────────────────────┘
426/// ```
427///
428/// # The `Handled` Return Value
429///
430/// Each handler returns [`Handled`] to indicate whether it processed the message:
431///
432/// - **`Handled::Yes`** - Message was handled. No further handlers are invoked.
433/// - **`Handled::No { message, retry }`** - Message was not handled. The message
434///   (possibly modified) is passed to the next handler in the chain.
435///
436/// For convenience, handlers can return `()` which is equivalent to `Handled::Yes`.
437///
438/// # The Retry Mechanism
439///
440/// The `retry` flag in `Handled::No` controls what happens when no handler claims a message:
441///
442/// - **`retry: false`** (default) - Send a "method not found" error
443///   response immediately for requests, or ignore notifications.
444/// - **`retry: true`** - Queue the message and retry it when new dynamic handlers are added.
445///
446/// This mechanism exists because of a timing issue with sessions: when a `session/new`
447/// response is being processed, the dynamic handler for that session hasn't been registered
448/// yet, but `session/update` notifications for that session may already be arriving.
449/// By setting `retry: true`, these early notifications are queued until the session's
450/// dynamic handler is added.
451///
452/// The queue holds at most 1024 messages per connection. Queuing one more gives up on the
453/// oldest: a request gets the "method not found" error, a notification is dropped with a
454/// log, and a response goes to its awaiter.
455///
456/// On v1 and unguarded connections, a client's role also retries unhandled messages from
457/// the agent that carry a `sessionId`. Its notifications are queued as above. Its requests
458/// are queued only while a dropped dynamic handler's removal is still pending, which covers
459/// a session handler being replaced, and are answered with "method not found" once no such
460/// removal is left. Any other unhandled session request is answered right away, so the
461/// agent never waits for a handler that nobody registers.
462///
463/// # Handler Registration
464///
465/// Most users register handlers using the builder methods on [`Builder`]:
466///
467/// ```
468/// # use agent_client_protocol::{Agent, Client, ConnectTo};
469/// # use agent_client_protocol::v1::schema::{AgentCapabilities, InitializeRequest, InitializeResponse};
470/// # use agent_client_protocol_test::StatusUpdate;
471/// # async fn example(transport: impl ConnectTo<Agent>) -> Result<(), agent_client_protocol::Error> {
472/// Agent.v1()
473///     .on_receive_request(async |req: InitializeRequest, responder, cx| {
474///         responder.respond(
475///             InitializeResponse::new(req.protocol_version)
476///                 .agent_capabilities(AgentCapabilities::new()),
477///         )
478///     }, agent_client_protocol::on_receive_request!())
479///     .on_receive_notification(async |notif: StatusUpdate, cx| {
480///         // Process notification
481///         Ok(())
482///     }, agent_client_protocol::on_receive_notification!())
483///     .connect_to(transport)
484///     .await?;
485/// # Ok(())
486/// # }
487/// ```
488///
489/// The type parameter on the closure determines which messages are dispatched to it.
490/// Messages that don't match the type are automatically passed to the next handler.
491///
492/// # Implementing Custom Handlers
493///
494/// For advanced use cases, you can implement [`HandleDispatchFrom`] directly:
495///
496/// ```no_run
497/// use agent_client_protocol::{
498///     Client, ConnectionTo, Dispatch, Error, HandleDispatchFrom, Handled,
499/// };
500///
501/// struct MyHandler;
502///
503/// impl HandleDispatchFrom<Client> for MyHandler {
504///     async fn handle_dispatch_from(
505///         &mut self,
506///         message: Dispatch,
507///         _connection: ConnectionTo<Client>,
508///     ) -> Result<Handled<Dispatch>, Error> {
509///         if message.method() == "my/custom/method" {
510///             // Handle it
511///             Ok(Handled::Yes)
512///         } else {
513///             // Pass to next handler
514///             Ok(Handled::No { message, retry: false })
515///         }
516///     }
517///
518///     fn describe_chain(&self) -> impl std::fmt::Debug {
519///         "MyHandler"
520///     }
521/// }
522/// ```
523///
524/// # Important: Handlers Must Not Block
525///
526/// The connection processes messages on a single async task. While a handler is running,
527/// no other messages can be processed. For expensive operations, use [`ConnectionTo::spawn`]
528/// to run work concurrently:
529///
530/// ```
531/// # use agent_client_protocol::{Client, Agent, ConnectTo};
532/// # use agent_client_protocol_test::{expensive_operation, ProcessComplete};
533/// # async fn example(transport: impl ConnectTo<Client>) -> Result<(), agent_client_protocol::Error> {
534/// # Client.v1().connect_with(transport, async |cx| {
535/// cx.spawn({
536///     let connection = cx.clone();
537///     async move {
538///         let result = expensive_operation("data").await?;
539///         connection.send_notification(ProcessComplete { result })?;
540///         Ok(())
541///     }
542/// })?;
543/// # Ok(())
544/// # }).await?;
545/// # Ok(())
546/// # }
547/// ```
548#[allow(async_fn_in_trait)]
549/// A handler for incoming JSON-RPC messages.
550///
551/// This trait is implemented by types that can process incoming messages on a connection.
552/// Handlers are registered with a [`Builder`] and are called in order until
553/// one claims the message.
554///
555/// The type parameter is the counterpart role that messages arrive from and
556/// that the supplied [`ConnectionTo`] addresses. An agent handler therefore
557/// implements `HandleDispatchFrom<Client>`, while a client handler implements
558/// `HandleDispatchFrom<Agent>`.
559pub trait HandleDispatchFrom<Counterpart: Role>: Send {
560    /// Attempt to claim an incoming dispatch (request, notification, or response).
561    ///
562    /// # Important: do not block
563    ///
564    /// The server will not process new messages until this handler returns.
565    /// You should avoid blocking in this callback unless you wish to block the server (e.g., for rate limiting).
566    /// The recommended approach to manage expensive operations is to the [`ConnectionTo::spawn`] method available on the message context.
567    ///
568    /// # Parameters
569    ///
570    /// * `message` - The incoming message to handle.
571    /// * `connection` - The connection, used to send messages and access connection state.
572    ///
573    /// # Returns
574    ///
575    /// * `Ok(Handled::Yes)` if the message was claimed. It will not be propagated further.
576    /// * `Ok(Handled::No(message))` if not; the (possibly changed) message will be passed to the remaining handlers.
577    /// * `Err` if processing fails. Requests receive an Error Response, response
578    ///   errors are routed to the local request awaiter, and notification errors
579    ///   are logged without a wire reply.
580    fn handle_dispatch_from(
581        &mut self,
582        message: Dispatch,
583        connection: ConnectionTo<Counterpart>,
584    ) -> impl Future<Output = Result<Handled<Dispatch>, crate::Error>> + Send;
585
586    /// Returns a debug description of the registered handlers for diagnostics.
587    fn describe_chain(&self) -> impl std::fmt::Debug;
588}
589
590impl<Counterpart: Role, H> HandleDispatchFrom<Counterpart> for &mut H
591where
592    H: HandleDispatchFrom<Counterpart>,
593{
594    fn handle_dispatch_from(
595        &mut self,
596        message: Dispatch,
597        cx: ConnectionTo<Counterpart>,
598    ) -> impl Future<Output = Result<Handled<Dispatch>, crate::Error>> + Send {
599        H::handle_dispatch_from(self, message, cx)
600    }
601
602    fn describe_chain(&self) -> impl std::fmt::Debug {
603        H::describe_chain(self)
604    }
605}
606
607/// A JSON-RPC connection that can act as either a server, client, or both.
608///
609/// [`Builder`] provides a builder-style API for creating JSON-RPC servers and clients.
610/// You start with a versioned entry point such as `Client.v1()` or `Client.v2()`, then add message
611/// handlers, and finally drive the connection with either [`connect_to`](Builder::connect_to)
612/// or [`connect_with`](Builder::connect_with), providing a component implementation
613/// (e.g., [`ByteStreams`] for byte streams).
614///
615/// # JSON-RPC Primer
616///
617/// JSON-RPC 2.0 has two fundamental message types:
618///
619/// * **Requests** - Messages that expect a response. They have an `id` field that gets
620///   echoed back in the response so the sender can correlate them.
621/// * **Notifications** - Fire-and-forget messages with no `id` field. The sender doesn't
622///   expect or receive a response.
623///
624/// # Type-Driven Message Dispatch
625///
626/// The handler registration methods use Rust's type system to determine which messages
627/// to handle. The type parameter you provide controls what gets dispatched to your handler:
628///
629/// ## Single Message Types
630///
631/// The simplest case - handle one specific message type:
632///
633/// ```no_run
634/// # use agent_client_protocol_test::*;
635/// # use agent_client_protocol::v1::schema::{InitializeRequest, InitializeResponse, SessionNotification};
636/// # async fn example() -> Result<(), agent_client_protocol::Error> {
637/// # let connection = mock_connection();
638/// connection
639///     .on_receive_request(async |req: InitializeRequest, responder, cx| {
640///         // Handle only InitializeRequest messages
641///         responder.respond(InitializeResponse::make())
642///     }, agent_client_protocol::on_receive_request!())
643///     .on_receive_notification(async |notif: SessionNotification, cx| {
644///         // Handle only SessionUpdate notifications
645///         Ok(())
646///     }, agent_client_protocol::on_receive_notification!())
647/// # .connect_to(agent_client_protocol_test::MockTransport).await?;
648/// # Ok(())
649/// # }
650/// ```
651///
652/// ## Enum Message Types
653///
654/// You can also handle multiple related messages with a single handler by defining an enum
655/// that implements the appropriate trait ([`JsonRpcRequest`] or [`JsonRpcNotification`]):
656///
657/// ```no_run
658/// # use agent_client_protocol_test::*;
659/// # use agent_client_protocol::{JsonRpcRequest, JsonRpcMessage, UntypedMessage};
660/// # use agent_client_protocol::v1::schema::{InitializeRequest, InitializeResponse, PromptRequest, PromptResponse};
661/// # async fn example() -> Result<(), agent_client_protocol::Error> {
662/// # let connection = mock_connection();
663/// // Define an enum for multiple request types
664/// #[derive(Debug, Clone)]
665/// enum MyRequests {
666///     Initialize(InitializeRequest),
667///     Prompt(PromptRequest),
668/// }
669///
670/// // Implement JsonRpcRequest for your enum
671/// # impl JsonRpcMessage for MyRequests {
672/// #     fn matches_method(_method: &str) -> bool { false }
673/// #     fn method(&self) -> &str { "myRequests" }
674/// #     fn to_untyped_message(&self) -> Result<UntypedMessage, agent_client_protocol::Error> { todo!() }
675/// #     fn parse_message(_method: &str, _params: &serde_json::Value) -> Result<Self, agent_client_protocol::Error> { Err(agent_client_protocol::Error::method_not_found()) }
676/// # }
677/// impl JsonRpcRequest for MyRequests { type Response = serde_json::Value; }
678///
679/// // Handle all variants in one place
680/// connection.on_receive_request(async |req: MyRequests, responder, cx| {
681///     match req {
682///         MyRequests::Initialize(init) => { responder.respond(serde_json::json!({})) }
683///         MyRequests::Prompt(prompt) => { responder.respond(serde_json::json!({})) }
684///     }
685/// }, agent_client_protocol::on_receive_request!())
686/// # .connect_to(agent_client_protocol_test::MockTransport).await?;
687/// # Ok(())
688/// # }
689/// ```
690///
691/// ## Mixed Message Types
692///
693/// To handle requests, notifications, and responses in one callback, use
694/// [`on_receive_dispatch`](Self::on_receive_dispatch):
695///
696/// ```no_run
697/// # use agent_client_protocol_test::*;
698/// # use agent_client_protocol::v1::Dispatch;
699/// # use agent_client_protocol::v1::schema::{InitializeRequest, InitializeResponse, SessionNotification};
700/// # async fn example() -> Result<(), agent_client_protocol::Error> {
701/// # let connection = mock_connection();
702/// // on_receive_dispatch receives requests, notifications, and responses
703/// connection.on_receive_dispatch(async |msg: Dispatch<InitializeRequest, SessionNotification>, _cx| {
704///     match msg {
705///         Dispatch::Request(req, responder) => {
706///             responder.respond(InitializeResponse::make())
707///         }
708///         Dispatch::Notification(notif) => {
709///             Ok(())
710///         }
711///         Dispatch::Response(result, router) => {
712///             // Forward response to its destination
713///             router.route_with_result(result)
714///         }
715///     }
716/// }, agent_client_protocol::on_receive_dispatch!())
717/// # .connect_to(agent_client_protocol_test::MockTransport).await?;
718/// # Ok(())
719/// # }
720/// ```
721///
722/// # Handler Registration
723///
724/// Register handlers using these methods (listed from most common to most flexible):
725///
726/// * [`on_receive_request`](Self::on_receive_request) - Handle JSON-RPC requests (messages expecting responses)
727/// * [`on_receive_notification`](Self::on_receive_notification) - Handle JSON-RPC notifications (fire-and-forget)
728/// * [`on_receive_dispatch`](Self::on_receive_dispatch) - Handle requests, notifications, and responses in one callback
729/// * [`with_handler`](Self::with_handler) - Low-level primitive for maximum flexibility
730///
731/// ## Handler Ordering
732///
733/// Handlers are tried in the order you register them. The first handler that claims a message
734/// (by matching its type) will process it. Subsequent handlers won't see that message:
735///
736/// ```no_run
737/// # use agent_client_protocol_test::*;
738/// # use agent_client_protocol::v1::schema::{InitializeRequest, InitializeResponse, PromptRequest, PromptResponse};
739/// # async fn example() -> Result<(), agent_client_protocol::Error> {
740/// # let connection = mock_connection();
741/// connection
742///     .on_receive_request(async |req: InitializeRequest, responder, cx| {
743///         // This runs first for InitializeRequest
744///         responder.respond(InitializeResponse::make())
745///     }, agent_client_protocol::on_receive_request!())
746///     .on_receive_request(async |req: PromptRequest, responder, cx| {
747///         // This runs first for PromptRequest
748///         responder.respond(PromptResponse::make())
749///     }, agent_client_protocol::on_receive_request!())
750///     // Unknown requests receive Method not found automatically; unhandled
751///     // notifications are ignored.
752/// # .connect_to(agent_client_protocol_test::MockTransport).await?;
753/// # Ok(())
754/// # }
755/// ```
756///
757/// # Event Loop and Concurrency
758///
759/// Understanding the event loop is critical for writing correct handlers.
760///
761/// ## The Event Loop
762///
763/// [`Builder`] runs all handler callbacks on a single async task - the event loop.
764/// While a handler is running, **the server cannot receive new messages**. This means
765/// any blocking or expensive work in your handlers will stall the entire connection.
766///
767/// To avoid blocking the event loop, use [`ConnectionTo::spawn`] to offload serious
768/// work to concurrent tasks:
769///
770/// ```no_run
771/// # use agent_client_protocol_test::*;
772/// # async fn example() -> Result<(), agent_client_protocol::Error> {
773/// # let connection = mock_connection();
774/// connection.on_receive_request(async |req: AnalyzeRequest, responder, cx| {
775///     // Clone cx for the spawned task
776///     cx.spawn({
777///         let connection = cx.clone();
778///         async move {
779///             let result = expensive_analysis(&req.data).await?;
780///             connection.send_notification(AnalysisComplete { result })?;
781///             Ok(())
782///         }
783///     })?;
784///
785///     // Respond immediately without blocking
786///     responder.respond(AnalysisStarted { job_id: 42 })
787/// }, agent_client_protocol::on_receive_request!())
788/// # .connect_to(agent_client_protocol_test::MockTransport).await?;
789/// # Ok(())
790/// # }
791/// ```
792///
793/// Note that the entire connection runs within one async task, so parallelism must be
794/// managed explicitly using [`spawn`](ConnectionTo::spawn).
795///
796/// ## The Connection Context
797///
798/// Handler callbacks receive a context object (`cx`) for interacting with the connection:
799///
800/// * **For request handlers** - [`Responder<R>`] provides [`respond`](Responder::respond)
801///   to send the response, plus methods to send other messages
802/// * **For notification handlers** - [`ConnectionTo`] provides methods to send messages
803///   and spawn tasks
804///
805/// Both context types support:
806/// * [`send_request`](ConnectionTo::send_request) - Send requests to the other side
807/// * [`send_notification`](ConnectionTo::send_notification) - Send notifications
808/// * [`spawn`](ConnectionTo::spawn) - Run tasks concurrently without blocking the event loop
809///
810/// The [`SentRequest`] returned by `send_request` provides methods like
811/// [`on_receiving_result`](SentRequest::on_receiving_result) that help you
812/// avoid accidentally blocking the event loop while waiting for responses.
813///
814/// # Driving the Connection
815///
816/// After adding handlers, you must drive the connection using one of two modes:
817///
818/// ## Server Mode: `connect_to()`
819///
820/// Use [`connect_to`](Self::connect_to) when you only need to respond to incoming messages:
821///
822/// ```no_run
823/// # use agent_client_protocol_test::*;
824/// # async fn example() -> Result<(), agent_client_protocol::Error> {
825/// # let connection = mock_connection();
826/// connection
827///     .on_receive_request(async |req: MyRequest, responder, cx| {
828///         responder.respond(MyResponse { status: "ok".into() })
829///     }, agent_client_protocol::on_receive_request!())
830///     .connect_to(MockTransport)  // Runs until connection closes or error occurs
831///     .await?;
832/// # Ok(())
833/// # }
834/// ```
835///
836/// The connection will process incoming messages and invoke your handlers until the
837/// connection is closed or an error occurs.
838///
839/// ## Client Mode: `connect_with()`
840///
841/// Use [`connect_with`](Self::connect_with) when you need to both handle incoming messages
842/// AND send your own requests/notifications:
843///
844/// ```no_run
845/// # use agent_client_protocol_test::*;
846/// # use agent_client_protocol::v1::schema::InitializeRequest;
847/// # async fn example() -> Result<(), agent_client_protocol::Error> {
848/// # let connection = mock_connection();
849/// connection
850///     .on_receive_request(async |req: MyRequest, responder, cx| {
851///         responder.respond(MyResponse { status: "ok".into() })
852///     }, agent_client_protocol::on_receive_request!())
853///     .connect_with(MockTransport, async |cx| {
854///         // You can send requests to the other side
855///         let response = cx.send_request(InitializeRequest::make())
856///             .block_task()
857///             .await?;
858///
859///         // And send notifications
860///         cx.send_notification(StatusUpdate { message: "ready".into() })?;
861///
862///         Ok(())
863///     })
864///     .await?;
865/// # Ok(())
866/// # }
867/// ```
868///
869/// The connection will serve incoming messages in the background while your client closure
870/// runs. When the closure returns, the connection shuts down.
871///
872/// # Example: Complete Agent
873///
874/// ```no_run
875/// # use agent_client_protocol::UntypedRole;
876/// # use agent_client_protocol::{Builder};
877/// # use agent_client_protocol::v1::schema::{InitializeRequest, InitializeResponse, PromptRequest, PromptResponse, SessionNotification};
878/// # async fn example(transport: impl agent_client_protocol::ConnectTo<UntypedRole>) -> Result<(), agent_client_protocol::Error> {
879///
880/// UntypedRole.builder()
881///     .name("my-agent")  // Optional: for debugging logs
882///     .on_receive_request(async |init: InitializeRequest, responder, cx| {
883///         let response: InitializeResponse = todo!();
884///         responder.respond(response)
885///     }, agent_client_protocol::on_receive_request!())
886///     .on_receive_request(async |prompt: PromptRequest, responder, cx| {
887///         // You can send notifications while processing a request
888///         let notif: SessionNotification = todo!();
889///         cx.send_notification(notif)?;
890///
891///         // Then respond to the request
892///         let response: PromptResponse = todo!();
893///         responder.respond(response)
894///     }, agent_client_protocol::on_receive_request!())
895///     .connect_to(transport)
896///     .await?;
897/// # Ok(())
898/// # }
899/// ```
900///
901/// # Protocol version
902///
903/// `P` is the [`Protocol`] marker of the request handles that typed handlers
904/// receive and of the connection type callbacks receive. `Client.v1()`,
905/// `Agent.v1()` and `Proxy.v1()` return [`V1`] builders
906/// ([`v1::Builder`](crate::v1::Builder)), the v2 builders use `V2`
907/// (`v2::Builder`), and [`Builder::new`] and other roles' builders use the
908/// version-neutral default, [`Raw`], with no protocol-version guard.
909#[must_use]
910#[derive(Debug)]
911pub struct Builder<Host: Role, Handler = NullHandler, Runner = NullRun, Close = NullClose, P = Raw>
912where
913    Handler: HandleDispatchFrom<Host::Counterpart>,
914    Runner: RunWithConnectionTo<Host::Counterpart>,
915    Close: HandleConnectionClose<Host::Counterpart>,
916    P: Protocol,
917{
918    /// My role.
919    host: Host,
920
921    /// Name of the connection, used in tracing logs.
922    name: Option<String>,
923
924    /// Handler for incoming messages.
925    handler: Handler,
926
927    /// Runner for background connection tasks.
928    runner: Runner,
929
930    /// Protocol version mode for the public API and wire compatibility layer.
931    protocol_mode: ProtocolMode,
932
933    /// Handler run when the incoming transport reaches clean EOF.
934    on_close: Close,
935
936    /// The protocol version of the callbacks: their connection type and the
937    /// request handles they receive.
938    protocol: PhantomData<fn() -> P>,
939}
940
941impl<Host: Role> Builder<Host, NullHandler, NullRun, NullClose> {
942    /// Create a new version-neutral connection builder for the given role.
943    /// This type follows a builder pattern; use other methods to configure and then invoke
944    /// [`Self::connect_to`] (to use as a server) or [`Self::connect_with`] to use as a client.
945    ///
946    /// The builder is raw: it applies no ACP protocol-version guard, even for
947    /// [`Client`](crate::Client), [`Agent`] and [`Proxy`](crate::Proxy), and
948    /// its callbacks receive [`Raw`] request handles. Messages are sent and received exactly as
949    /// handlers produce them. This suits protocol-routing infrastructure that
950    /// validates `initialize` itself and forwarders such as the conductor,
951    /// which leave version validation to the endpoints.
952    ///
953    /// Applications should use [`Client.v1()`](crate::Client::v1),
954    /// [`Agent.v1()`](crate::Agent::v1) or [`Proxy.v1()`](crate::Proxy::v1)
955    /// (or the `v2()` entry points with the `unstable_protocol_v2` feature),
956    /// which apply that version's wire guard.
957    pub fn new(role: Host) -> Self {
958        Self {
959            host: role,
960            name: None,
961            handler: NullHandler,
962            runner: NullRun,
963            protocol_mode: ProtocolMode::disabled(),
964            on_close: NullClose,
965            protocol: PhantomData,
966        }
967    }
968}
969
970impl<Host: Role, Handler> Builder<Host, Handler, NullRun, NullClose>
971where
972    Handler: HandleDispatchFrom<Host::Counterpart>,
973{
974    /// Create a new connection builder with the given handler.
975    ///
976    /// Like [`Builder::new`], the builder applies no protocol-version guard.
977    pub fn new_with(role: Host, handler: Handler) -> Self {
978        Self {
979            host: role,
980            name: None,
981            handler,
982            runner: NullRun,
983            protocol_mode: ProtocolMode::disabled(),
984            on_close: NullClose,
985            protocol: PhantomData,
986        }
987    }
988}
989
990impl<
991    Host: Role,
992    Handler: HandleDispatchFrom<Host::Counterpart>,
993    Runner: RunWithConnectionTo<Host::Counterpart>,
994    Close: HandleConnectionClose<Host::Counterpart>,
995    P: Protocol,
996> Builder<Host, Handler, Runner, Close, P>
997{
998    /// Set the "name" of this connection -- used only for debugging logs.
999    pub fn name(mut self, name: impl ToString) -> Self {
1000        self.name = Some(name.to_string());
1001        self
1002    }
1003
1004    /// The same builder with callbacks for protocol `Q`. Handlers already
1005    /// registered keep their own protocol.
1006    pub(crate) fn into_protocol<Q: Protocol>(self) -> Builder<Host, Handler, Runner, Close, Q> {
1007        Builder {
1008            host: self.host,
1009            name: self.name,
1010            handler: self.handler,
1011            runner: self.runner,
1012            protocol_mode: self.protocol_mode,
1013            on_close: self.on_close,
1014            protocol: PhantomData,
1015        }
1016    }
1017
1018    #[cfg(feature = "unstable_protocol_v2")]
1019    pub(crate) fn v2_agent(self) -> Builder<Host, Handler, Runner, Close, V2> {
1020        let mut builder = self.into_protocol();
1021        builder.protocol_mode = ProtocolMode::v2_agent();
1022        builder
1023    }
1024
1025    #[cfg(feature = "unstable_protocol_v2")]
1026    pub(crate) fn v2_client(self) -> Builder<Host, Handler, Runner, Close, V2> {
1027        let mut builder = self.into_protocol();
1028        builder.protocol_mode = ProtocolMode::v2_client();
1029        builder
1030    }
1031
1032    #[cfg(feature = "unstable_protocol_v2")]
1033    pub(crate) fn v2_proxy(self) -> Builder<Host, Handler, Runner, Close, V2> {
1034        let mut builder = self.into_protocol();
1035        builder.protocol_mode = ProtocolMode::v2_proxy();
1036        builder
1037    }
1038
1039    pub(crate) fn v1_agent(self) -> Builder<Host, Handler, Runner, Close, V1> {
1040        let mut builder = self.into_protocol();
1041        builder.protocol_mode = ProtocolMode::v1_agent();
1042        builder
1043    }
1044
1045    pub(crate) fn v1_client(self) -> Builder<Host, Handler, Runner, Close, V1> {
1046        let mut builder = self.into_protocol();
1047        builder.protocol_mode = ProtocolMode::v1_client();
1048        builder
1049    }
1050
1051    pub(crate) fn v1_proxy(self) -> Builder<Host, Handler, Runner, Close, V1> {
1052        let mut builder = self.into_protocol();
1053        builder.protocol_mode = ProtocolMode::v1_proxy();
1054        builder
1055    }
1056
1057    /// Record a request handler of type `Req`.
1058    ///
1059    /// A v1 agent that handles `initialize` itself rejects other requests
1060    /// until initialization completes, as v1 agents SHOULD. Agents without
1061    /// such a handler, including those with only catch-all handlers, keep
1062    /// accepting requests without initialization, because they could not
1063    /// complete one.
1064    fn note_request_handler<Req: JsonRpcRequest>(mut self) -> Self {
1065        // A handler for every method is a catch-all, not an initialize handler.
1066        const UNRELATED_METHOD: &str = "\0acp-sdk/not-a-method";
1067        if TypeId::of::<Host>() == TypeId::of::<Agent>()
1068            && Req::matches_method("initialize")
1069            && !Req::matches_method(UNRELATED_METHOD)
1070        {
1071            self.protocol_mode = self.protocol_mode.require_initialize();
1072        }
1073        self
1074    }
1075
1076    /// Merge another [`Builder`] into this one.
1077    ///
1078    /// Prefer [`Self::on_receive_request`] or [`Self::on_receive_notification`].
1079    /// This is a low-level method that is not intended for general use.
1080    pub fn with_connection_builder(
1081        self,
1082        other: Builder<
1083            Host,
1084            impl HandleDispatchFrom<Host::Counterpart>,
1085            impl RunWithConnectionTo<Host::Counterpart>,
1086            impl HandleConnectionClose<Host::Counterpart>,
1087            P,
1088        >,
1089    ) -> Builder<
1090        Host,
1091        impl HandleDispatchFrom<Host::Counterpart>,
1092        impl RunWithConnectionTo<Host::Counterpart>,
1093        impl HandleConnectionClose<Host::Counterpart>,
1094        P,
1095    > {
1096        let Builder {
1097            name: other_name,
1098            handler: other_handler,
1099            runner: other_runner,
1100            protocol_mode: other_protocol_mode,
1101            on_close: other_on_close,
1102            protocol: _,
1103            host: _,
1104        } = other;
1105        Builder {
1106            host: self.host,
1107            name: self.name,
1108            handler: ChainedHandler::new(
1109                self.handler,
1110                NamedHandler::new(other_name, other_handler),
1111            ),
1112            runner: ChainRun::new(self.runner, other_runner),
1113            protocol_mode: self.protocol_mode.merge(other_protocol_mode),
1114            on_close: ChainedClose::new(self.on_close, other_on_close),
1115            protocol: PhantomData,
1116        }
1117    }
1118
1119    /// Add a new [`HandleDispatchFrom`] to the chain.
1120    ///
1121    /// Prefer [`Self::on_receive_request`] or [`Self::on_receive_notification`].
1122    /// This is a low-level method that is not intended for general use.
1123    pub fn with_handler(
1124        self,
1125        handler: impl HandleDispatchFrom<Host::Counterpart>,
1126    ) -> Builder<Host, impl HandleDispatchFrom<Host::Counterpart>, Runner, Close, P> {
1127        Builder {
1128            host: self.host,
1129            name: self.name,
1130            handler: ChainedHandler::new(self.handler, handler),
1131            runner: self.runner,
1132            protocol_mode: self.protocol_mode,
1133            on_close: self.on_close,
1134            protocol: PhantomData,
1135        }
1136    }
1137
1138    /// Add a new [`RunWithConnectionTo`] to the chain.
1139    pub fn with_runner<Run1>(
1140        self,
1141        runner: Run1,
1142    ) -> Builder<Host, Handler, impl RunWithConnectionTo<Host::Counterpart>, Close, P>
1143    where
1144        Run1: RunWithConnectionTo<Host::Counterpart>,
1145    {
1146        Builder {
1147            host: self.host,
1148            name: self.name,
1149            handler: self.handler,
1150            runner: ChainRun::new(self.runner, runner),
1151            protocol_mode: self.protocol_mode,
1152            on_close: self.on_close,
1153            protocol: PhantomData,
1154        }
1155    }
1156
1157    /// Enqueue a task to run once the connection is actively serving traffic.
1158    #[track_caller]
1159    pub fn with_spawned<F, Fut>(
1160        self,
1161        task: F,
1162    ) -> Builder<Host, Handler, impl RunWithConnectionTo<Host::Counterpart>, Close, P>
1163    where
1164        F: FnOnce(P::Connection<Host::Counterpart>) -> Fut + Send,
1165        Fut: Future<Output = Result<(), crate::Error>> + Send,
1166    {
1167        let location = Location::caller();
1168        // Boxed for the same reason as `main_fn` in `connect_with`: the driver
1169        // would otherwise store the task's captured state once per layer.
1170        self.with_runner(SpawnedRun::<_, P>::new(location, Box::new(task)))
1171    }
1172
1173    /// Run a callback when the incoming transport reaches clean EOF.
1174    ///
1175    /// Each callback runs at most once and receives the connection context. A
1176    /// successful callback observes the close without otherwise changing the
1177    /// lifetime of [`connect_with`](Self::connect_with). Returning an error
1178    /// shuts down the connection and cancels a still-running `connect_with`
1179    /// future.
1180    ///
1181    /// Multiple callbacks run sequentially in registration order. All of them
1182    /// run even if an earlier callback fails, after which the first error is
1183    /// returned. Pending requests are failed before callbacks begin, while the
1184    /// selected connection context's `incoming_closed` future completes only
1185    /// after they finish. A callback must therefore not await that close
1186    /// future itself.
1187    ///
1188    /// This separation lets applications choose their cancellation policy. A
1189    /// callback can notify application-owned tasks and return `Ok(())` for
1190    /// graceful cleanup, or return an error to stop them immediately.
1191    ///
1192    /// Close callbacks do not run for transport or handler errors, foreground
1193    /// completion, or a dropped driver. Use [`ConnectionTo::terminated`] to
1194    /// observe every way the connection can end.
1195    ///
1196    /// ```
1197    /// # use agent_client_protocol::{Client, ConnectTo, Error};
1198    /// # async fn example(transport: impl ConnectTo<Client>) -> Result<(), Error> {
1199    /// Client.v1()
1200    ///     .on_close(async |_cx| {
1201    ///         Err(Error::internal_error().data("agent transport closed"))
1202    ///     })
1203    ///     .connect_with(transport, async |_cx| {
1204    ///         std::future::pending().await
1205    ///     })
1206    ///     .await?;
1207    /// # Ok(())
1208    /// # }
1209    /// ```
1210    pub fn on_close<F, Fut>(
1211        self,
1212        callback: F,
1213    ) -> Builder<Host, Handler, Runner, impl HandleConnectionClose<Host::Counterpart>, P>
1214    where
1215        F: FnOnce(P::Connection<Host::Counterpart>) -> Fut + Send,
1216        Fut: Future<Output = Result<(), crate::Error>> + Send,
1217    {
1218        Builder {
1219            host: self.host,
1220            name: self.name,
1221            handler: self.handler,
1222            runner: self.runner,
1223            protocol_mode: self.protocol_mode,
1224            on_close: ChainedClose::new(self.on_close, CloseCallback::<_, P>::new(callback)),
1225            protocol: PhantomData,
1226        }
1227    }
1228
1229    /// Register a handler for requests, notifications, and responses.
1230    ///
1231    /// Use this when you want to handle all JSON-RPC message kinds in one callback.
1232    /// Your handler receives a [`Dispatch<Req, Notif>`] with three variants:
1233    ///
1234    /// - `Dispatch::Request(request, responder)` - A request with its response context
1235    /// - `Dispatch::Notification(notification)` - A notification
1236    /// - `Dispatch::Response(result, router)` - A response to a request we sent
1237    ///
1238    /// # Example
1239    ///
1240    /// ```no_run
1241    /// # use agent_client_protocol_test::*;
1242    /// # use agent_client_protocol::v1::Dispatch;
1243    /// # async fn example() -> Result<(), agent_client_protocol::Error> {
1244    /// # let connection = mock_connection();
1245    /// connection.on_receive_dispatch(async |message: Dispatch<MyRequest, StatusUpdate>, _cx| {
1246    ///     match message {
1247    ///         Dispatch::Request(req, responder) => {
1248    ///             // Handle request and send response
1249    ///             responder.respond(MyResponse { status: "ok".into() })
1250    ///         }
1251    ///         Dispatch::Notification(notif) => {
1252    ///             // Handle notification (no response needed)
1253    ///             Ok(())
1254    ///         }
1255    ///         Dispatch::Response(result, router) => {
1256    ///             // Forward response to its destination
1257    ///             router.route_with_result(result)
1258    ///         }
1259    ///     }
1260    /// }, agent_client_protocol::on_receive_dispatch!())
1261    /// # .connect_to(agent_client_protocol_test::MockTransport).await?;
1262    /// # Ok(())
1263    /// # }
1264    /// ```
1265    ///
1266    /// For most use cases, prefer [`on_receive_request`](Self::on_receive_request) or
1267    /// [`on_receive_notification`](Self::on_receive_notification) which provide cleaner APIs
1268    /// for handling requests or notifications separately.
1269    ///
1270    /// # Ordering
1271    ///
1272    /// This callback runs inside the dispatch loop and blocks further message processing
1273    /// until it completes. See the [`ordering`](crate::concepts::ordering) module for details on
1274    /// ordering guarantees and how to avoid deadlocks.
1275    pub fn on_receive_dispatch<Req, Notif, F, T, ToFut>(
1276        self,
1277        op: F,
1278        to_future_hack: ToFut,
1279    ) -> Builder<Host, impl HandleDispatchFrom<Host::Counterpart>, Runner, Close, P>
1280    where
1281        Host::Counterpart: HasPeer<Host::Counterpart>,
1282        Req: JsonRpcRequest,
1283        Notif: JsonRpcNotification,
1284        F: AsyncFnMut(
1285                Dispatch<Req, Notif, P>,
1286                P::Connection<Host::Counterpart>,
1287            ) -> Result<T, crate::Error>
1288            + Send,
1289        T: IntoHandled<Dispatch<Req, Notif, P>>,
1290        ToFut: Fn(
1291                &mut F,
1292                Dispatch<Req, Notif, P>,
1293                P::Connection<Host::Counterpart>,
1294            ) -> crate::BoxFuture<'_, Result<T, crate::Error>>
1295            + Send
1296            + Sync,
1297    {
1298        let handler = MessageHandler::<_, _, P, _, _, _, _>::new(
1299            self.host.counterpart(),
1300            self.host.counterpart(),
1301            op,
1302            to_future_hack,
1303        );
1304        self.note_request_handler::<Req>().with_handler(handler)
1305    }
1306
1307    /// Register a handler for JSON-RPC requests of type `Req`.
1308    ///
1309    /// Your handler receives three arguments:
1310    /// 1. The request (type `Req`)
1311    /// 2. A [`Responder<Req::Response, P>`] for sending the response
1312    /// 3. The builder-selected connection context for the peer that sent the
1313    ///    request (`ConnectionTo` by default, or `v2::ConnectionTo` for a
1314    ///    `v2::Builder`)
1315    ///
1316    /// The request context allows you to:
1317    /// - Send the response with [`Responder::respond`]
1318    /// - Send notifications to the client with the context's
1319    ///   `send_notification` method
1320    /// - Send requests to the client with the context's `send_request` method
1321    ///
1322    /// # Example
1323    ///
1324    /// ```no_run
1325    /// # use agent_client_protocol::{Agent, ConnectTo};
1326    /// # use agent_client_protocol::v1::schema::{PromptRequest, PromptResponse, SessionNotification};
1327    /// # async fn example(transport: impl ConnectTo<Agent>) -> Result<(), agent_client_protocol::Error> {
1328    /// Agent.v1().on_receive_request(async |request: PromptRequest, responder, cx| {
1329    ///     // Send a notification while processing
1330    ///     let notif: SessionNotification = todo!();
1331    ///     cx.send_notification(notif)?;
1332    ///
1333    ///     // Send the response
1334    ///     let response: PromptResponse = todo!();
1335    ///     responder.respond(response)
1336    /// }, agent_client_protocol::on_receive_request!())
1337    /// .connect_to(transport)
1338    /// .await
1339    /// # }
1340    /// ```
1341    ///
1342    /// # Type Parameter
1343    ///
1344    /// `Req` can be either a single request type or an enum of multiple request types.
1345    /// See the [type-driven dispatch](Self#type-driven-message-dispatch) section for details.
1346    ///
1347    /// # Ordering
1348    ///
1349    /// This callback runs inside the dispatch loop and blocks further message processing
1350    /// until it completes. See the [`ordering`](crate::concepts::ordering) module for details on
1351    /// ordering guarantees and how to avoid deadlocks.
1352    pub fn on_receive_request<Req: JsonRpcRequest, F, T, ToFut>(
1353        self,
1354        op: F,
1355        to_future_hack: ToFut,
1356    ) -> Builder<Host, impl HandleDispatchFrom<Host::Counterpart>, Runner, Close, P>
1357    where
1358        Host::Counterpart: HasPeer<Host::Counterpart>,
1359        F: AsyncFnMut(
1360                Req,
1361                Responder<Req::Response, P>,
1362                P::Connection<Host::Counterpart>,
1363            ) -> Result<T, crate::Error>
1364            + Send,
1365        T: IntoHandled<(Req, Responder<Req::Response, P>)>,
1366        ToFut: Fn(
1367                &mut F,
1368                Req,
1369                Responder<Req::Response, P>,
1370                P::Connection<Host::Counterpart>,
1371            ) -> crate::BoxFuture<'_, Result<T, crate::Error>>
1372            + Send
1373            + Sync,
1374    {
1375        let handler = RequestHandler::<_, _, P, _, _, _>::new(
1376            self.host.counterpart(),
1377            self.host.counterpart(),
1378            op,
1379            to_future_hack,
1380        );
1381        self.note_request_handler::<Req>().with_handler(handler)
1382    }
1383
1384    /// Register a handler for JSON-RPC notifications of type `Notif`.
1385    ///
1386    /// Notifications are fire-and-forget messages that don't expect a response.
1387    /// Your handler receives:
1388    /// 1. The notification (type `Notif`)
1389    /// 2. The builder-selected connection context for sending messages to the
1390    ///    other side
1391    ///
1392    /// Unlike request handlers, you cannot send a response (notifications don't have IDs),
1393    /// but you can still send your own requests and notifications using the context.
1394    ///
1395    /// # Example
1396    ///
1397    /// ```no_run
1398    /// # use agent_client_protocol_test::*;
1399    /// # async fn example() -> Result<(), agent_client_protocol::Error> {
1400    /// # let connection = mock_connection();
1401    /// connection.on_receive_notification(async |notif: SessionUpdate, cx| {
1402    ///     // Process the notification
1403    ///     update_session_state(&notif)?;
1404    ///
1405    ///     // Optionally send a notification back
1406    ///     cx.send_notification(StatusUpdate {
1407    ///         message: "Acknowledged".into(),
1408    ///     })?;
1409    ///
1410    ///     Ok(())
1411    /// }, agent_client_protocol::on_receive_notification!())
1412    /// # .connect_to(agent_client_protocol_test::MockTransport).await?;
1413    /// # Ok(())
1414    /// # }
1415    /// ```
1416    ///
1417    /// # Type Parameter
1418    ///
1419    /// `Notif` can be either a single notification type or an enum of multiple notification types.
1420    /// See the [type-driven dispatch](Self#type-driven-message-dispatch) section for details.
1421    ///
1422    /// # Ordering
1423    ///
1424    /// This callback runs inside the dispatch loop and blocks further message processing
1425    /// until it completes. See the [`ordering`](crate::concepts::ordering) module for details on
1426    /// ordering guarantees and how to avoid deadlocks.
1427    pub fn on_receive_notification<Notif, F, T, ToFut>(
1428        self,
1429        op: F,
1430        to_future_hack: ToFut,
1431    ) -> Builder<Host, impl HandleDispatchFrom<Host::Counterpart>, Runner, Close, P>
1432    where
1433        Host::Counterpart: HasPeer<Host::Counterpart>,
1434        Notif: JsonRpcNotification,
1435        F: AsyncFnMut(Notif, P::Connection<Host::Counterpart>) -> Result<T, crate::Error> + Send,
1436        T: IntoHandled<(Notif, P::Connection<Host::Counterpart>)>,
1437        ToFut: Fn(
1438                &mut F,
1439                Notif,
1440                P::Connection<Host::Counterpart>,
1441            ) -> crate::BoxFuture<'_, Result<T, crate::Error>>
1442            + Send
1443            + Sync,
1444    {
1445        let handler = NotificationHandler::<_, _, P, _, _, _>::new(
1446            self.host.counterpart(),
1447            self.host.counterpart(),
1448            op,
1449            to_future_hack,
1450        );
1451        self.with_handler(handler)
1452    }
1453
1454    /// Register a handler for messages from a specific peer.
1455    ///
1456    /// This is similar to [`on_receive_dispatch`](Self::on_receive_dispatch), but allows
1457    /// specifying the source peer explicitly. This is useful when receiving messages
1458    /// from a peer that requires message transformation (e.g., unwrapping `SuccessorMessage`
1459    /// envelopes when receiving from an agent via a proxy).
1460    ///
1461    /// For the common case of receiving from the default counterpart, use
1462    /// [`on_receive_dispatch`](Self::on_receive_dispatch) instead.
1463    ///
1464    /// # Ordering
1465    ///
1466    /// This callback runs inside the dispatch loop and blocks further message processing
1467    /// until it completes. See the [`ordering`](crate::concepts::ordering) module for details on
1468    /// ordering guarantees and how to avoid deadlocks.
1469    pub fn on_receive_dispatch_from<
1470        Req: JsonRpcRequest,
1471        Notif: JsonRpcNotification,
1472        Peer: Role,
1473        F,
1474        T,
1475        ToFut,
1476    >(
1477        self,
1478        peer: Peer,
1479        op: F,
1480        to_future_hack: ToFut,
1481    ) -> Builder<Host, impl HandleDispatchFrom<Host::Counterpart>, Runner, Close, P>
1482    where
1483        Host::Counterpart: HasPeer<Peer>,
1484        F: AsyncFnMut(
1485                Dispatch<Req, Notif, P>,
1486                P::Connection<Host::Counterpart>,
1487            ) -> Result<T, crate::Error>
1488            + Send,
1489        T: IntoHandled<Dispatch<Req, Notif, P>>,
1490        ToFut: Fn(
1491                &mut F,
1492                Dispatch<Req, Notif, P>,
1493                P::Connection<Host::Counterpart>,
1494            ) -> crate::BoxFuture<'_, Result<T, crate::Error>>
1495            + Send
1496            + Sync,
1497    {
1498        let handler = MessageHandler::<_, _, P, _, _, _, _>::new(
1499            self.host.counterpart(),
1500            peer,
1501            op,
1502            to_future_hack,
1503        );
1504        self.note_request_handler::<Req>().with_handler(handler)
1505    }
1506
1507    /// Register a handler for JSON-RPC requests from a specific peer.
1508    ///
1509    /// This is similar to [`on_receive_request`](Self::on_receive_request), but allows
1510    /// specifying the source peer explicitly. This is useful when receiving messages
1511    /// from a peer that requires message transformation (e.g., unwrapping `SuccessorRequest`
1512    /// envelopes when receiving from an agent via a proxy).
1513    ///
1514    /// For the common case of receiving from the default counterpart, use
1515    /// [`on_receive_request`](Self::on_receive_request) instead.
1516    ///
1517    /// # Example
1518    ///
1519    /// ```ignore
1520    /// use agent_client_protocol::Agent;
1521    /// use agent_client_protocol::v1::schema::InitializeRequest;
1522    ///
1523    /// // Conductor receiving from agent direction - messages will be unwrapped from SuccessorMessage
1524    /// connection.on_receive_request_from(Agent, async |req: InitializeRequest, responder, cx| {
1525    ///     // Handle the request
1526    ///     responder.respond(InitializeResponse::make())
1527    /// })
1528    /// ```
1529    ///
1530    /// # Ordering
1531    ///
1532    /// This callback runs inside the dispatch loop and blocks further message processing
1533    /// until it completes. See the [`ordering`](crate::concepts::ordering) module for details on
1534    /// ordering guarantees and how to avoid deadlocks.
1535    pub fn on_receive_request_from<Req: JsonRpcRequest, Peer: Role, F, T, ToFut>(
1536        self,
1537        peer: Peer,
1538        op: F,
1539        to_future_hack: ToFut,
1540    ) -> Builder<Host, impl HandleDispatchFrom<Host::Counterpart>, Runner, Close, P>
1541    where
1542        Host::Counterpart: HasPeer<Peer>,
1543        F: AsyncFnMut(
1544                Req,
1545                Responder<Req::Response, P>,
1546                P::Connection<Host::Counterpart>,
1547            ) -> Result<T, crate::Error>
1548            + Send,
1549        T: IntoHandled<(Req, Responder<Req::Response, P>)>,
1550        ToFut: Fn(
1551                &mut F,
1552                Req,
1553                Responder<Req::Response, P>,
1554                P::Connection<Host::Counterpart>,
1555            ) -> crate::BoxFuture<'_, Result<T, crate::Error>>
1556            + Send
1557            + Sync,
1558    {
1559        let handler = RequestHandler::<_, _, P, _, _, _>::new(
1560            self.host.counterpart(),
1561            peer,
1562            op,
1563            to_future_hack,
1564        );
1565        self.note_request_handler::<Req>().with_handler(handler)
1566    }
1567
1568    /// Register a handler for JSON-RPC notifications from a specific peer.
1569    ///
1570    /// This is similar to [`on_receive_notification`](Self::on_receive_notification), but allows
1571    /// specifying the source peer explicitly. This is useful when receiving messages
1572    /// from a peer that requires message transformation (e.g., unwrapping `SuccessorNotification`
1573    /// envelopes when receiving from an agent via a proxy).
1574    ///
1575    /// For the common case of receiving from the default counterpart, use
1576    /// [`on_receive_notification`](Self::on_receive_notification) instead.
1577    ///
1578    /// # Ordering
1579    ///
1580    /// This callback runs inside the dispatch loop and blocks further message processing
1581    /// until it completes. See the [`ordering`](crate::concepts::ordering) module for details on
1582    /// ordering guarantees and how to avoid deadlocks.
1583    pub fn on_receive_notification_from<Notif: JsonRpcNotification, Peer: Role, F, T, ToFut>(
1584        self,
1585        peer: Peer,
1586        op: F,
1587        to_future_hack: ToFut,
1588    ) -> Builder<Host, impl HandleDispatchFrom<Host::Counterpart>, Runner, Close, P>
1589    where
1590        Host::Counterpart: HasPeer<Peer>,
1591        F: AsyncFnMut(Notif, P::Connection<Host::Counterpart>) -> Result<T, crate::Error> + Send,
1592        T: IntoHandled<(Notif, P::Connection<Host::Counterpart>)>,
1593        ToFut: Fn(
1594                &mut F,
1595                Notif,
1596                P::Connection<Host::Counterpart>,
1597            ) -> crate::BoxFuture<'_, Result<T, crate::Error>>
1598            + Send
1599            + Sync,
1600    {
1601        let handler = NotificationHandler::<_, _, P, _, _, _>::new(
1602            self.host.counterpart(),
1603            peer,
1604            op,
1605            to_future_hack,
1606        );
1607        self.with_handler(handler)
1608    }
1609
1610    /// Run in server mode with the provided transport.
1611    ///
1612    /// This drives the connection by continuously processing messages from the transport
1613    /// and dispatching them to your registered handlers. The connection will run until:
1614    /// - The transport closes (e.g., EOF on byte streams)
1615    /// - An error occurs
1616    ///
1617    /// Handler errors are normally contained: requests receive an Error Response,
1618    /// response-handler errors are routed to the pending local request, and
1619    /// notification errors are logged without a wire reply.
1620    ///
1621    /// On clean EOF, messages already accepted by the outgoing queue—including
1622    /// handler responses and close-callback notifications—are drained through
1623    /// the transport sink before this returns `Ok(())`.
1624    ///
1625    /// The transport boundary carries [`TransportFrame`] values. Physical stream adapters
1626    /// serialize and deserialize frames, while channel-based components relay them directly.
1627    ///
1628    /// Use this mode when you only need to respond to incoming messages and don't need
1629    /// to initiate your own requests. If you need to send requests to the other side,
1630    /// use [`connect_with`](Self::connect_with) instead.
1631    ///
1632    /// # Example: Byte Stream Transport
1633    ///
1634    /// ```no_run
1635    /// # use agent_client_protocol::UntypedRole;
1636    /// # use agent_client_protocol::{Builder};
1637    /// # use agent_client_protocol_test::*;
1638    /// # async fn example(transport: impl agent_client_protocol::ConnectTo<UntypedRole>) -> Result<(), agent_client_protocol::Error> {
1639    ///
1640    /// UntypedRole.builder()
1641    ///     .on_receive_request(async |req: MyRequest, responder, cx| {
1642    ///         responder.respond(MyResponse { status: "ok".into() })
1643    ///     }, agent_client_protocol::on_receive_request!())
1644    ///     .connect_to(transport)
1645    ///     .await?;
1646    /// # Ok(())
1647    /// # }
1648    /// ```
1649    pub async fn connect_to(
1650        self,
1651        transport: impl ConnectTo<Host> + 'static,
1652    ) -> Result<(), crate::Error> {
1653        let (_, future) = self.into_connection_and_future(transport, true, async move |cx| {
1654            cx.incoming_closed().await;
1655            Ok(())
1656        });
1657        future.await
1658    }
1659
1660    /// Run the connection until the provided closure completes.
1661    ///
1662    /// This drives the connection by:
1663    /// 1. Running your registered handlers in the background to process incoming messages
1664    /// 2. Executing your `main_fn` closure with the builder-selected connection
1665    ///    context for sending requests and notifications
1666    ///
1667    /// The connection stays active until your `main_fn` returns, then shuts down.
1668    /// Clean incoming EOF fails every pending request and makes future
1669    /// requests fail immediately. It does not cancel unrelated work in
1670    /// `main_fn`: that future may observe the context's `incoming_closed`
1671    /// future, or the builder can use [`on_close`](Self::on_close) to notify it
1672    /// or return an error and stop it.
1673    ///
1674    /// Use this mode when you need to initiate communication (send requests/notifications)
1675    /// in addition to responding to incoming messages. For server-only mode where you just
1676    /// respond to messages, use [`connect_to`](Self::connect_to) instead.
1677    ///
1678    /// # Example
1679    ///
1680    /// ```no_run
1681    /// # use agent_client_protocol::UntypedRole;
1682    /// # use agent_client_protocol::{Builder};
1683    /// # use agent_client_protocol::ByteStreams;
1684    /// # use agent_client_protocol::v1::schema::InitializeRequest;
1685    /// # use agent_client_protocol_test::*;
1686    /// # async fn example(transport: impl agent_client_protocol::ConnectTo<UntypedRole>) -> Result<(), agent_client_protocol::Error> {
1687    ///
1688    /// UntypedRole.builder()
1689    ///     .on_receive_request(async |req: MyRequest, responder, cx| {
1690    ///         // Handle incoming requests in the background
1691    ///         responder.respond(MyResponse { status: "ok".into() })
1692    ///     }, agent_client_protocol::on_receive_request!())
1693    ///     .connect_with(transport, async |cx| {
1694    ///         // Initialize the protocol
1695    ///         let init_response = cx.send_request(InitializeRequest::make())
1696    ///             .block_task()
1697    ///             .await?;
1698    ///
1699    ///         // Send more requests...
1700    ///         let result = cx.send_request(MyRequest {})
1701    ///             .block_task()
1702    ///             .await?;
1703    ///
1704    ///         // When this closure returns, the connection shuts down
1705    ///         Ok(())
1706    ///     })
1707    ///     .await?;
1708    /// # Ok(())
1709    /// # }
1710    /// ```
1711    ///
1712    /// # Parameters
1713    ///
1714    /// - `main_fn`: Your client logic. Receives the builder-selected connection
1715    ///   context for sending messages.
1716    ///
1717    /// # Errors
1718    ///
1719    /// Returns an error if a handler, background task, transport, or close
1720    /// callback fails, or if `main_fn` returns an error. Clean incoming EOF is
1721    /// observable through the context's `incoming_closed` future and is not
1722    /// itself an error in this mode.
1723    pub async fn connect_with<R>(
1724        self,
1725        transport: impl ConnectTo<Host> + 'static,
1726        main_fn: impl AsyncFnOnce(P::Connection<Host::Counterpart>) -> Result<R, crate::Error>,
1727    ) -> Result<R, crate::Error> {
1728        // The driver moves `main_fn` through several nested futures, and each
1729        // one reserves room for it. Box the closure and its future so that the
1730        // returned future holds the caller's captured state once instead of
1731        // once per layer. Otherwise a closure that captures a few kilobytes,
1732        // such as an `initialize` request and response, makes it very large.
1733        let main_fn = Box::new(main_fn);
1734        let (_, future) =
1735            self.into_connection_and_future(transport, false, async move |connection| {
1736                Box::pin(main_fn(protocol::connection_from_raw::<P, _>(connection))).await
1737            });
1738        future.await
1739    }
1740
1741    /// Helper that returns a [`ConnectionTo<R>`] and a future that runs this connection until `main_fn` returns.
1742    fn into_connection_and_future<R>(
1743        self,
1744        transport: impl ConnectTo<Host> + 'static,
1745        wait_owned_transport: bool,
1746        main_fn: impl AsyncFnOnce(ConnectionTo<Host::Counterpart>) -> Result<R, crate::Error>,
1747    ) -> (
1748        ConnectionTo<Host::Counterpart>,
1749        impl Future<Output = Result<R, crate::Error>>,
1750    ) {
1751        let Self {
1752            name,
1753            handler,
1754            runner,
1755            host: me,
1756            protocol_mode,
1757            on_close,
1758            protocol: _,
1759        } = self;
1760
1761        let (outgoing_tx, outgoing_rx) = mpsc::unbounded();
1762        let (new_task_tx, new_task_rx) = mpsc::unbounded();
1763        let (dynamic_handler_tx, dynamic_handler_rx) = mpsc::unbounded();
1764        let (foreground_succeeded_tx, foreground_succeeded) = completion_signal();
1765        let (foreground_done_tx, foreground_done) = completion_signal();
1766        let pending_replies = PendingReplies::default();
1767        let termination_sources = TerminationSources::default();
1768
1769        // Normalize the transport without losing ownership or finish metadata.
1770        let transport_component = crate::DynConnectTo::new(transport);
1771        let (transport_channel, mut transport_future) =
1772            transport_component.into_channel_and_future();
1773        let owned_transport = transport_future.is_some();
1774        let transport_finish = transport_future
1775            .as_mut()
1776            .and_then(crate::ConnectionDriver::take_finish);
1777        let (transport_completion_tx, transport_completion_rx) = oneshot::channel();
1778        let transport_completion = transport_completion_rx
1779            .map(|result| {
1780                result.unwrap_or_else(|error| {
1781                    Err(crate::util::internal_error(format!(
1782                        "transport task dropped before reporting completion: {error}"
1783                    )))
1784                })
1785            })
1786            .boxed()
1787            .shared();
1788
1789        let connection = ConnectionTo::new(
1790            me.counterpart(),
1791            outgoing_tx,
1792            new_task_tx,
1793            dynamic_handler_tx,
1794            transport_completion,
1795            pending_replies.registrar(),
1796            protocol_mode,
1797        );
1798        // Transport progress must outlive successful foreground completion.
1799        // Application tasks remain cancellable. The inherited close-callback
1800        // phase still polls them for cleanup, but physical drain alone does not.
1801        let transport_driver = if let Some(driver) = transport_future {
1802            let termination_sources = termination_sources.clone();
1803            async move {
1804                let result = driver.await;
1805                termination_sources.record(TerminationSource::Transport, &result);
1806                drop(transport_completion_tx.send(result.clone()));
1807                result
1808            }
1809            .boxed()
1810        } else {
1811            // Channel-only endpoints have no physical sink work to await.
1812            // Their protocol drain marker still orders accepted output.
1813            drop(transport_completion_tx.send(Ok(())));
1814            future::ready(Ok(())).boxed()
1815        };
1816
1817        // Destructure the channel endpoints
1818        let Channel {
1819            rx: mut transport_incoming_rx,
1820            tx: transport_outgoing_tx,
1821        } = transport_channel;
1822
1823        let transport_incoming = futures::stream::poll_fn({
1824            let mut completion = connection.transport_completion.clone();
1825            let mut completed = false;
1826            move |cx| {
1827                if owned_transport
1828                    && !completed
1829                    && let std::task::Poll::Ready(Ok(())) =
1830                        std::pin::Pin::new(&mut completion).poll(cx)
1831                {
1832                    // Owned completion closes the producer boundary, not the
1833                    // accepted buffer. The incoming actor still dispatches every
1834                    // accepted frame and completes its close callbacks in order.
1835                    transport_incoming_rx.close();
1836                    completed = true;
1837                }
1838                transport_incoming_rx.poll_next_unpin(cx)
1839            }
1840        });
1841
1842        let protocol_compat = ProtocolCompat::new(protocol_mode);
1843
1844        // Constructed outside the driver so dropping it unpolled still
1845        // publishes a termination.
1846        let termination_guard = TerminationGuard {
1847            incoming_closed: connection.incoming_closed.clone(),
1848            pending_replies: pending_replies.clone(),
1849        };
1850
1851        let future = crate::util::instrument_with_connection_name(name, {
1852            let connection = connection.clone();
1853            async move {
1854                let sources = &termination_sources;
1855                let driver = async {
1856                    let background = async {
1857                        let incoming = {
1858                            let pending_replies = pending_replies.clone();
1859                            let protocol_compat = protocol_compat.clone();
1860                            async {
1861                                let mut transport_incoming = std::pin::pin!(transport_incoming);
1862                                let incoming = incoming_actor::incoming_protocol_actor(
1863                                    me.counterpart(),
1864                                    &connection,
1865                                    transport_incoming.as_mut(),
1866                                    dynamic_handler_rx,
1867                                    pending_replies,
1868                                    incoming_actor::IncomingHandlers::new(
1869                                        handler,
1870                                        on_close,
1871                                        foreground_succeeded.clone(),
1872                                    ),
1873                                    protocol_compat,
1874                                );
1875                                // Success stops delivery, not physical I/O. An
1876                                // underway close callback finishes before sealing.
1877                                let result = run_incoming_until_foreground_succeeds(
1878                                    incoming,
1879                                    foreground_succeeded,
1880                                    connection.incoming_closed.clone(),
1881                                )
1882                                .await;
1883                                sources.record(TerminationSource::Handler, &result);
1884                                if result.is_err() {
1885                                    connection.request_shutdown();
1886                                }
1887                                result?;
1888                                // Keep the raw producer boundary alive while the
1889                                // physical driver drains. Discard without application
1890                                // delivery, rather than fail a late read-side send.
1891                                while transport_incoming.next().await.is_some() {}
1892                                Ok(())
1893                            }
1894                        };
1895                        let other_actors = async {
1896                            let result = futures::try_join!(
1897                                // A ready driver error is authoritative even if its
1898                                // closed channel would also make output forwarding fail.
1899                                transport_driver,
1900                                // Protocol layer: OutgoingMessage -> RawJsonRpcMessage
1901                                outgoing_actor::outgoing_protocol_actor(
1902                                    outgoing_rx,
1903                                    pending_replies,
1904                                    transport_outgoing_tx,
1905                                    protocol_compat,
1906                                    foreground_done,
1907                                )
1908                                .inspect(
1909                                    |result| sources.record(TerminationSource::Transport, result)
1910                                ),
1911                            );
1912                            // Signal before awaiting an underway close callback.
1913                            if result.is_err() {
1914                                connection.request_shutdown();
1915                            }
1916                            result?;
1917                            Ok(())
1918                        };
1919
1920                        // Keep close callbacks alive when another core actor fails.
1921                        // The outer coordination provides the same protection when
1922                        // EOF wakes an application task or the foreground.
1923                        run_until_connection_close(
1924                            incoming,
1925                            other_actors,
1926                            connection.incoming_closed.clone(),
1927                        )
1928                        .await
1929                    };
1930
1931                    run_until_connection_close(
1932                        finish_actor_error(background, &connection),
1933                        async {
1934                            let application = async {
1935                                futures::try_join!(
1936                                    finish_actor_error(
1937                                        task_actor::task_actor(new_task_rx, &connection)
1938                                            .inspect(|result| sources
1939                                                .record(TerminationSource::Handler, result),),
1940                                        &connection,
1941                                    ),
1942                                    finish_actor_error(
1943                                        runner
1944                                            .run_with_connection_to(connection.clone())
1945                                            .inspect(|result| sources
1946                                                .record(TerminationSource::Handler, result),),
1947                                        &connection,
1948                                    ),
1949                                )?;
1950                                Ok(())
1951                            };
1952                            let result = run_until_connection_close(
1953                                application,
1954                                async {
1955                                    let result = main_fn(connection.clone()).await;
1956                                    sources.record(TerminationSource::Foreground, &result);
1957                                    connection.request_shutdown();
1958                                    if result.is_ok() {
1959                                        // Stop new incoming delivery immediately,
1960                                        // including during the callback cleanup phase.
1961                                        let _ = foreground_succeeded_tx.send(());
1962                                    }
1963                                    // Shutdown cancels local consumers, not remote
1964                                    // requests. Do not add cancellation traffic while
1965                                    // dropping those consumers before the drain.
1966                                    connection.pending_replies.disarm_cancellations();
1967                                    // The application actor (including actual scoped
1968                                    // runners) remains polled while supervisors finish.
1969                                    // Only then may ordinary application tasks drop.
1970                                    connection.wait_protected_operations().await;
1971                                    result
1972                                },
1973                                connection.incoming_closed.clone(),
1974                            )
1975                            .await?;
1976                            let _ = foreground_done_tx.send(());
1977                            let drained = connection
1978                                .drain_outgoing(transport_finish, wait_owned_transport)
1979                                .await;
1980                            sources.record(TerminationSource::Transport, &drained);
1981                            drained?;
1982                            Ok(result)
1983                        },
1984                        connection.incoming_closed.clone(),
1985                    )
1986                    .await
1987                };
1988                // Every actor, handler, and task has completed or been
1989                // dropped by the time `driver` resolves.
1990                let result = driver.await;
1991                termination_guard.finish(match &result {
1992                    // A foreground that finishes after observing EOF still
1993                    // ended at a clean EOF boundary.
1994                    Ok(_) if connection.incoming_closed.is_closing() => {
1995                        ConnectionTermination::IncomingClosed
1996                    }
1997                    Ok(_) => ConnectionTermination::LocalShutdown,
1998                    Err(error) => sources.classify(error.clone()),
1999                });
2000                result
2001            }
2002        });
2003
2004        (connection, future)
2005    }
2006}
2007
2008/// Defer an actor error without dropping the other actors that drive owned
2009/// cleanup or an underway close callback. Physical output drain stays separate.
2010async fn finish_actor_error<R: Role>(
2011    actor: impl Future<Output = Result<(), crate::Error>>,
2012    connection: &ConnectionTo<R>,
2013) -> Result<(), crate::Error> {
2014    let result = actor.await;
2015    if result.is_err() {
2016        connection.request_shutdown();
2017        if connection.incoming_closed.is_closing() {
2018            connection.incoming_closed.closed().await;
2019        }
2020        connection.wait_protected_operations().await;
2021    }
2022    result
2023}
2024
2025#[cfg(feature = "unstable_mcp_over_acp")]
2026impl<
2027    Host: Role,
2028    Handler: HandleDispatchFrom<Host::Counterpart>,
2029    Runner: RunWithConnectionTo<Host::Counterpart>,
2030    Close: HandleConnectionClose<Host::Counterpart>,
2031> Builder<Host, Handler, Runner, Close, V1>
2032{
2033    /// Add an MCP server to protocol v1 session setup requests proxied through
2034    /// this connection.
2035    ///
2036    /// The same native MCP server declaration is added to new, load, and resume
2037    /// requests, plus fork requests when `unstable_session_fork` is enabled.
2038    /// Unrelated request fields are preserved exactly.
2039    ///
2040    /// Only applicable to proxies. Use the same method on `v2::Builder` to
2041    /// attach the server to protocol v2 setup requests.
2042    ///
2043    /// The declaration is an `acp` transport (`McpServer::Acp`). The agent must
2044    /// advertise `agentCapabilities.mcpCapabilities.acp`, or a compatibility
2045    /// proxy such as `McpOverAcpPolyfill` must sit between this proxy and the
2046    /// agent; otherwise a conforming agent rejects the setup request with
2047    /// `-32602`. This method does not check the agent's capabilities.
2048    pub fn with_mcp_server(
2049        self,
2050        mcp_server: McpServer<Host::Counterpart, impl RunWithConnectionTo<Host::Counterpart>>,
2051    ) -> Builder<
2052        Host,
2053        impl HandleDispatchFrom<Host::Counterpart>,
2054        impl RunWithConnectionTo<Host::Counterpart>,
2055        Close,
2056        V1,
2057    >
2058    where
2059        Host::Counterpart: HasPeer<Agent> + HasPeer<Client>,
2060    {
2061        let (handler, runner) = mcp_server.into_handler_and_runner();
2062        self.with_handler(handler).with_runner(runner)
2063    }
2064}
2065
2066#[cfg(all(feature = "unstable_mcp_over_acp", feature = "unstable_protocol_v2"))]
2067impl<
2068    Host: Role,
2069    Handler: HandleDispatchFrom<Host::Counterpart>,
2070    Runner: RunWithConnectionTo<Host::Counterpart>,
2071    Close: HandleConnectionClose<Host::Counterpart>,
2072> Builder<Host, Handler, Runner, Close, V2>
2073{
2074    /// Add an MCP server to protocol v2 session setup requests proxied through
2075    /// this connection.
2076    ///
2077    /// The same native MCP server declaration is added to new and resume
2078    /// requests, plus fork requests when `unstable_session_fork` is enabled.
2079    /// Unrelated request fields are preserved exactly.
2080    ///
2081    /// MCP server names must be unique within `mcpServers`. If a client's
2082    /// setup request already declares a server with this server's name, the
2083    /// proxy answers that request with `-32602` naming the conflicting server
2084    /// and does not forward it. The client's servers are never renamed or
2085    /// dropped.
2086    ///
2087    /// Only applicable to proxies.
2088    ///
2089    /// The declaration is an `acp` transport (`McpServer::Acp`). The downstream
2090    /// agent must advertise `session.mcp.acp`, or a compatibility proxy such as
2091    /// `McpOverAcpPolyfill` must sit between this proxy and the agent;
2092    /// otherwise a conforming agent rejects the setup request with `-32602`.
2093    /// This method does not check the agent's capabilities.
2094    pub fn with_mcp_server(
2095        self,
2096        mcp_server: McpServer<Host::Counterpart, impl RunWithConnectionTo<Host::Counterpart>>,
2097    ) -> Builder<
2098        Host,
2099        impl HandleDispatchFrom<Host::Counterpart>,
2100        impl RunWithConnectionTo<Host::Counterpart>,
2101        Close,
2102        V2,
2103    >
2104    where
2105        Host::Counterpart: HasPeer<Agent> + HasPeer<Client>,
2106    {
2107        let (handler, runner) = mcp_server.into_v2_handler_and_runner();
2108        self.with_handler(handler).with_runner(runner)
2109    }
2110}
2111
2112impl<R, H, Run, Close, P> ConnectTo<R::Counterpart> for Builder<R, H, Run, Close, P>
2113where
2114    R: Role,
2115    H: HandleDispatchFrom<R::Counterpart> + 'static,
2116    Run: RunWithConnectionTo<R::Counterpart> + 'static,
2117    Close: HandleConnectionClose<R::Counterpart> + 'static,
2118    P: Protocol,
2119{
2120    async fn connect_to(self, client: impl ConnectTo<R>) -> Result<(), crate::Error> {
2121        Builder::connect_to(self, client).await
2122    }
2123}
2124
2125/// The payload sent through the response oneshot channel.
2126///
2127/// Includes the response value and an optional ack channel for dispatch loop
2128/// synchronization.
2129pub(crate) struct ResponsePayload {
2130    /// The response result - either the JSON value or an error.
2131    pub(crate) result: Result<serde_json::Value, crate::Error>,
2132
2133    /// Optional acknowledgment channel for dispatch loop synchronization.
2134    ///
2135    /// When present, the receiver must send on this channel to signal that
2136    /// response processing is complete, allowing the dispatch loop to continue
2137    /// to the next message.
2138    ///
2139    /// This is present when ordered response consumption was selected before
2140    /// the response was routed during its original dispatch. Public callback
2141    /// consumption and framework-owned ordered blocking transforms can hold
2142    /// the dispatch loop; ordinary blocking consumers, local error paths, and
2143    /// responses routed later do not.
2144    pub(crate) ack_tx: Option<oneshot::Sender<()>>,
2145}
2146
2147type ResponseRouteHook =
2148    Box<dyn FnOnce(&str, &serde_json::Value) -> Result<(), crate::Error> + Send>;
2149
2150/// A prerequisite that must complete before an outgoing request is published
2151/// to the transport.
2152struct RequestReadiness {
2153    future: BoxFuture<'static, Result<(), crate::Error>>,
2154}
2155
2156impl RequestReadiness {
2157    fn new(future: impl Future<Output = Result<(), crate::Error>> + Send + 'static) -> Self {
2158        Self {
2159            future: future.boxed(),
2160        }
2161    }
2162}
2163
2164impl Future for RequestReadiness {
2165    type Output = Result<(), crate::Error>;
2166
2167    fn poll(
2168        mut self: std::pin::Pin<&mut Self>,
2169        cx: &mut std::task::Context<'_>,
2170    ) -> std::task::Poll<Self::Output> {
2171        self.future.as_mut().poll(cx)
2172    }
2173}
2174
2175impl Debug for RequestReadiness {
2176    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2177        formatter
2178            .debug_struct("RequestReadiness")
2179            .finish_non_exhaustive()
2180    }
2181}
2182
2183impl std::fmt::Debug for ResponsePayload {
2184    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2185        f.debug_struct("ResponsePayload")
2186            .field("result", &self.result)
2187            .field("ack_tx", &self.ack_tx.as_ref().map(|_| "..."))
2188            .finish()
2189    }
2190}
2191
2192#[derive(Clone, Debug, Default)]
2193struct ResponseOrdering {
2194    ordered: Arc<AtomicBool>,
2195}
2196
2197impl ResponseOrdering {
2198    fn mark_ordered(&self) {
2199        self.ordered.store(true, Ordering::Release);
2200    }
2201
2202    fn is_ordered(&self) -> bool {
2203        self.ordered.load(Ordering::Acquire)
2204    }
2205}
2206
2207struct PendingReply {
2208    id: RawJsonRpcId,
2209    method: String,
2210    role_id: RoleId,
2211    sender: oneshot::Sender<ResponsePayload>,
2212    cancellation_disarm: SentRequestCancellationDisarm,
2213    ordering: ResponseOrdering,
2214    response_route_hook: Option<ResponseRouteHook>,
2215    /// Set only by `v2::ConnectionTo::send_initialize`, whose typed outcome
2216    /// reports a lower-version initialize response as a success.
2217    accepts_lower_initialize_version: bool,
2218}
2219
2220impl PendingReply {
2221    fn fail(self, error: crate::Error) {
2222        self.cancellation_disarm.disarm();
2223        if self
2224            .sender
2225            .send(ResponsePayload {
2226                result: Err(error),
2227                ack_tx: None,
2228            })
2229            .is_err()
2230        {
2231            tracing::trace!(method = %self.method, "Pending request was already dropped");
2232        }
2233    }
2234
2235    fn fail_incoming_closed(self) {
2236        let error = incoming_transport_closed_error(&self.method);
2237        self.fail(error);
2238    }
2239}
2240
2241#[derive(Default)]
2242struct PendingRepliesInner {
2243    incoming_closed: bool,
2244    termination: Option<ConnectionTermination>,
2245    replies: HashMap<RawJsonRpcId, PendingReply>,
2246}
2247
2248#[derive(Clone, Default)]
2249struct PendingReplies {
2250    inner: Arc<Mutex<PendingRepliesInner>>,
2251}
2252
2253impl PendingReplies {
2254    fn registrar(&self) -> PendingRepliesRegistrar {
2255        PendingRepliesRegistrar {
2256            inner: Arc::downgrade(&self.inner),
2257        }
2258    }
2259
2260    fn contains(&self, id: &RawJsonRpcId) -> bool {
2261        self.inner
2262            .lock()
2263            .expect("pending replies mutex poisoned")
2264            .replies
2265            .contains_key(id)
2266    }
2267
2268    fn remove(&self, id: &RawJsonRpcId) -> Option<PendingReply> {
2269        self.inner
2270            .lock()
2271            .expect("pending replies mutex poisoned")
2272            .replies
2273            .remove(id)
2274    }
2275
2276    /// Atomically reject new subscriptions and fail every existing one.
2277    fn close_incoming(&self) -> usize {
2278        let replies = {
2279            let mut inner = self.inner.lock().expect("pending replies mutex poisoned");
2280            inner.incoming_closed = true;
2281            std::mem::take(&mut inner.replies)
2282        };
2283        let count = replies.len();
2284        for (_, reply) in replies {
2285            reply.fail_incoming_closed();
2286        }
2287        count
2288    }
2289
2290    /// Atomically reject new subscriptions and fail every remaining one
2291    /// because the driver has terminated.
2292    fn terminate(&self, termination: &ConnectionTermination) -> usize {
2293        let replies = {
2294            let mut inner = self.inner.lock().expect("pending replies mutex poisoned");
2295            inner.termination = Some(termination.clone());
2296            std::mem::take(&mut inner.replies)
2297        };
2298        let count = replies.len();
2299        for (_, reply) in replies {
2300            let error = connection_terminated_error(&reply.method, termination);
2301            reply.fail(error);
2302        }
2303        count
2304    }
2305}
2306
2307/// A non-owning handle used to register a request before it enters the
2308/// outgoing queue. Keeping this weak prevents escaped [`ConnectionTo`] clones
2309/// from extending the lifetime of response senders after the driver stops.
2310#[derive(Clone)]
2311struct PendingRepliesRegistrar {
2312    inner: Weak<Mutex<PendingRepliesInner>>,
2313}
2314
2315impl PendingRepliesRegistrar {
2316    fn disarm_cancellations(&self) {
2317        if let Some(inner) = self.inner.upgrade() {
2318            let inner = inner.lock().expect("pending replies mutex poisoned");
2319            for reply in inner.replies.values() {
2320                reply.cancellation_disarm.disarm();
2321            }
2322        }
2323    }
2324
2325    /// Register a response destination before the request becomes observable.
2326    ///
2327    /// Returns an error after failing `reply` when EOF has already made a
2328    /// response impossible or the connection driver is no longer running.
2329    fn subscribe(
2330        &self,
2331        id: RawJsonRpcId,
2332        reply: PendingReply,
2333        incoming_closed: &IncomingClosed,
2334    ) -> Result<(), crate::Error> {
2335        let Some(inner) = self.inner.upgrade() else {
2336            let error = if incoming_closed.is_closing() {
2337                incoming_transport_closed_error(&reply.method)
2338            } else if let Some(termination) = incoming_closed.termination() {
2339                connection_terminated_error(&reply.method, &termination)
2340            } else {
2341                crate::util::internal_error(format!(
2342                    "failed to send outgoing request `{}`: connection is no longer running",
2343                    reply.method
2344                ))
2345            };
2346            reply.fail(error.clone());
2347            return Err(error);
2348        };
2349
2350        let result = {
2351            let mut inner = inner.lock().expect("pending replies mutex poisoned");
2352            if inner.incoming_closed {
2353                Err((reply, None))
2354            } else if let Some(termination) = &inner.termination {
2355                Err((reply, Some(termination.clone())))
2356            } else {
2357                Ok(inner.replies.insert(id, reply))
2358            }
2359        };
2360
2361        match result {
2362            Err((rejected, termination)) => {
2363                let error = match termination {
2364                    Some(termination) => {
2365                        connection_terminated_error(&rejected.method, &termination)
2366                    }
2367                    None => incoming_transport_closed_error(&rejected.method),
2368                };
2369                rejected.fail(error.clone());
2370                Err(error)
2371            }
2372            Ok(replaced) => {
2373                if let Some(replaced) = replaced {
2374                    replaced.fail(
2375                        crate::Error::internal_error()
2376                            .data("outgoing request ID was reused before its response arrived"),
2377                    );
2378                }
2379                Ok(())
2380            }
2381        }
2382    }
2383
2384    fn remove(&self, id: &RawJsonRpcId) -> Option<PendingReply> {
2385        self.inner
2386            .upgrade()?
2387            .lock()
2388            .expect("pending replies mutex poisoned")
2389            .replies
2390            .remove(id)
2391    }
2392}
2393
2394impl Debug for PendingRepliesRegistrar {
2395    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2396        formatter
2397            .debug_struct("PendingRepliesRegistrar")
2398            .field("is_connected", &(self.inner.strong_count() > 0))
2399            .finish()
2400    }
2401}
2402
2403/// A request-local marker that is set when the peer asks to cancel the request.
2404///
2405/// Request handlers can get this handle from [`Responder::cancellation`] and
2406/// use it from spawned work to stop long-running request processing
2407/// cooperatively.
2408#[derive(Clone)]
2409pub struct RequestCancellation {
2410    state: Arc<RequestCancellationState>,
2411}
2412
2413struct RequestCancellationState {
2414    cancelled: AtomicBool,
2415    signal_tx: Mutex<Option<oneshot::Sender<()>>>,
2416    signal_rx: future::Shared<BoxFuture<'static, ()>>,
2417}
2418
2419impl RequestCancellation {
2420    fn new() -> Self {
2421        let (signal_tx, signal_rx) = oneshot::channel();
2422        let signal_rx = signal_rx.map(|_| ()).boxed().shared();
2423        Self {
2424            state: Arc::new(RequestCancellationState {
2425                cancelled: AtomicBool::new(false),
2426                signal_tx: Mutex::new(Some(signal_tx)),
2427                signal_rx,
2428            }),
2429        }
2430    }
2431
2432    /// Wait until the peer sends `$/cancel_request` for this request.
2433    ///
2434    /// If cancellation was already requested, this returns immediately.
2435    pub async fn cancelled(&self) {
2436        self.state.signal_rx.clone().await;
2437    }
2438
2439    /// Run request work until it completes or the peer asks to cancel it.
2440    ///
2441    /// If cancellation is requested first, this returns
2442    /// [`Error::request_cancelled`]. This is a convenience for request handlers
2443    /// that want to respond with the normal result or the standard
2444    /// cancellation error.
2445    ///
2446    /// When cancellation wins, `future` is dropped: work stops at its next
2447    /// await point, partial results are lost, and any cleanup must happen in
2448    /// `Drop` implementations. Handlers that need to flush partial results or
2449    /// run async cleanup should instead watch [`cancelled`](Self::cancelled)
2450    /// or poll [`is_cancelled`](Self::is_cancelled) from inside the work.
2451    ///
2452    /// [`Error::request_cancelled`]: crate::Error::request_cancelled
2453    pub async fn run_until_cancelled<T>(
2454        &self,
2455        future: impl std::future::Future<Output = Result<T, crate::Error>>,
2456    ) -> Result<T, crate::Error> {
2457        if self.is_cancelled() {
2458            return Err(crate::Error::request_cancelled());
2459        }
2460
2461        match future::select(pin!(future), pin!(self.cancelled())).await {
2462            Either::Left((result, _)) => result,
2463            Either::Right(((), _)) => Err(crate::Error::request_cancelled()),
2464        }
2465    }
2466
2467    /// Returns whether the peer has already requested cancellation.
2468    #[must_use]
2469    pub fn is_cancelled(&self) -> bool {
2470        self.state.cancelled.load(Ordering::Acquire)
2471    }
2472
2473    fn cancel(&self) {
2474        if self.state.cancelled.swap(true, Ordering::AcqRel) {
2475            return;
2476        }
2477
2478        let signal_tx = self
2479            .state
2480            .signal_tx
2481            .lock()
2482            .expect("request cancellation signal mutex poisoned")
2483            .take();
2484
2485        // Complete the oneshot outside the lock: it wakes waiters, and
2486        // arbitrary waker code must not observe the lock held.
2487        if let Some(signal_tx) = signal_tx {
2488            let _ = signal_tx.send(());
2489        }
2490    }
2491}
2492
2493impl Debug for RequestCancellation {
2494    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2495        formatter
2496            .debug_struct("RequestCancellation")
2497            .field("is_cancelled", &self.is_cancelled())
2498            .finish_non_exhaustive()
2499    }
2500}
2501
2502/// Per-request cancellation state tracked by [`RequestCancellationRegistry`].
2503///
2504/// The full [`RequestCancellation`] marker (with its wakeup machinery) is only
2505/// allocated once a handler asks for it via [`Responder::cancellation`]; until
2506/// then an incoming `$/cancel_request` just flips the entry to `Cancelled`.
2507/// This keeps the per-request cost of the registry to a single map entry.
2508#[derive(Debug)]
2509enum RequestCancellationEntry {
2510    /// The request is in flight; no marker handed out, no cancellation yet.
2511    Armed,
2512    /// `$/cancel_request` arrived before a marker was handed out.
2513    Cancelled,
2514    /// A marker was handed out via [`Responder::cancellation`].
2515    Marker(RequestCancellation),
2516}
2517
2518/// A registered request's cancellation state, tagged with the generation of
2519/// its registration.
2520///
2521/// The generation distinguishes a registration from earlier ones that used
2522/// the same request ID, so that when a (protocol-violating) peer reuses the
2523/// ID of a request that is still in flight, the stale request's responder can
2524/// neither remove nor observe the cancellation state of the newer request.
2525#[derive(Debug)]
2526struct RequestCancellationSlot {
2527    generation: u64,
2528    entry: RequestCancellationEntry,
2529}
2530
2531#[derive(Debug, Default)]
2532struct RequestCancellationRegistryInner {
2533    slots: HashMap<RawJsonRpcId, RequestCancellationSlot>,
2534    next_generation: u64,
2535}
2536
2537#[derive(Clone, Debug, Default)]
2538struct RequestCancellationRegistry {
2539    inner: Arc<Mutex<RequestCancellationRegistryInner>>,
2540}
2541
2542#[derive(Debug)]
2543struct ResponderCancellation {
2544    id: RawJsonRpcId,
2545    generation: u64,
2546    registry: RequestCancellationRegistry,
2547}
2548
2549impl RequestCancellationRegistry {
2550    fn new() -> Self {
2551        Self::default()
2552    }
2553
2554    fn register(&self, id: &RawJsonRpcId) -> ResponderCancellation {
2555        let generation = {
2556            let mut inner = self
2557                .inner
2558                .lock()
2559                .expect("request cancellation registry mutex poisoned");
2560            let generation = inner.next_generation;
2561            inner.next_generation += 1;
2562            if inner
2563                .slots
2564                .insert(
2565                    id.clone(),
2566                    RequestCancellationSlot {
2567                        generation,
2568                        entry: RequestCancellationEntry::Armed,
2569                    },
2570                )
2571                .is_some()
2572            {
2573                tracing::debug!(
2574                    ?id,
2575                    "peer reused the ID of a request that is still in flight"
2576                );
2577            }
2578            generation
2579        };
2580        ResponderCancellation {
2581            id: id.clone(),
2582            generation,
2583            registry: self.clone(),
2584        }
2585    }
2586
2587    /// Get the cancellation marker for a registered request, creating it on
2588    /// first use. Repeated calls return markers that share the same state.
2589    ///
2590    /// Exception: when the registration is stale (a protocol-violating peer
2591    /// reused this request ID and the slot now belongs to a newer request, or
2592    /// was already removed by it), every call returns a fresh *detached*
2593    /// marker. Detached markers can never fire, and detached markers from
2594    /// repeated calls do not share state with each other.
2595    fn marker(&self, id: &RawJsonRpcId, generation: u64) -> RequestCancellation {
2596        let mut inner = self
2597            .inner
2598            .lock()
2599            .expect("request cancellation registry mutex poisoned");
2600        let Some(slot) = inner.slots.get_mut(id) else {
2601            // The slot lives as long as the responder that owns it, so this
2602            // is only reachable if the peer reused this request ID and the
2603            // newer request's responder already removed the replacement slot.
2604            // Hand out a detached marker rather than panicking.
2605            return RequestCancellation::new();
2606        };
2607        if slot.generation != generation {
2608            // The peer reused this request ID while the request was still in
2609            // flight, and the slot now belongs to the newer request. Hand the
2610            // stale responder a detached marker instead of cross-wiring the
2611            // two requests' cancellation states.
2612            return RequestCancellation::new();
2613        }
2614        let entry = &mut slot.entry;
2615        match entry {
2616            RequestCancellationEntry::Marker(marker) => marker.clone(),
2617            RequestCancellationEntry::Armed => {
2618                let marker = RequestCancellation::new();
2619                *entry = RequestCancellationEntry::Marker(marker.clone());
2620                marker
2621            }
2622            RequestCancellationEntry::Cancelled => {
2623                // No one can be waiting on a marker that did not exist yet,
2624                // so firing it while holding the registry lock is fine.
2625                let marker = RequestCancellation::new();
2626                marker.cancel();
2627                *entry = RequestCancellationEntry::Marker(marker.clone());
2628                marker
2629            }
2630        }
2631    }
2632
2633    fn cancel_if_requested(&self, dispatch: &Dispatch) -> Result<bool, crate::Error> {
2634        let Some(request_id) = cancellation_request_id(dispatch)? else {
2635            return Ok(false);
2636        };
2637        Ok(self.cancel(&request_id))
2638    }
2639
2640    /// Mark whichever request currently owns `request_id` as cancelled.
2641    fn cancel(&self, request_id: &RawJsonRpcId) -> bool {
2642        let marker = {
2643            let mut inner = self
2644                .inner
2645                .lock()
2646                .expect("request cancellation registry mutex poisoned");
2647            let Some(slot) = inner.slots.get_mut(request_id) else {
2648                return false;
2649            };
2650            let entry = &mut slot.entry;
2651            match entry {
2652                RequestCancellationEntry::Marker(marker) => marker.clone(),
2653                RequestCancellationEntry::Cancelled => return true,
2654                RequestCancellationEntry::Armed => {
2655                    *entry = RequestCancellationEntry::Cancelled;
2656                    return true;
2657                }
2658            }
2659        };
2660
2661        // Fire the marker outside the registry lock: waking waiters runs
2662        // arbitrary waker code that must not observe the lock held.
2663        marker.cancel();
2664        true
2665    }
2666
2667    /// Remove the slot for `request_id`, but only if it still belongs to the
2668    /// registration identified by `generation`.
2669    fn remove(&self, request_id: &RawJsonRpcId, generation: u64) {
2670        let mut inner = self
2671            .inner
2672            .lock()
2673            .expect("request cancellation registry mutex poisoned");
2674        if inner
2675            .slots
2676            .get(request_id)
2677            .is_some_and(|slot| slot.generation == generation)
2678        {
2679            inner.slots.remove(request_id);
2680        }
2681    }
2682}
2683
2684impl ResponderCancellation {
2685    fn cancellation(&self) -> RequestCancellation {
2686        self.registry.marker(&self.id, self.generation)
2687    }
2688
2689    /// Whether the peer has cancelled this request, without allocating a
2690    /// marker.
2691    fn is_cancelled(&self) -> bool {
2692        let inner = self
2693            .registry
2694            .inner
2695            .lock()
2696            .expect("request cancellation registry mutex poisoned");
2697        let Some(slot) = inner.slots.get(&self.id) else {
2698            return false;
2699        };
2700        if slot.generation != self.generation {
2701            return false;
2702        }
2703        match &slot.entry {
2704            RequestCancellationEntry::Armed => false,
2705            RequestCancellationEntry::Cancelled => true,
2706            RequestCancellationEntry::Marker(marker) => marker.is_cancelled(),
2707        }
2708    }
2709}
2710
2711impl Drop for ResponderCancellation {
2712    fn drop(&mut self) {
2713        self.registry.remove(&self.id, self.generation);
2714    }
2715}
2716
2717fn cancellation_request_id(dispatch: &Dispatch) -> Result<Option<RawJsonRpcId>, crate::Error> {
2718    let Dispatch::Notification(message) = dispatch else {
2719        return Ok(None);
2720    };
2721    cancellation_request_id_from_message(message)
2722}
2723
2724fn cancellation_request_id_from_message(
2725    message: &UntypedMessage,
2726) -> Result<Option<RawJsonRpcId>, crate::Error> {
2727    let (method, params) = peel_successor_envelopes(&message.method, &message.params);
2728    if !crate::v1::schema::CancelRequestNotification::matches_method(method) {
2729        return Ok(None);
2730    }
2731
2732    let notification = crate::v1::schema::CancelRequestNotification::parse_message(method, params)?;
2733    Ok(Some(notification.request_id.into()))
2734}
2735
2736/// Peel any [`SuccessorMessage`] envelopes off a notification by reference,
2737/// returning the innermost method and params.
2738///
2739/// This only peeks at the envelope's `method`/`params` fields instead of
2740/// deserializing the envelope, for two reasons:
2741///
2742/// - It avoids deep-cloning the params of every wrapped notification on the
2743///   hot dispatch path just to inspect the inner method name.
2744/// - It is deliberately lenient: a malformed envelope is left as-is here and
2745///   flows on to the handler chain, which is responsible for reporting it.
2746///
2747/// [`SuccessorMessage`]: crate::schema::SuccessorMessage
2748fn peel_successor_envelopes<'message>(
2749    mut method: &'message str,
2750    mut params: &'message serde_json::Value,
2751) -> (&'message str, &'message serde_json::Value) {
2752    while crate::schema::SuccessorMessage::<UntypedMessage>::matches_method(method) {
2753        let Some(inner_method) = params.get("method").and_then(serde_json::Value::as_str) else {
2754            break;
2755        };
2756        method = inner_method;
2757        params = params.get("params").unwrap_or(&serde_json::Value::Null);
2758    }
2759    (method, params)
2760}
2761
2762/// Whether a notification is a `$/cancel_request`, even when it is still
2763/// wrapped in `proxy/successor` envelopes.
2764///
2765/// `$/cancel_request` is connection-scoped: its `requestId` was allocated on
2766/// the connection the notification arrived over and means nothing on any
2767/// other connection. Generic forwarding code (such as
2768/// [`ConnectionTo::send_proxied_message_to`]) uses this check to drop the raw
2769/// notification instead of tunneling it across a hop; the cancellation still
2770/// propagates because [`forward_response_to`](SentRequest::forward_response_to)
2771/// re-issues it with the forwarded request's own ID.
2772///
2773/// Checking a notification whose method is not the successor envelope is a
2774/// plain method-name comparison. Only successor-wrapped notifications pay for
2775/// a serialization to peel the envelope.
2776#[must_use]
2777pub fn is_cancel_request_notification<N: JsonRpcNotification>(notification: &N) -> bool {
2778    let method = notification.method();
2779    if crate::v1::schema::CancelRequestNotification::matches_method(method) {
2780        return true;
2781    }
2782    if !crate::schema::SuccessorMessage::<UntypedMessage>::matches_method(method) {
2783        return false;
2784    }
2785
2786    match notification.to_untyped_message() {
2787        Ok(untyped) => {
2788            let (method, _params) = peel_successor_envelopes(&untyped.method, &untyped.params);
2789            crate::v1::schema::CancelRequestNotification::matches_method(method)
2790        }
2791        Err(error) => {
2792            tracing::debug!(
2793                error = ?crate::util::redacted_error(error.code),
2794                "failed to inspect successor-wrapped notification for cancellation"
2795            );
2796            false
2797        }
2798    }
2799}
2800
2801/// Where the response to an incoming request is sent.
2802///
2803/// A request is answered at most once; a duplicate completion is ignored.
2804///
2805/// While a handler attempt for the request is running (see
2806/// [`begin_handler_attempt`](Self::begin_handler_attempt)), the automatic
2807/// error for a dropped [`Responder`] is held back: if the handler then
2808/// returns an error, that error is the response, not the generic fallback.
2809#[derive(Clone, Debug, Default)]
2810struct ResponseDestination {
2811    state: Arc<ResponseDestinationState>,
2812}
2813
2814#[derive(Debug, Default)]
2815struct ResponseDestinationState {
2816    completed: AtomicBool,
2817    attempts: Mutex<HandlerAttempts>,
2818}
2819
2820#[derive(Debug, Default)]
2821struct HandlerAttempts {
2822    active: usize,
2823    deferred: Option<AbandonedResponse>,
2824}
2825
2826/// The automatic error response for a [`Responder`] dropped without replying.
2827#[derive(Debug)]
2828struct AbandonedResponse {
2829    message_tx: OutgoingMessageTx,
2830    connection_state: IncomingClosed,
2831    message: OutgoingMessage,
2832}
2833
2834impl AbandonedResponse {
2835    fn send(self) {
2836        // Re-check: shutdown may have begun while the response was deferred.
2837        if self.connection_state.is_shutting_down() {
2838            tracing::debug!("not answering dropped responder: connection is shutting down");
2839            return;
2840        }
2841        if let Err(error) = send_raw_message(&self.message_tx, self.message) {
2842            tracing::debug!(
2843                error = ?crate::util::redacted_error(error.code),
2844                "could not answer request whose responder was dropped"
2845            );
2846        }
2847    }
2848}
2849
2850/// A running handler attempt for one request; see [`ResponseDestination`].
2851struct HandlerAttempt {
2852    destination: ResponseDestination,
2853}
2854
2855impl Drop for HandlerAttempt {
2856    fn drop(&mut self) {
2857        let deferred = {
2858            let mut attempts = self.destination.attempts();
2859            attempts.active -= 1;
2860            if attempts.active == 0 {
2861                attempts.deferred.take()
2862            } else {
2863                None
2864            }
2865        };
2866        if let Some(deferred) = deferred {
2867            deferred.send();
2868        }
2869    }
2870}
2871
2872impl ResponseDestination {
2873    fn individual() -> Self {
2874        Self::default()
2875    }
2876
2877    fn attempts(&self) -> std::sync::MutexGuard<'_, HandlerAttempts> {
2878        self.state
2879            .attempts
2880            .lock()
2881            .expect("response destination mutex poisoned")
2882    }
2883
2884    fn is_completed(&self) -> bool {
2885        self.state.completed.load(Ordering::Acquire)
2886    }
2887
2888    fn complete(self, response: RawJsonRpcMessage) -> Option<TransportFrame> {
2889        if self.state.completed.swap(true, Ordering::AcqRel) {
2890            tracing::warn!("Ignoring duplicate completion of JSON-RPC request");
2891            return None;
2892        }
2893
2894        Some(TransportFrame::Single(response))
2895    }
2896
2897    fn begin_handler_attempt(&self) -> HandlerAttempt {
2898        self.attempts().active += 1;
2899        HandlerAttempt {
2900            destination: self.clone(),
2901        }
2902    }
2903
2904    /// Send, or defer until the running handler attempt ends, the automatic
2905    /// error for a dropped responder.
2906    fn abandon(&self, response: AbandonedResponse) {
2907        {
2908            let mut attempts = self.attempts();
2909            if attempts.active > 0 {
2910                attempts.deferred = Some(response);
2911                return;
2912            }
2913        }
2914        response.send();
2915    }
2916
2917    /// A handler error answers the request; drop any deferred fallback.
2918    fn discard_abandoned(&self) {
2919        self.attempts().deferred = None;
2920    }
2921}
2922
2923#[derive(Clone, Debug)]
2924struct RequestReplyTarget {
2925    id: RawJsonRpcId,
2926    method: String,
2927    destination: ResponseDestination,
2928}
2929
2930#[derive(Clone)]
2931struct ResponseReplyTarget {
2932    id: RawJsonRpcId,
2933    method: String,
2934    sender: Arc<Mutex<Option<oneshot::Sender<ResponsePayload>>>>,
2935    ordering: ResponseOrdering,
2936    dispatch: ResponseDispatch,
2937}
2938
2939impl ResponseReplyTarget {
2940    fn route(self, result: Result<serde_json::Value, crate::Error>) {
2941        let sender = self
2942            .sender
2943            .lock()
2944            .expect("response reply mutex poisoned")
2945            .take();
2946        let Some(sender) = sender else {
2947            tracing::debug!(
2948                method = %self.method,
2949                id = ?self.id,
2950                "response was already routed to its local awaiter"
2951            );
2952            return;
2953        };
2954
2955        let ack_tx = self.dispatch.acknowledgment(&self.ordering);
2956        if sender.send(ResponsePayload { result, ack_tx }).is_err() {
2957            tracing::debug!(
2958                method = %self.method,
2959                id = ?self.id,
2960                "dropped response because local receiver was gone"
2961            );
2962        }
2963    }
2964}
2965
2966#[derive(Clone, Default)]
2967struct ResponseDispatch {
2968    state: Arc<Mutex<ResponseDispatchState>>,
2969}
2970
2971#[derive(Default)]
2972struct ResponseDispatchState {
2973    complete: bool,
2974    ack_rx: Option<oneshot::Receiver<()>>,
2975}
2976
2977impl ResponseDispatch {
2978    fn acknowledgment(&self, ordering: &ResponseOrdering) -> Option<oneshot::Sender<()>> {
2979        if !ordering.is_ordered() {
2980            return None;
2981        }
2982
2983        let mut state = self.state.lock().expect("response dispatch mutex poisoned");
2984        if state.complete {
2985            return None;
2986        }
2987
2988        let (ack_tx, ack_rx) = oneshot::channel();
2989        let previous_ack = state.ack_rx.replace(ack_rx);
2990        debug_assert!(
2991            previous_ack.is_none(),
2992            "a response dispatch can only be routed once"
2993        );
2994        Some(ack_tx)
2995    }
2996
2997    fn complete(&self) -> Option<oneshot::Receiver<()>> {
2998        let mut state = self.state.lock().expect("response dispatch mutex poisoned");
2999        state.complete = true;
3000        state.ack_rx.take()
3001    }
3002}
3003
3004enum HandlerErrorTarget {
3005    Request(RequestReplyTarget),
3006    Response(ResponseReplyTarget),
3007}
3008
3009impl HandlerErrorTarget {
3010    fn begin_handler_attempt(&self) -> Option<HandlerAttempt> {
3011        match self {
3012            Self::Request(target) => Some(target.destination.begin_handler_attempt()),
3013            Self::Response(_) => None,
3014        }
3015    }
3016}
3017
3018#[derive(Debug)]
3019enum OutgoingMessage {
3020    /// Close the outgoing application queue and acknowledge after every
3021    /// already-accepted message has entered the raw transport queue.
3022    CloseAfterDraining { done: oneshot::Sender<()> },
3023
3024    /// Send a request to the server.
3025    Request {
3026        /// id assigned to this request (generated by sender)
3027        id: RawJsonRpcId,
3028
3029        /// the original method
3030        method: String,
3031
3032        /// The logical message before peer-direction wrapping.
3033        untyped: UntypedMessage,
3034
3035        /// How to transform the logical message for its target peer.
3036        remote_style: crate::role::RemoteStyle,
3037
3038        /// Optional prerequisite that must finish before the request becomes
3039        /// visible on the transport.
3040        readiness: Option<RequestReadiness>,
3041    },
3042
3043    /// Send a notification to the server.
3044    Notification {
3045        /// the message to send; this may have a distinct method
3046        /// depending on the peer
3047        untyped: UntypedMessage,
3048    },
3049
3050    /// Send a response to a message from the server
3051    Response {
3052        id: RawJsonRpcId,
3053
3054        /// Method of the incoming request this response completes.
3055        method: String,
3056
3057        response: Result<serde_json::Value, crate::Error>,
3058
3059        destination: ResponseDestination,
3060    },
3061
3062    /// Send an Error Response that cannot be correlated to a request ID.
3063    UncorrelatedErrorResponse {
3064        error: crate::Error,
3065        destination: ResponseDestination,
3066    },
3067}
3068
3069impl OutgoingMessage {
3070    /// Kind, method, and ID only; params, results, and errors can carry
3071    /// credentials and must not appear in ordinary logs.
3072    fn log_summary(&self) -> (&'static str, Option<&str>, Option<&RawJsonRpcId>) {
3073        match self {
3074            Self::CloseAfterDraining { .. } => ("close_after_draining", None, None),
3075            Self::Request { id, method, .. } => ("request", Some(method), Some(id)),
3076            Self::Notification { untyped } => ("notification", Some(&untyped.method), None),
3077            Self::Response { id, method, .. } => ("response", Some(method), Some(id)),
3078            Self::UncorrelatedErrorResponse { .. } => ("uncorrelated_error_response", None, None),
3079        }
3080    }
3081}
3082
3083/// Return type from JrHandler; indicates whether the request was handled or not.
3084#[must_use]
3085#[derive(Debug)]
3086pub enum Handled<T> {
3087    /// The message was handled
3088    Yes,
3089
3090    /// The message was not handled; returns the original value.
3091    ///
3092    /// If `retry` is true,
3093    No {
3094        /// The message to be passed to subsequent handlers
3095        /// (typically the original message, but it may have been
3096        /// mutated.)
3097        message: T,
3098
3099        /// If true, request the message to be queued and retried with
3100        /// dynamic handlers as they are added.
3101        ///
3102        /// This is used for managing session updates since the dynamic
3103        /// handler for a session cannot be added until the response to the
3104        /// new session request has been processed and there may be updates
3105        /// that get processed at the same time.
3106        retry: bool,
3107    },
3108}
3109
3110/// Trait for converting handler return values into [`Handled`].
3111///
3112/// This trait allows handlers to return either `()` (which becomes `Handled::Yes`)
3113/// or an explicit `Handled<T>` value for more control over handler propagation.
3114pub trait IntoHandled<T> {
3115    /// Convert this value into a `Handled<T>`.
3116    fn into_handled(self) -> Handled<T>;
3117}
3118
3119impl<T> IntoHandled<T> for () {
3120    fn into_handled(self) -> Handled<T> {
3121        Handled::Yes
3122    }
3123}
3124
3125impl<T> IntoHandled<T> for Handled<T> {
3126    fn into_handled(self) -> Handled<T> {
3127        self
3128    }
3129}
3130
3131/// Connection context for sending messages and spawning tasks.
3132///
3133/// This is the primary handle for interacting with the JSON-RPC connection from
3134/// within handler callbacks. You can use it to:
3135///
3136/// * Send requests and notifications to the other side
3137/// * Spawn concurrent tasks that run alongside the connection
3138/// * Respond to requests (via [`Responder`] which wraps this)
3139///
3140/// # Cloning
3141///
3142/// `ConnectionTo` is cheaply cloneable - all clones refer to the same underlying connection.
3143/// This makes it easy to share across async tasks.
3144///
3145/// # Event Loop and Concurrency
3146///
3147/// Handler callbacks run on the event loop, which means the connection cannot process new
3148/// messages while your handler is running. Use [`spawn`](Self::spawn) to offload any
3149/// expensive or blocking work to concurrent tasks.
3150///
3151/// See the [Event Loop and Concurrency](Builder#event-loop-and-concurrency) section
3152/// for more details.
3153#[derive(Clone, Debug)]
3154pub struct ConnectionTo<Counterpart: Role> {
3155    counterpart: Counterpart,
3156    message_tx: OutgoingMessageTx,
3157    task_tx: TaskTx,
3158    dynamic_handler_tx: mpsc::UnboundedSender<DynamicHandlerMessage<Counterpart>>,
3159    transport_completion: SharedTransportCompletion,
3160    pending_replies: PendingRepliesRegistrar,
3161    protocol_mode: ProtocolMode,
3162    incoming_closed: IncomingClosed,
3163    protected_operations: Arc<Mutex<ProtectedOperations>>,
3164    runner_error_scope: Option<run::RunnerErrorScope>,
3165}
3166
3167type SharedTransportCompletion = future::Shared<BoxFuture<'static, Result<(), crate::Error>>>;
3168
3169type SharedCompletionSignal = future::Shared<BoxFuture<'static, ()>>;
3170
3171#[derive(Default)]
3172struct ProtectedOperations {
3173    pending: Vec<oneshot::Receiver<()>>,
3174    joining: Option<SharedCompletionSignal>,
3175}
3176
3177impl Debug for ProtectedOperations {
3178    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3179        formatter
3180            .debug_struct("ProtectedOperations")
3181            .field("pending", &self.pending.len())
3182            .field("joining", &self.joining.is_some())
3183            .finish_non_exhaustive()
3184    }
3185}
3186
3187fn completion_signal() -> (oneshot::Sender<()>, SharedCompletionSignal) {
3188    let (tx, rx) = oneshot::channel();
3189    let signal = async move {
3190        // Dropping a sender (e.g. foreground failure) is not success.
3191        if rx.await.is_err() {
3192            future::pending::<()>().await;
3193        }
3194    }
3195    .boxed()
3196    .shared();
3197    (tx, signal)
3198}
3199
3200#[derive(Clone)]
3201struct IncomingClosed {
3202    state: Arc<IncomingClosedState>,
3203}
3204
3205struct IncomingClosedState {
3206    closing: AtomicBool,
3207    closed: AtomicBool,
3208    signal_tx: Mutex<Option<oneshot::Sender<()>>>,
3209    signal_rx: future::Shared<BoxFuture<'static, ()>>,
3210    shutdown_tx: Mutex<Option<oneshot::Sender<()>>>,
3211    #[cfg(any(feature = "unstable_mcp_over_acp", test))]
3212    shutdown_rx: SharedCompletionSignal,
3213    termination: Mutex<Option<ConnectionTermination>>,
3214    terminated_tx: Mutex<Option<oneshot::Sender<()>>>,
3215    terminated_rx: SharedCompletionSignal,
3216}
3217
3218impl IncomingClosed {
3219    fn new() -> Self {
3220        let (signal_tx, signal_rx) = oneshot::channel();
3221        let (shutdown_tx, shutdown_rx) = oneshot::channel();
3222        #[cfg(not(any(feature = "unstable_mcp_over_acp", test)))]
3223        drop(shutdown_rx);
3224        let (terminated_tx, terminated_rx) = oneshot::channel();
3225        Self {
3226            state: Arc::new(IncomingClosedState {
3227                closing: AtomicBool::new(false),
3228                closed: AtomicBool::new(false),
3229                signal_tx: Mutex::new(Some(signal_tx)),
3230                signal_rx: signal_rx.map(|_| ()).boxed().shared(),
3231                shutdown_tx: Mutex::new(Some(shutdown_tx)),
3232                #[cfg(any(feature = "unstable_mcp_over_acp", test))]
3233                shutdown_rx: shutdown_rx.map(|_| ()).boxed().shared(),
3234                termination: Mutex::new(None),
3235                terminated_tx: Mutex::new(Some(terminated_tx)),
3236                terminated_rx: terminated_rx.map(|_| ()).boxed().shared(),
3237            }),
3238        }
3239    }
3240
3241    fn begin_close(&self) {
3242        self.state.closing.store(true, Ordering::Release);
3243        self.request_shutdown();
3244    }
3245
3246    fn request_shutdown(&self) {
3247        if let Some(tx) = self
3248            .state
3249            .shutdown_tx
3250            .lock()
3251            .expect("shutdown signal mutex poisoned")
3252            .take()
3253        {
3254            let _ = tx.send(());
3255        }
3256    }
3257
3258    /// Whether the connection has begun shutting down (incoming EOF, a
3259    /// finished foreground, an actor error) or has already terminated.
3260    fn is_shutting_down(&self) -> bool {
3261        self.state
3262            .shutdown_tx
3263            .lock()
3264            .expect("shutdown signal mutex poisoned")
3265            .is_none()
3266            || self.termination().is_some()
3267    }
3268
3269    fn finish_close(&self) {
3270        self.state.closed.store(true, Ordering::Release);
3271        let signal_tx = self
3272            .state
3273            .signal_tx
3274            .lock()
3275            .expect("incoming-close signal mutex poisoned")
3276            .take();
3277
3278        if let Some(signal_tx) = signal_tx {
3279            let _ = signal_tx.send(());
3280        }
3281    }
3282
3283    async fn closed(&self) {
3284        self.state.signal_rx.clone().await;
3285    }
3286
3287    fn is_closed(&self) -> bool {
3288        self.state.closed.load(Ordering::Acquire)
3289    }
3290
3291    fn is_closing(&self) -> bool {
3292        self.state.closing.load(Ordering::Acquire)
3293    }
3294
3295    /// Record the termination reason. Returns `false` if one was already set.
3296    fn set_termination(&self, termination: ConnectionTermination) -> bool {
3297        let mut slot = self
3298            .state
3299            .termination
3300            .lock()
3301            .expect("termination mutex poisoned");
3302        if slot.is_some() {
3303            return false;
3304        }
3305        *slot = Some(termination);
3306        true
3307    }
3308
3309    fn signal_terminated(&self) {
3310        if let Some(tx) = self
3311            .state
3312            .terminated_tx
3313            .lock()
3314            .expect("terminated signal mutex poisoned")
3315            .take()
3316        {
3317            let _ = tx.send(());
3318        }
3319    }
3320
3321    fn termination(&self) -> Option<ConnectionTermination> {
3322        self.state
3323            .termination
3324            .lock()
3325            .expect("termination mutex poisoned")
3326            .clone()
3327    }
3328
3329    async fn terminated(&self) -> ConnectionTermination {
3330        self.state.terminated_rx.clone().await;
3331        self.termination()
3332            .expect("termination is recorded before it is signalled")
3333    }
3334}
3335
3336/// Publishes the connection's termination exactly once: when the driver
3337/// completes via [`Self::finish`], or synchronously when the driver future is
3338/// dropped first.
3339struct TerminationGuard {
3340    incoming_closed: IncomingClosed,
3341    pending_replies: PendingReplies,
3342}
3343
3344impl TerminationGuard {
3345    fn finish(self, termination: ConnectionTermination) {
3346        self.publish(termination);
3347    }
3348
3349    fn publish(&self, termination: ConnectionTermination) {
3350        if !self.incoming_closed.set_termination(termination.clone()) {
3351            return;
3352        }
3353        // Record first, so a requester woken by its failure observes the
3354        // termination; then fail requests before waking `terminated()`.
3355        let pending_reply_count = self.pending_replies.terminate(&termination);
3356        tracing::debug!(
3357            termination = termination.kind(),
3358            pending_reply_count,
3359            "Connection terminated"
3360        );
3361        self.incoming_closed.signal_terminated();
3362    }
3363}
3364
3365impl Drop for TerminationGuard {
3366    fn drop(&mut self) {
3367        // No-op after `finish`.
3368        self.publish(ConnectionTermination::Dropped);
3369    }
3370}
3371
3372impl Debug for IncomingClosed {
3373    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3374        formatter
3375            .debug_struct("IncomingClosed")
3376            .field("is_closing", &self.is_closing())
3377            .field("is_closed", &self.is_closed())
3378            .finish_non_exhaustive()
3379    }
3380}
3381
3382/// Stable discriminator stored in the `data.reason` field of errors produced
3383/// when the incoming transport reaches clean EOF before a request receives its
3384/// response.
3385///
3386/// The `data` field is informational. Use [`is_incoming_transport_closed`] to
3387/// detect these errors: a peer can send this value in its own error data.
3388pub const INCOMING_TRANSPORT_CLOSED_REASON: &str = "incoming_transport_closed";
3389
3390/// Return whether `error` reports that the incoming transport reached clean
3391/// EOF before a request received its response.
3392///
3393/// Only errors the SDK produced for its own connection match. An error
3394/// response received from a peer never does, even when its `data.reason` is
3395/// [`INCOMING_TRANSPORT_CLOSED_REASON`], and neither does an error built from
3396/// the same code, message, and data.
3397#[must_use]
3398pub fn is_incoming_transport_closed(error: &crate::Error) -> bool {
3399    error.origin == crate::error::ErrorOrigin::IncomingTransportClosed
3400}
3401
3402fn incoming_transport_closed_error(method: &str) -> crate::Error {
3403    let mut error = crate::Error::internal_error();
3404    error.message = "Incoming transport closed".to_string();
3405    error.origin = crate::error::ErrorOrigin::IncomingTransportClosed;
3406    error.data(serde_json::json!({
3407        "reason": INCOMING_TRANSPORT_CLOSED_REASON,
3408        "method": method,
3409    }))
3410}
3411
3412/// Unlike the cleanup coordinator below, check success before polling delivery:
3413/// an already-ready success must not resume a message handler into another
3414/// dispatch.
3415fn run_incoming_until_foreground_succeeds(
3416    incoming: impl Future<Output = Result<(), crate::Error>>,
3417    foreground_succeeded: SharedCompletionSignal,
3418    incoming_closed: IncomingClosed,
3419) -> impl Future<Output = Result<(), crate::Error>> {
3420    let mut incoming = Box::pin(incoming);
3421    future::poll_fn(move |cx| {
3422        if foreground_succeeded.clone().poll_unpin(cx).is_ready() && !incoming_closed.is_closing() {
3423            return std::task::Poll::Ready(Ok(()));
3424        }
3425        // A close callback already underway is protected. Its result is polled
3426        // before stopping, so callback errors retain their existing precedence.
3427        incoming.as_mut().poll(cx)
3428    })
3429}
3430
3431/// Run the connection background alongside its foreground while ensuring that
3432/// a foreground woken by incoming EOF cannot cancel close callbacks midway.
3433fn run_until_connection_close<R>(
3434    background: impl Future<Output = Result<(), crate::Error>>,
3435    foreground: impl Future<Output = Result<R, crate::Error>>,
3436    incoming_closed: IncomingClosed,
3437) -> impl Future<Output = Result<R, crate::Error>> {
3438    // Box these before constructing the returned future. Keeping the generic
3439    // connection actors directly in this async state would substantially grow
3440    // every `connect_*` future.
3441    let background = Box::pin(background);
3442    let foreground = Box::pin(foreground);
3443
3444    async move {
3445        match future::select(background, foreground).await {
3446            Either::Left((background_result, foreground)) => {
3447                background_result?;
3448                foreground.await
3449            }
3450            Either::Right((foreground_result, background)) => {
3451                if !incoming_closed.is_closing() {
3452                    return foreground_result;
3453                }
3454
3455                match future::select(background, Box::pin(incoming_closed.closed())).await {
3456                    Either::Left((background_result, _)) => {
3457                        background_result?;
3458                        foreground_result
3459                    }
3460                    Either::Right(((), background)) => {
3461                        // Poll the background first once more so an error returned
3462                        // by the just-finished close callback wins over the ready
3463                        // foreground result.
3464                        crate::util::run_until(background, future::ready(foreground_result)).await
3465                    }
3466                }
3467            }
3468        }
3469    }
3470}
3471
3472impl<Counterpart: Role> ConnectionTo<Counterpart> {
3473    fn new(
3474        counterpart: Counterpart,
3475        message_tx: mpsc::UnboundedSender<OutgoingMessage>,
3476        task_tx: mpsc::UnboundedSender<Task>,
3477        dynamic_handler_tx: mpsc::UnboundedSender<DynamicHandlerMessage<Counterpart>>,
3478        transport_completion: SharedTransportCompletion,
3479        pending_replies: PendingRepliesRegistrar,
3480        protocol_mode: ProtocolMode,
3481    ) -> Self {
3482        Self {
3483            counterpart,
3484            message_tx,
3485            task_tx,
3486            dynamic_handler_tx,
3487            transport_completion,
3488            pending_replies,
3489            protocol_mode,
3490            incoming_closed: IncomingClosed::new(),
3491            protected_operations: Arc::default(),
3492            runner_error_scope: None,
3493        }
3494    }
3495
3496    pub(crate) fn with_runner_error_scope(mut self, scope: run::RunnerErrorScope) -> Self {
3497        self.runner_error_scope = Some(scope);
3498        self
3499    }
3500
3501    pub(crate) fn finish_runner_error(
3502        &self,
3503        error: crate::Error,
3504    ) -> impl Future<Output = ()> + Send + '_ {
3505        if let Some(scope) = &self.runner_error_scope {
3506            Either::Left(scope.finish(error))
3507        } else {
3508            // Unscoped runners belong to the connection itself.
3509            self.request_shutdown();
3510            Either::Right(self.wait_protected_operations())
3511        }
3512    }
3513
3514    /// Spawn only a connection-owned supervisor whose async cleanup must finish
3515    /// before the driver returns. Ordinary application work must use `spawn`.
3516    #[cfg(any(feature = "unstable_mcp_over_acp", test))]
3517    #[track_caller]
3518    pub(crate) fn spawn_protected(
3519        &self,
3520        task: impl IntoFuture<Output = Result<(), crate::Error>, IntoFuture: Send + 'static>,
3521    ) -> Result<(), crate::Error> {
3522        let mut state = self
3523            .protected_operations
3524            .lock()
3525            .expect("protected operations mutex poisoned");
3526        if state.joining.is_some() {
3527            return Err(crate::Error::request_cancelled());
3528        }
3529        // Reap completed acknowledgments at admission, rather than retaining
3530        // every operation for the entire lifetime of the connection.
3531        state
3532            .pending
3533            .retain_mut(|done| matches!(done.try_recv(), Ok(None)));
3534        let (done_tx, done_rx) = oneshot::channel();
3535        let task = task.into_future();
3536        self.spawn(async move {
3537            let result = task.await;
3538            let _ = done_tx.send(());
3539            result
3540        })?;
3541        state.pending.push(done_rx);
3542        Ok(())
3543    }
3544
3545    pub(crate) async fn wait_protected_operations(&self) {
3546        let joining = {
3547            let mut state = self
3548                .protected_operations
3549                .lock()
3550                .expect("protected operations mutex poisoned");
3551            if state.joining.is_none() {
3552                let operations = std::mem::take(&mut state.pending);
3553                state.joining = Some(
3554                    async move {
3555                        for operation in operations {
3556                            let _ = operation.await;
3557                        }
3558                    }
3559                    .boxed()
3560                    .shared(),
3561                );
3562            }
3563            state.joining.as_ref().expect("join initialized").clone()
3564        };
3565        joining.await;
3566    }
3567
3568    pub(crate) fn request_shutdown(&self) {
3569        self.incoming_closed.request_shutdown();
3570    }
3571
3572    /// Early cancellation for owned native work, before close callbacks or drain.
3573    #[cfg(any(feature = "unstable_mcp_over_acp", test))]
3574    pub(crate) async fn shutdown_requested(&self) {
3575        self.incoming_closed.state.shutdown_rx.clone().await;
3576    }
3577
3578    /// Return the counterpart role this connection is talking to.
3579    pub fn counterpart(&self) -> Counterpart {
3580        self.counterpart.clone()
3581    }
3582
3583    /// Wait until the incoming transport reaches clean EOF.
3584    ///
3585    /// Transport closure means that no more messages or responses can arrive.
3586    /// Pending requests are failed first; this completes after registered
3587    /// [`Builder::on_close`] callbacks finish.
3588    /// It does not automatically cancel the future passed to
3589    /// [`Builder::connect_with`]; use [`Builder::on_close`] when the connection
3590    /// should run application-specific cleanup or terminate that future.
3591    ///
3592    /// This never completes if the connection ends some other way; use
3593    /// [`terminated`](Self::terminated) to observe every termination.
3594    pub async fn incoming_closed(&self) {
3595        self.incoming_closed.closed().await;
3596    }
3597
3598    /// Return whether clean incoming-EOF processing has completed.
3599    ///
3600    /// This remains `false` while [`Builder::on_close`] callbacks are running.
3601    #[must_use]
3602    pub fn is_incoming_closed(&self) -> bool {
3603        self.incoming_closed.is_closed()
3604    }
3605
3606    /// Wait until the connection driver has terminated, for any reason.
3607    ///
3608    /// This is the universal terminal event for a connection driven by
3609    /// [`Builder::connect_to`] or [`Builder::connect_with`]. Unlike
3610    /// [`incoming_closed`](Self::incoming_closed), it also completes after
3611    /// transport errors, handler or close-callback errors, foreground
3612    /// completion, and a dropped driver future.
3613    ///
3614    /// The termination is published once, synchronously, as the driver future
3615    /// returns (or is dropped). At that point:
3616    ///
3617    /// - No further handler, close callback, runner, or
3618    ///   [`spawn`](Self::spawn)ed task of this connection will run; each has
3619    ///   completed or been dropped.
3620    /// - Every request still awaiting a response has been failed. Requests
3621    ///   failed earlier by clean incoming EOF satisfy
3622    ///   [`is_incoming_transport_closed`](crate::is_incoming_transport_closed);
3623    ///   the rest satisfy [`is_connection_terminated`](crate::is_connection_terminated),
3624    ///   as do requests sent afterwards.
3625    ///
3626    /// Do not await this from inside the connection's own handlers, close
3627    /// callbacks, or tasks: termination happens only after they finish.
3628    ///
3629    /// Termination does not reap child processes owned by the transport, nor
3630    /// drain application-owned queues.
3631    pub async fn terminated(&self) -> ConnectionTermination {
3632        self.incoming_closed.terminated().await
3633    }
3634
3635    /// Return the termination reason if the connection driver has terminated.
3636    ///
3637    /// See [`terminated`](Self::terminated).
3638    #[must_use]
3639    pub fn termination(&self) -> Option<ConnectionTermination> {
3640        self.incoming_closed.termination()
3641    }
3642
3643    /// Stop accepting outgoing messages, drain routable output through the
3644    /// protocol actor, and finish cooperative physical sinks. Reactive serving also
3645    /// joins owned transport work after incoming EOF.
3646    async fn drain_outgoing(
3647        &self,
3648        finish: Option<crate::component::FinishControl>,
3649        wait_owned_transport: bool,
3650    ) -> Result<(), crate::Error> {
3651        let (done_tx, done_rx) = oneshot::channel();
3652        let marker_result = send_raw_message(
3653            &self.message_tx,
3654            OutgoingMessage::CloseAfterDraining { done: done_tx },
3655        );
3656        let marker_result = match marker_result {
3657            Ok(()) => done_rx.await.map_err(|error| {
3658                crate::util::internal_error(format!(
3659                    "outgoing drain marker was dropped before completion: {error}"
3660                ))
3661            }),
3662            Err(error) => Err(error),
3663        };
3664
3665        let physical_finish = finish.is_some();
3666        if let Some(mut finish) = finish {
3667            // Only finish the physical sink after the protocol actor has handed
3668            // off its accepted output. Closing it earlier races the drain.
3669            finish.request();
3670        }
3671        if physical_finish || wait_owned_transport {
3672            // Cooperative completion proves physical sink drain. Reactive serving
3673            // also waits for owned work after EOF (e.g. child exit status).
3674            self.transport_completion.clone().await?;
3675        }
3676        // Opaque application drivers have no physical finish contract. Keep
3677        // polling their errors in the background, but do not globally join work
3678        // which may intentionally run forever after the foreground returns.
3679        marker_result
3680    }
3681
3682    fn is_incoming_closing(&self) -> bool {
3683        self.incoming_closed.is_closing()
3684    }
3685
3686    pub(super) fn begin_incoming_close(&self) {
3687        self.incoming_closed.begin_close();
3688    }
3689
3690    pub(super) fn finish_incoming_close(&self) {
3691        self.incoming_closed.finish_close();
3692    }
3693
3694    /// Spawns a task that will run so long as the JSON-RPC connection is being served.
3695    ///
3696    /// This is the primary mechanism for offloading expensive work from handler callbacks
3697    /// to avoid blocking the event loop. Spawned tasks run concurrently with the connection,
3698    /// allowing the server to continue processing messages.
3699    ///
3700    /// # Event Loop
3701    ///
3702    /// Handler callbacks run on the event loop, which cannot process new messages while
3703    /// your handler is running. Use `spawn` for any expensive operations:
3704    ///
3705    /// ```no_run
3706    /// # use agent_client_protocol_test::*;
3707    /// # async fn example() -> Result<(), agent_client_protocol::Error> {
3708    /// # let connection = mock_connection();
3709    /// connection.on_receive_request(async |req: ProcessRequest, responder, cx| {
3710    ///     // Clone cx for the spawned task
3711    ///     cx.spawn({
3712    ///         let connection = cx.clone();
3713    ///         async move {
3714    ///             let result = expensive_operation(&req.data).await?;
3715    ///             connection.send_notification(ProcessComplete { result })?;
3716    ///             Ok(())
3717    ///         }
3718    ///     })?;
3719    ///
3720    ///     // Respond immediately
3721    ///     responder.respond(ProcessResponse { result: "started".into() })
3722    /// }, agent_client_protocol::on_receive_request!())
3723    /// # .connect_to(agent_client_protocol_test::MockTransport).await?;
3724    /// # Ok(())
3725    /// # }
3726    /// ```
3727    ///
3728    /// # Errors
3729    ///
3730    /// If the spawned task returns an error, the entire server will shut down.
3731    #[track_caller]
3732    pub fn spawn(
3733        &self,
3734        task: impl IntoFuture<Output = Result<(), crate::Error>, IntoFuture: Send + 'static>,
3735    ) -> Result<(), crate::Error> {
3736        let location = std::panic::Location::caller();
3737        let task = task.into_future();
3738        Task::new(location, task).spawn(&self.task_tx)
3739    }
3740
3741    /// Spawn a JSON-RPC connection in the background and return the
3742    /// connection context its builder selects.
3743    ///
3744    /// This is useful for creating multiple connections that communicate with each other,
3745    /// such as implementing proxy patterns or connecting to multiple backend services.
3746    ///
3747    /// # Arguments
3748    ///
3749    /// - `builder`: The connection builder with handlers configured
3750    /// - `transport`: The transport component to connect to
3751    ///
3752    /// # Returns
3753    ///
3754    /// The connection type that `builder`'s callbacks receive: a raw
3755    /// [`ConnectionTo`] for a [`Raw`] builder such as [`Builder::new`], a
3756    /// [`v1::ConnectionTo`](crate::v1::ConnectionTo) for
3757    /// [`Client.v1()`](crate::Client::v1), and a `v2::ConnectionTo` for
3758    /// `Client.v2()`. Convert a typed connection back with `into_raw`.
3759    ///
3760    /// # Example: Proxying to a backend connection
3761    ///
3762    /// ```
3763    /// # use agent_client_protocol::UntypedRole;
3764    /// # use agent_client_protocol::{Builder, ConnectionTo};
3765    /// # use agent_client_protocol_test::*;
3766    /// # async fn example(cx: ConnectionTo<UntypedRole>) -> Result<(), agent_client_protocol::Error> {
3767    /// // Set up a backend connection builder
3768    /// let backend = UntypedRole.builder()
3769    ///     .on_receive_request(async |req: MyRequest, responder, _cx| {
3770    ///         responder.respond(MyResponse { status: "ok".into() })
3771    ///     }, agent_client_protocol::on_receive_request!());
3772    ///
3773    /// // Spawn it and get a context to send requests to it
3774    /// let backend_connection = cx.spawn_connection(backend, MockTransport)?;
3775    ///
3776    /// // Now you can forward requests to the backend
3777    /// let response = backend_connection.send_request(MyRequest {}).block_task().await?;
3778    /// # Ok(())
3779    /// # }
3780    /// ```
3781    ///
3782    /// # Example: Spawning a v1 client
3783    ///
3784    /// ```no_run
3785    /// # use agent_client_protocol::{
3786    /// #     Agent, Client, ConnectTo, ConnectionTo, Error, UntypedRole, v1,
3787    /// # };
3788    /// # fn example(
3789    /// #     connection: ConnectionTo<UntypedRole>,
3790    /// #     transport: impl ConnectTo<Client> + 'static,
3791    /// # ) -> Result<(), Error> {
3792    /// let child: v1::ConnectionTo<Agent> = connection.spawn_connection(Client.v1(), transport)?;
3793    /// # drop(child);
3794    /// # Ok(())
3795    /// # }
3796    /// ```
3797    #[track_caller]
3798    pub fn spawn_connection<R: Role, P: Protocol>(
3799        &self,
3800        builder: Builder<
3801            R,
3802            impl HandleDispatchFrom<R::Counterpart> + 'static,
3803            impl RunWithConnectionTo<R::Counterpart> + 'static,
3804            impl HandleConnectionClose<R::Counterpart> + 'static,
3805            P,
3806        >,
3807        transport: impl ConnectTo<R> + 'static,
3808    ) -> Result<P::Connection<R::Counterpart>, crate::Error> {
3809        let (connection, future) =
3810            builder.into_connection_and_future(transport, false, |_| std::future::pending());
3811        Task::new(std::panic::Location::caller(), future).spawn(&self.task_tx)?;
3812        Ok(protocol::connection_from_raw::<P, _>(connection))
3813    }
3814
3815    /// The ACP protocol version of this connection's wire guard, or `None`
3816    /// when its builder applies no guard, as with [`Builder::new`].
3817    ///
3818    /// `Client.v1()`, `Agent.v1()` and `Proxy.v1()` connections report
3819    /// [`ProtocolVersion::V1`](crate::schema::ProtocolVersion::V1), and the
3820    /// `v2()` entry points report `ProtocolVersion::V2`.
3821    #[must_use]
3822    pub fn protocol_version(&self) -> Option<crate::schema::ProtocolVersion> {
3823        self.protocol_mode.api_protocol_version()
3824    }
3825
3826    /// The same connection, typed for protocol `P`.
3827    ///
3828    /// `into_protocol::<V1>()` returns a [`v1::ConnectionTo`](crate::v1::ConnectionTo)
3829    /// (and, with `unstable_protocol_v2`, `into_protocol::<V2>()` a
3830    /// `v2::ConnectionTo`), whose sends return request handles typed for that
3831    /// version and which carries that version's session helpers. Only the
3832    /// Rust API changes: the connection's wire guard is the one its builder
3833    /// selected. The versioned connections convert back with `into_raw`.
3834    ///
3835    /// # Errors
3836    ///
3837    /// Returns an Internal error (`-32603`) when the builder's guard selected
3838    /// a different version than `P`, for example `into_protocol::<V2>()` on a
3839    /// connection from `Client.v1()`. The mismatch is a local programming
3840    /// error, not a malformed message from the peer. A
3841    /// connection whose builder applies no guard (see
3842    /// [`protocol_version`](Self::protocol_version)) converts to every
3843    /// protocol, and `into_protocol::<Raw>()` never fails.
3844    ///
3845    /// ```
3846    /// # use agent_client_protocol::{Agent, ConnectionTo, Error, V1, v1};
3847    /// fn sessions(connection: ConnectionTo<Agent>) -> Result<v1::ConnectionTo<Agent>, Error> {
3848    ///     connection.into_protocol::<V1>()
3849    /// }
3850    /// ```
3851    pub fn into_protocol<P: Protocol>(self) -> Result<P::Connection<Counterpart>, crate::Error> {
3852        if let (Some(guard), Some(requested)) =
3853            (self.protocol_version(), protocol::protocol_version::<P>())
3854            && guard != requested
3855        {
3856            return Err(crate::Error::internal_error().data(format!(
3857                "cannot use a connection guarded for ACP protocol version {guard} \
3858                 as a protocol version {requested} connection",
3859            )));
3860        }
3861        Ok(protocol::connection_from_raw::<P, _>(self))
3862    }
3863
3864    /// Send a request/notification and forward the response appropriately.
3865    ///
3866    /// The request context's response type matches the request's response type,
3867    /// enabling type-safe message forwarding.
3868    pub fn send_proxied_message<
3869        Req: JsonRpcRequest<Response: Send>,
3870        Notif: JsonRpcNotification,
3871        Q: Protocol,
3872    >(
3873        &self,
3874        message: Dispatch<Req, Notif, Q>,
3875    ) -> Result<(), crate::Error>
3876    where
3877        Counterpart: HasPeer<Counterpart>,
3878    {
3879        self.send_proxied_message_to(self.counterpart(), message)
3880    }
3881
3882    /// Send a request/notification and forward the response appropriately.
3883    ///
3884    /// The request context's response type matches the request's response type,
3885    /// enabling type-safe message forwarding.
3886    ///
3887    /// `$/cancel_request` notifications are *not* forwarded: their `requestId`
3888    /// refers to a request on the connection they arrived over and would be
3889    /// meaningless to `peer`. Cancellation instead propagates hop by hop,
3890    /// because the responders passed to
3891    /// [`forward_response_to`](SentRequest::forward_response_to) observe it
3892    /// and re-issue the cancellation with the forwarded request's own ID.
3893    pub fn send_proxied_message_to<
3894        Peer: Role,
3895        Req: JsonRpcRequest<Response: Send>,
3896        Notif: JsonRpcNotification,
3897        Q: Protocol,
3898    >(
3899        &self,
3900        peer: Peer,
3901        message: Dispatch<Req, Notif, Q>,
3902    ) -> Result<(), crate::Error>
3903    where
3904        Counterpart: HasPeer<Peer>,
3905    {
3906        match message {
3907            Dispatch::Request(request, responder) => self
3908                .send_ordered_request_to::<Raw, _, _>(peer, request)
3909                .forward_response_to(responder),
3910            Dispatch::Notification(notification) => {
3911                // `$/cancel_request` is connection-scoped: its `requestId` was
3912                // allocated on the connection the notification arrived over
3913                // and means nothing to `peer`. The cancellation has already
3914                // been recorded on this connection's responder markers, and
3915                // `forward_response_to` re-issues it for the forwarded request
3916                // with the correct per-hop ID, so drop the raw notification
3917                // instead of tunneling a meaningless ID across the hop.
3918                if is_cancel_request_notification(&notification) {
3919                    tracing::debug!(
3920                        "not forwarding hop-scoped `$/cancel_request` notification across proxy hop"
3921                    );
3922                    return Ok(());
3923                }
3924                self.send_notification_to(peer, notification)
3925            }
3926            Dispatch::Response(result, router) => {
3927                // Responses are forwarded directly to their destination
3928                router.route_with_result(result)
3929            }
3930        }
3931    }
3932
3933    /// Send an outgoing request and return a [`SentRequest`] for handling the reply.
3934    ///
3935    /// The returned [`SentRequest`] makes the response-consumption mode explicit:
3936    ///
3937    /// * [`on_receiving_result`](SentRequest::on_receiving_result) - Register a callback and
3938    ///   return immediately. If registered before the response is routed during its original
3939    ///   dispatch, the loop waits for the callback to complete.
3940    /// * [`block_task`](SentRequest::block_task) - Wait on the current task until the response
3941    ///   arrives. This is only safe when that task already runs outside the dispatch loop.
3942    ///
3943    /// For callback ordering selected before publication, use
3944    /// [`prepare_request`](Self::prepare_request) instead. Even an immediately
3945    /// chained callback can race with a fast response on a concurrent connection.
3946    ///
3947    /// # Anti-Footgun Design
3948    ///
3949    /// The API intentionally makes it difficult to block on the result directly to prevent
3950    /// the common mistake of blocking the event loop while waiting for a response:
3951    ///
3952    /// ```compile_fail
3953    /// # use agent_client_protocol_test::*;
3954    /// # async fn example(cx: agent_client_protocol::ConnectionTo<agent_client_protocol::UntypedRole>) -> Result<(), agent_client_protocol::Error> {
3955    /// // ❌ This doesn't compile - prevents blocking the event loop
3956    /// let response = cx.send_request(MyRequest {}).await?;
3957    /// # Ok(())
3958    /// # }
3959    /// ```
3960    ///
3961    /// ```no_run
3962    /// # use agent_client_protocol_test::*;
3963    /// # async fn example(cx: agent_client_protocol::ConnectionTo<agent_client_protocol::UntypedRole>) -> Result<(), agent_client_protocol::Error> {
3964    /// // ✅ Option 1: Register an ordered callback (safe in handlers)
3965    /// cx.send_request(MyRequest {})
3966    ///     .on_receiving_result(async |result| {
3967    ///         // Handle the response
3968    ///         Ok(())
3969    ///     })?;
3970    ///
3971    /// // ✅ Option 2: Block in spawned task (safe because task is concurrent)
3972    /// cx.spawn({
3973    ///     let cx = cx.clone();
3974    ///     async move {
3975    ///         let response = cx.send_request(MyRequest {})
3976    ///             .block_task()
3977    ///             .await?;
3978    ///         // Process response...
3979    ///         Ok(())
3980    ///     }
3981    /// })?;
3982    /// # Ok(())
3983    /// # }
3984    /// ```
3985    /// Send an outgoing request to the default counterpart peer.
3986    ///
3987    /// This is a convenience method that sends to the counterpart role `R`.
3988    /// For explicit control over the target peer, use [`send_request_to`](Self::send_request_to).
3989    pub fn send_request<Req: JsonRpcRequest>(&self, request: Req) -> SentRequest<Req::Response>
3990    where
3991        Counterpart: HasPeer<Counterpart>,
3992    {
3993        self.send_request_to(self.counterpart.clone(), request)
3994    }
3995
3996    /// Send an outgoing request to a specific peer.
3997    ///
3998    /// The message will be transformed according to the [`HasPeer`](crate::role::HasPeer)
3999    /// implementation before being sent.
4000    pub fn send_request_to<Peer: Role, Req: JsonRpcRequest>(
4001        &self,
4002        peer: Peer,
4003        request: Req,
4004    ) -> SentRequest<Req::Response>
4005    where
4006        Counterpart: HasPeer<Peer>,
4007    {
4008        self.send_request_to_with_options(peer, request, false, None, None)
4009    }
4010
4011    /// Prepare a request without sending it until response handling is selected.
4012    ///
4013    /// Unlike [`send_request`](Self::send_request), this does not register a
4014    /// pending reply or enqueue the request. A consuming method on the returned
4015    /// [`PreparedRequest`] publishes it synchronously. Callback-style methods
4016    /// select ordered consumption before publication, closing the race with a
4017    /// fast peer response even when the connection runs on another task.
4018    ///
4019    /// Dropping the prepared request sends nothing. See [`PreparedRequest`] for
4020    /// the available consumption modes and their error and cancellation behavior.
4021    ///
4022    /// # Examples
4023    ///
4024    /// ```no_run
4025    /// # use agent_client_protocol::{ConnectionTo, Error, UntypedRole};
4026    /// # use agent_client_protocol_test::MyRequest;
4027    /// # fn example(connection: ConnectionTo<UntypedRole>) -> Result<(), Error> {
4028    /// connection.prepare_request(MyRequest {}).on_receiving_result(async |result| {
4029    ///     let response = result?;
4030    ///     // Apply bounded response work before later inbound messages.
4031    ///     Ok(())
4032    /// })?;
4033    /// # Ok(())
4034    /// # }
4035    /// ```
4036    pub fn prepare_request<Req: JsonRpcRequest>(
4037        &self,
4038        request: Req,
4039    ) -> PreparedRequest<Req::Response>
4040    where
4041        Counterpart: HasPeer<Counterpart>,
4042    {
4043        self.prepare_request_to(self.counterpart.clone(), request)
4044    }
4045
4046    /// Prepare a request to a specific peer without sending it.
4047    ///
4048    /// The request is serialized now. A consuming method synchronously registers
4049    /// its pending reply and enqueues the request; peer transformation and
4050    /// transmission happen later in the connection driver.
4051    /// See [`prepare_request`](Self::prepare_request).
4052    pub fn prepare_request_to<Peer: Role, Req: JsonRpcRequest>(
4053        &self,
4054        peer: Peer,
4055        request: Req,
4056    ) -> PreparedRequest<Req::Response>
4057    where
4058        Counterpart: HasPeer<Peer>,
4059    {
4060        self.prepare_request_to_with_options(peer, request, None, None)
4061    }
4062
4063    /// Send a request and run a synchronous side effect when its valid success
4064    /// response is routed, after `before_send` completes and independently
4065    /// from how the returned request is eventually consumed.
4066    #[cfg(feature = "unstable_protocol_v2")]
4067    pub(crate) fn send_request_to_with_response_hook_after<
4068        P: Protocol,
4069        Peer: Role,
4070        Req: JsonRpcRequest,
4071        BeforeSend: Future<Output = Result<(), crate::Error>> + Send + 'static,
4072    >(
4073        &self,
4074        peer: Peer,
4075        request: Req,
4076        before_send: BeforeSend,
4077        response_hook: impl FnOnce(&Req::Response) -> Result<(), crate::Error> + Send + 'static,
4078    ) -> SentRequest<Req::Response, P>
4079    where
4080        Counterpart: HasPeer<Peer>,
4081    {
4082        let hook: ResponseRouteHook = Box::new(move |method, value| {
4083            let response = Req::Response::from_json(method, value.clone())?;
4084            response_hook(&response)
4085        });
4086        self.send_request_to_with_options(
4087            peer,
4088            request,
4089            false,
4090            Some(RequestReadiness::new(before_send)),
4091            Some(hook),
4092        )
4093    }
4094
4095    /// Send an ordered request with readiness and valid-success hooks.
4096    #[cfg(feature = "unstable_protocol_v2")]
4097    pub(crate) fn send_ordered_request_to_with_response_hook_after<
4098        P: Protocol,
4099        Peer: Role,
4100        Req: JsonRpcRequest,
4101        BeforeSend: Future<Output = Result<(), crate::Error>> + Send + 'static,
4102    >(
4103        &self,
4104        peer: Peer,
4105        request: Req,
4106        before_send: BeforeSend,
4107        response_hook: impl FnOnce(&Req::Response) -> Result<(), crate::Error> + Send + 'static,
4108    ) -> SentRequest<Req::Response, P>
4109    where
4110        Counterpart: HasPeer<Peer>,
4111    {
4112        let hook: ResponseRouteHook = Box::new(move |method, value| {
4113            let response = Req::Response::from_json(method, value.clone())?;
4114            response_hook(&response)
4115        });
4116        self.send_request_to_with_options(
4117            peer,
4118            request,
4119            true,
4120            Some(RequestReadiness::new(before_send)),
4121            Some(hook),
4122        )
4123    }
4124
4125    /// Send a request whose callback must run before later inbound messages.
4126    ///
4127    /// The ordering marker is installed before the request enters the outgoing
4128    /// queue, closing the race between a fast peer response and the immediate
4129    /// [`SentRequest::on_receiving_result`] call. Callers must consume the
4130    /// returned request with a callback-style method without yielding.
4131    pub(crate) fn send_ordered_request_to<P: Protocol, Peer: Role, Req: JsonRpcRequest>(
4132        &self,
4133        peer: Peer,
4134        request: Req,
4135    ) -> SentRequest<Req::Response, P>
4136    where
4137        Counterpart: HasPeer<Peer>,
4138    {
4139        self.send_request_to_with_options(peer, request, true, None, None)
4140    }
4141
4142    /// Send an ordered request after `before_send` completes successfully.
4143    ///
4144    /// The ordering marker and readiness prerequisite are both registered
4145    /// before the request enters the outgoing queue. This is used by framework
4146    /// setup paths that must acknowledge local routing before the peer can
4147    /// observe the request.
4148    pub(crate) fn send_ordered_request_to_after<
4149        P: Protocol,
4150        Peer: Role,
4151        Req: JsonRpcRequest,
4152        BeforeSend: Future<Output = Result<(), crate::Error>> + Send + 'static,
4153    >(
4154        &self,
4155        peer: Peer,
4156        request: Req,
4157        before_send: BeforeSend,
4158    ) -> SentRequest<Req::Response, P>
4159    where
4160        Counterpart: HasPeer<Peer>,
4161    {
4162        self.send_request_to_with_options(
4163            peer,
4164            request,
4165            true,
4166            Some(RequestReadiness::new(before_send)),
4167            None,
4168        )
4169    }
4170
4171    fn send_request_to_with_options<P: Protocol, Peer: Role, Req: JsonRpcRequest>(
4172        &self,
4173        peer: Peer,
4174        request: Req,
4175        ordered: bool,
4176        readiness: Option<RequestReadiness>,
4177        response_route_hook: Option<ResponseRouteHook>,
4178    ) -> SentRequest<Req::Response, P>
4179    where
4180        Counterpart: HasPeer<Peer>,
4181    {
4182        self.prepare_request_to_with_options(peer, request, readiness, response_route_hook)
4183            .into_sent_request(ordered)
4184    }
4185
4186    fn prepare_request_to_with_options<P: Protocol, Peer: Role, Req: JsonRpcRequest>(
4187        &self,
4188        peer: Peer,
4189        request: Req,
4190        readiness: Option<RequestReadiness>,
4191        response_route_hook: Option<ResponseRouteHook>,
4192    ) -> PreparedRequest<Req::Response, P>
4193    where
4194        Counterpart: HasPeer<Peer>,
4195    {
4196        let method = request.method().to_string();
4197        let id = HandleId::<P>::generated(Uuid::new_v4().to_string());
4198        let (response_tx, response_rx) = oneshot::channel();
4199        let response_ordering = ResponseOrdering::default();
4200        let role_id = peer.role_id();
4201        let remote_style = self.counterpart.remote_style(peer);
4202        let cancellation = SentRequestCancellation::new(self.message_tx.clone(), id.raw().clone());
4203        let pending_reply = PendingReply {
4204            id: id.raw().clone(),
4205            method: method.clone(),
4206            role_id,
4207            sender: response_tx,
4208            cancellation_disarm: cancellation.disarm_handle(),
4209            ordering: response_ordering.clone(),
4210            response_route_hook,
4211            accepts_lower_initialize_version: false,
4212        };
4213        let message = if self.is_incoming_closing() {
4214            Err(incoming_transport_closed_error(&method))
4215        } else {
4216            request
4217                .to_untyped_message()
4218                .map(|untyped| OutgoingMessage::Request {
4219                    id: id.raw().clone(),
4220                    method: method.clone(),
4221                    untyped,
4222                    remote_style,
4223                    readiness,
4224                })
4225                .map_err(|error| {
4226                    crate::util::internal_error(format!(
4227                        "failed to create untyped request for `{method}`: {error}"
4228                    ))
4229                })
4230        };
4231        let sent = SentRequest::new(
4232            id,
4233            method.clone(),
4234            self.task_tx.clone(),
4235            response_rx,
4236            cancellation,
4237            response_ordering,
4238        )
4239        .map(move |json| <Req::Response>::from_json(&method, json));
4240        PreparedRequest {
4241            sent,
4242            publication: RequestPublication {
4243                message,
4244                pending_reply,
4245                message_tx: self.message_tx.clone(),
4246                pending_replies: self.pending_replies.clone(),
4247                incoming_closed: self.incoming_closed.clone(),
4248            },
4249        }
4250    }
4251
4252    /// Send an outgoing notification to the default counterpart peer (no reply expected).
4253    ///
4254    /// Notifications are fire-and-forget messages that don't have IDs and don't expect responses.
4255    /// This method sends the notification immediately and returns.
4256    ///
4257    /// This is a convenience method that sends to the counterpart role `R`.
4258    /// For explicit control over the target peer, use [`send_notification_to`](Self::send_notification_to).
4259    ///
4260    /// ```no_run
4261    /// # use agent_client_protocol_test::*;
4262    /// # async fn example(cx: agent_client_protocol::ConnectionTo<agent_client_protocol::Agent>) -> Result<(), agent_client_protocol::Error> {
4263    /// cx.send_notification(StatusUpdate {
4264    ///     message: "Processing...".into(),
4265    /// })?;
4266    /// # Ok(())
4267    /// # }
4268    /// ```
4269    pub fn send_notification<N: JsonRpcNotification>(
4270        &self,
4271        notification: N,
4272    ) -> Result<(), crate::Error>
4273    where
4274        Counterpart: HasPeer<Counterpart>,
4275    {
4276        self.send_notification_to(self.counterpart.clone(), notification)
4277    }
4278
4279    /// Send an outgoing notification to a specific peer (no reply expected).
4280    ///
4281    /// The message will be transformed according to the [`HasPeer`](crate::role::HasPeer)
4282    /// implementation before being sent.
4283    pub fn send_notification_to<Peer: Role, N: JsonRpcNotification>(
4284        &self,
4285        peer: Peer,
4286        notification: N,
4287    ) -> Result<(), crate::Error>
4288    where
4289        Counterpart: HasPeer<Peer>,
4290    {
4291        let remote_style = self.counterpart.remote_style(peer);
4292        tracing::debug!(
4293            role = std::any::type_name::<Counterpart>(),
4294            peer = std::any::type_name::<Peer>(),
4295            notification_type = std::any::type_name::<N>(),
4296            ?remote_style,
4297            original_method = notification.method(),
4298            "send_notification_to"
4299        );
4300        let transformed = remote_style.transform_outgoing_message(notification)?;
4301        tracing::debug!(
4302            transformed_method = %transformed.method,
4303            "send_notification_to transformed"
4304        );
4305        send_raw_message(
4306            &self.message_tx,
4307            OutgoingMessage::Notification {
4308                untyped: transformed,
4309            },
4310        )
4311    }
4312
4313    /// Send a `$/cancel_request` notification for an arbitrary request ID to
4314    /// the default counterpart peer.
4315    ///
4316    /// Prefer [`SentRequest::cancel`] when you have the request handle: it
4317    /// already knows the correct request ID. Use this low-level method only
4318    /// when implementing custom routing with a request ID that is valid on
4319    /// this connection.
4320    pub fn send_cancel_request(
4321        &self,
4322        request_id: impl Into<RawJsonRpcId>,
4323    ) -> Result<(), crate::Error>
4324    where
4325        Counterpart: HasPeer<Counterpart>,
4326    {
4327        self.send_cancel_request_to(self.counterpart.clone(), request_id)
4328    }
4329
4330    /// Send a `$/cancel_request` notification for an arbitrary request ID to a
4331    /// specific peer.
4332    ///
4333    /// `$/cancel_request` is hop-local, so the notification is always sent
4334    /// plain, never wrapped in `proxy/successor`, even to a proxy's
4335    /// successor. To cancel a request sent to a successor, pass the ID of the
4336    /// `proxy/successor` request on this connection.
4337    ///
4338    /// Prefer [`SentRequest::cancel`] when you have the request handle: it
4339    /// already knows the correct request ID. Use this low-level method only
4340    /// when implementing custom routing with a request ID that is valid on
4341    /// this connection.
4342    pub fn send_cancel_request_to<Peer: Role>(
4343        &self,
4344        _peer: Peer,
4345        request_id: impl Into<RawJsonRpcId>,
4346    ) -> Result<(), crate::Error>
4347    where
4348        Counterpart: HasPeer<Peer>,
4349    {
4350        let untyped = crate::v1::schema::CancelRequestNotification::new(
4351            crate::v1::schema::RequestId::from(request_id.into()),
4352        )
4353        .to_untyped_message()?;
4354        send_raw_message(&self.message_tx, OutgoingMessage::Notification { untyped })
4355    }
4356
4357    /// Register a dynamic message handler, used to intercept messages specific to a particular session
4358    /// or some similar modal thing.
4359    ///
4360    /// Dynamic message handlers run after the handlers registered on [`Builder`] and before the
4361    /// role's default handler. They receive messages that the builder handlers decline.
4362    ///
4363    /// The handler will stay registered until the returned registration guard is dropped.
4364    pub fn add_dynamic_handler(
4365        &self,
4366        handler: impl HandleDispatchFrom<Counterpart> + 'static,
4367    ) -> Result<DynamicHandlerGuard<Counterpart>, crate::Error> {
4368        let uuid = Uuid::new_v4();
4369        let active = Arc::new(AtomicBool::new(true));
4370        self.dynamic_handler_tx
4371            .unbounded_send(DynamicHandlerMessage::AddDynamicHandler(
4372                uuid,
4373                Box::new(GuardedDynamicHandler {
4374                    active: active.clone(),
4375                    handler,
4376                }),
4377                active.clone(),
4378            ))
4379            .map_err(crate::util::internal_error)?;
4380
4381        Ok(DynamicHandlerGuard::new(uuid, active, self.clone()))
4382    }
4383
4384    /// Wait until every dynamic-handler update queued before this call has
4385    /// been applied by the incoming protocol actor.
4386    pub(crate) fn dynamic_handler_barrier(&self) -> BoxFuture<'static, Result<(), crate::Error>> {
4387        let (acknowledgment_tx, acknowledgment_rx) = oneshot::channel();
4388        if let Err(error) =
4389            self.dynamic_handler_tx
4390                .unbounded_send(DynamicHandlerMessage::AcknowledgedBarrier(
4391                    acknowledgment_tx,
4392                ))
4393        {
4394            return future::ready(Err(crate::Error::into_internal_error(error))).boxed();
4395        }
4396
4397        async move {
4398            acknowledgment_rx.await.map_err(|error| {
4399                crate::util::internal_error(format!(
4400                    "dynamic-handler barrier was dropped before acknowledgment: {error}"
4401                ))
4402            })
4403        }
4404        .boxed()
4405    }
4406
4407    fn remove_dynamic_handler(&self, uuid: Uuid) {
4408        // Ignore errors
4409        drop(
4410            self.dynamic_handler_tx
4411                .unbounded_send(DynamicHandlerMessage::RemoveDynamicHandler(uuid)),
4412        );
4413    }
4414}
4415
4416struct GuardedDynamicHandler<Handler> {
4417    active: Arc<AtomicBool>,
4418    handler: Handler,
4419}
4420
4421impl<Counterpart, Handler> HandleDispatchFrom<Counterpart> for GuardedDynamicHandler<Handler>
4422where
4423    Counterpart: Role,
4424    Handler: HandleDispatchFrom<Counterpart>,
4425{
4426    async fn handle_dispatch_from(
4427        &mut self,
4428        message: Dispatch,
4429        connection: ConnectionTo<Counterpart>,
4430    ) -> Result<Handled<Dispatch>, crate::Error> {
4431        if !self.active.load(Ordering::Acquire) {
4432            return Ok(Handled::No {
4433                message,
4434                retry: false,
4435            });
4436        }
4437        self.handler.handle_dispatch_from(message, connection).await
4438    }
4439
4440    fn describe_chain(&self) -> impl Debug {
4441        self.handler.describe_chain()
4442    }
4443}
4444
4445/// A guard that keeps a dynamic message handler registered.
4446///
4447/// Dropping the guard immediately deactivates the handler and queues its
4448/// removal from the connection. Use [`detach`](Self::detach) to keep the
4449/// handler registered for the remaining lifetime of the connection.
4450#[must_use = "dropping this guard unregisters the dynamic handler"]
4451#[derive(Debug)]
4452pub struct DynamicHandlerGuard<R: Role> {
4453    uuid: Option<Uuid>,
4454    active: Arc<AtomicBool>,
4455    cx: ConnectionTo<R>,
4456    cleanup: Option<Arc<dyn DynamicHandlerCleanup>>,
4457}
4458
4459/// Private registration-local cleanup, independent of connection task admission.
4460pub(crate) trait DynamicHandlerCleanup: std::fmt::Debug + Send + Sync {
4461    fn close(&self);
4462    fn wait(&self) -> futures::future::BoxFuture<'static, ()>;
4463}
4464
4465impl<R: Role> DynamicHandlerGuard<R> {
4466    fn new(uuid: Uuid, active: Arc<AtomicBool>, cx: ConnectionTo<R>) -> Self {
4467        Self {
4468            uuid: Some(uuid),
4469            active,
4470            cx,
4471            cleanup: None,
4472        }
4473    }
4474
4475    #[cfg(feature = "unstable_mcp_over_acp")]
4476    pub(crate) fn with_cleanup(mut self, cleanup: Arc<dyn DynamicHandlerCleanup>) -> Self {
4477        self.cleanup = Some(cleanup);
4478        self
4479    }
4480
4481    pub(crate) fn cleanup(&self) -> Option<Arc<dyn DynamicHandlerCleanup>> {
4482        self.cleanup.clone()
4483    }
4484
4485    /// Stop the handler from claiming messages without queuing its removal.
4486    ///
4487    /// Until the guard is dropped, the incoming actor keeps unclaimed session
4488    /// requests parked for a replacement handler.
4489    pub(crate) fn deactivate(&self) {
4490        self.active.store(false, Ordering::Release);
4491    }
4492
4493    /// Keep the dynamic handler registered after this guard is dropped.
4494    ///
4495    /// The handler remains registered until the connection itself shuts down.
4496    /// Unlike leaking the guard, detaching does not retain an extra
4497    /// [`ConnectionTo`] handle.
4498    pub fn detach(mut self) {
4499        self.uuid = None;
4500    }
4501}
4502
4503impl<R: Role> Drop for DynamicHandlerGuard<R> {
4504    fn drop(&mut self) {
4505        if let Some(uuid) = self.uuid {
4506            self.active.store(false, Ordering::Release);
4507            if let Some(cleanup) = &self.cleanup {
4508                cleanup.close();
4509            }
4510            self.cx.remove_dynamic_handler(uuid);
4511        }
4512    }
4513}
4514
4515/// The context to respond to an incoming request.
4516///
4517/// This context is provided to request handlers and serves a dual role:
4518///
4519/// 1. **Respond to the request** - Use [`respond`](Self::respond) or
4520///    [`respond_with_result`](Self::respond_with_result) to send the response
4521/// 2. **Send other messages** - Use the [`ConnectionTo`] parameter passed to your
4522///    handler, which provides [`send_request`](`ConnectionTo::send_request`),
4523///    [`send_notification`](`ConnectionTo::send_notification`), and
4524///    [`spawn`](`ConnectionTo::spawn`)
4525///
4526/// # Example
4527///
4528/// ```no_run
4529/// # use agent_client_protocol_test::*;
4530/// # async fn example() -> Result<(), agent_client_protocol::Error> {
4531/// # let connection = mock_connection();
4532/// connection.on_receive_request(async |req: ProcessRequest, responder, cx| {
4533///     // Send a notification while processing
4534///     cx.send_notification(StatusUpdate {
4535///         message: "processing".into(),
4536///     })?;
4537///
4538///     // Do some work...
4539///     let result = process(&req.data)?;
4540///
4541///     // Respond to the request
4542///     responder.respond(ProcessResponse { result })
4543/// }, agent_client_protocol::on_receive_request!())
4544/// # .connect_to(agent_client_protocol_test::MockTransport).await?;
4545/// # Ok(())
4546/// # }
4547/// ```
4548///
4549/// # Event Loop Considerations
4550///
4551/// Like all handlers, request handlers run on the event loop. Use
4552/// [`spawn`](ConnectionTo::spawn) for expensive operations to avoid blocking
4553/// the connection.
4554///
4555/// See the [Event Loop and Concurrency](Builder#event-loop-and-concurrency)
4556/// section for more details.
4557///
4558/// # Drop behavior
4559///
4560/// A request must be answered. If a responder for a request is dropped
4561/// without a response having been sent through it, the SDK answers the
4562/// request itself with an error, so the peer is never left waiting:
4563///
4564/// - `-32800` ([`Error::request_cancelled`]) if the peer had cancelled the
4565///   request with `$/cancel_request`;
4566/// - otherwise `-32603` ([`Error::internal_error`]), with data naming the
4567///   method whose responder was dropped.
4568///
4569/// No automatic response is sent when:
4570///
4571/// - a response was already sent through the responder (any of the
4572///   `respond*` methods), or the responder was handed to something that
4573///   answers through it (such as
4574///   [`SentRequest::forward_response_to`]) — only dropping the responder
4575///   itself without responding triggers the fallback;
4576/// - the responder was moved into another owner (another task, a wrapped
4577///   responder from [`cast`](Self::cast) or [`wrap_params`](Self::wrap_params),
4578///   a retried [`Dispatch`]); that owner's eventual drop is what counts;
4579/// - the connection is shutting down or has terminated.
4580///
4581/// When a handler drops the responder and then returns an error, that error
4582/// is the response instead of the generic fallback.
4583///
4584/// The automatic error is an ordinary error response: for example, a dropped
4585/// `initialize` responder fails initialization just as an explicit error
4586/// would.
4587///
4588/// # Protocol version
4589///
4590/// `P` is the [`Protocol`] marker and selects the type [`id`](Self::id)
4591/// returns. Typed handlers on `Client.v1()`, `Agent.v1()` and
4592/// `Proxy.v1()` receive [`V1`] responders and those on the v2 builders
4593/// receive `V2` responders. The version-neutral raw dispatch layer
4594/// ([`HandleDispatchFrom`], [`MatchDispatch`](crate::util::MatchDispatch))
4595/// uses the default, [`Raw`]. [`raw_id`](Self::raw_id) returns the wire ID
4596/// whatever the marker; [`into_protocol`](Responder::into_protocol) and
4597/// [`into_raw`](Self::into_raw) convert between markers.
4598///
4599/// [`Error::request_cancelled`]: crate::Error::request_cancelled
4600/// [`Error::internal_error`]: crate::Error::internal_error
4601#[must_use]
4602pub struct Responder<T: JsonRpcResponse = serde_json::Value, P: Protocol = Raw> {
4603    /// The method of the request.
4604    method: String,
4605
4606    /// The `id` of the message we are replying to.
4607    id: HandleId<P>,
4608
4609    /// Where the response is sent; it is completed at most once.
4610    destination: ResponseDestination,
4611
4612    /// Function to send the response to its destination.
4613    ///
4614    /// For incoming requests: serializes to JSON and sends over the wire.
4615    /// For incoming responses: sends to the waiting oneshot channel.
4616    send_fn: Box<dyn FnOnce(Result<T, crate::Error>) -> Result<(), crate::Error> + Send>,
4617
4618    /// Answers the request with an error if no response is sent. Owns the
4619    /// request-local cancellation state, so it can still observe a
4620    /// cancellation when it fires.
4621    drop_guard: ResponderDropGuard,
4622}
4623
4624/// Sends the automatic error for a [`Responder`] dropped without responding.
4625struct ResponderDropGuard {
4626    message_tx: OutgoingMessageTx,
4627    connection_state: IncomingClosed,
4628    /// The method of the request as received, used to route the response.
4629    wire_method: String,
4630    id: RawJsonRpcId,
4631    destination: ResponseDestination,
4632    /// Request-local cancellation state.
4633    cancellation: ResponderCancellation,
4634    armed: bool,
4635}
4636
4637impl ResponderDropGuard {
4638    fn disarm(&mut self) {
4639        self.armed = false;
4640    }
4641}
4642
4643impl Drop for ResponderDropGuard {
4644    fn drop(&mut self) {
4645        if !self.armed || self.destination.is_completed() {
4646            return;
4647        }
4648        if self.connection_state.is_shutting_down() {
4649            tracing::debug!(
4650                id = ?self.id,
4651                method = %self.wire_method,
4652                "responder dropped while the connection is shutting down; not answering"
4653            );
4654            return;
4655        }
4656
4657        let error = if self.cancellation.is_cancelled() {
4658            crate::Error::request_cancelled()
4659        } else {
4660            crate::Error::internal_error().data(format!(
4661                "request handler dropped its responder for `{}` without responding",
4662                self.wire_method
4663            ))
4664        };
4665        tracing::warn!(
4666            id = ?self.id,
4667            method = %self.wire_method,
4668            code = ?error.code,
4669            "Responder dropped without responding; answering with an error"
4670        );
4671        self.destination.abandon(AbandonedResponse {
4672            message_tx: self.message_tx.clone(),
4673            connection_state: self.connection_state.clone(),
4674            message: OutgoingMessage::Response {
4675                id: self.id.clone(),
4676                method: self.wire_method.clone(),
4677                response: Err(error),
4678                destination: self.destination.clone(),
4679            },
4680        });
4681    }
4682}
4683
4684impl<T: JsonRpcResponse, P: Protocol> std::fmt::Debug for Responder<T, P> {
4685    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4686        f.debug_struct("Responder")
4687            .field("method", &self.method)
4688            .field("id", &self.id)
4689            .field("response_type", &std::any::type_name::<T>())
4690            .finish_non_exhaustive()
4691    }
4692}
4693
4694impl Responder<serde_json::Value, Raw> {
4695    /// Create a new request context for an incoming request.
4696    ///
4697    /// The response will be serialized to JSON and sent over the wire.
4698    fn new(
4699        message_tx: OutgoingMessageTx,
4700        connection_state: IncomingClosed,
4701        method: String,
4702        id: RawJsonRpcId,
4703        cancellation_registry: &RequestCancellationRegistry,
4704        destination: ResponseDestination,
4705    ) -> Self {
4706        let id_clone = id.clone();
4707        let method_clone = method.clone();
4708        let cancellation = cancellation_registry.register(&id);
4709        let send_destination = destination.clone();
4710        let drop_guard = ResponderDropGuard {
4711            message_tx: message_tx.clone(),
4712            connection_state,
4713            wire_method: method.clone(),
4714            id: id.clone(),
4715            destination: destination.clone(),
4716            cancellation,
4717            armed: true,
4718        };
4719        Self {
4720            method,
4721            id: HandleId::raw_layer(id),
4722            destination,
4723            send_fn: Box::new(move |response: Result<serde_json::Value, crate::Error>| {
4724                send_raw_message(
4725                    &message_tx,
4726                    OutgoingMessage::Response {
4727                        id: id_clone,
4728                        method: method_clone,
4729                        response,
4730                        destination: send_destination,
4731                    },
4732                )
4733            }),
4734            drop_guard,
4735        }
4736    }
4737}
4738
4739impl<P: Protocol> Responder<serde_json::Value, P> {
4740    /// Cast this request context to a different response type.
4741    ///
4742    /// The provided type `T` will be serialized to JSON before sending.
4743    pub fn cast<T: JsonRpcResponse>(self) -> Responder<T, P> {
4744        self.wrap_params(move |method, value| match value {
4745            Ok(value) => T::into_json(value, method),
4746            Err(e) => Err(e),
4747        })
4748    }
4749}
4750
4751impl<T: JsonRpcResponse, P: Protocol> Responder<T, P> {
4752    /// Method of the incoming request
4753    #[must_use]
4754    pub fn method(&self) -> &str {
4755        &self.method
4756    }
4757
4758    /// ID of the incoming request, as this responder's protocol version
4759    /// types it.
4760    ///
4761    /// On a [`V2`](crate::Protocol) responder this is never `null`: the SDK
4762    /// rejects v2 requests with a `null` ID before dispatch.
4763    #[must_use]
4764    pub fn id(&self) -> &P::RequestId {
4765        self.id.typed()
4766    }
4767
4768    /// ID of the incoming request exactly as it appeared on the wire.
4769    ///
4770    /// This is the same ID as [`id`](Self::id), in the version-neutral form
4771    /// used by routers, forwarders and tracing.
4772    #[must_use]
4773    pub fn raw_id(&self) -> &RawJsonRpcId {
4774        self.id.raw()
4775    }
4776
4777    /// Returns the cancellation marker for this request.
4778    ///
4779    /// The marker is set when the peer sends `$/cancel_request` for this
4780    /// request's JSON-RPC ID. Cancellation is cooperative: handlers should use
4781    /// the marker to stop long-running work and then respond. Unless the
4782    /// method defines a successful response for cancellation (for example a
4783    /// permission request's `cancelled` outcome), that response is
4784    /// [`Error::request_cancelled`] (`-32800`) rather than partial data.
4785    /// Dropping the responder of a cancelled request sends that error
4786    /// automatically.
4787    ///
4788    /// [`Error::request_cancelled`]: crate::Error::request_cancelled
4789    #[must_use]
4790    pub fn cancellation(&self) -> RequestCancellation {
4791        self.drop_guard.cancellation.cancellation()
4792    }
4793
4794    /// Convert to a `Responder` that expects a JSON value
4795    /// and which checks (dynamically) that the JSON value it receives
4796    /// can be converted to `T`.
4797    pub fn erase_to_json(self) -> Responder<serde_json::Value, P> {
4798        self.wrap_params(|method, value| T::from_json(method, value?))
4799    }
4800
4801    /// Return a new Responder with a different method name.
4802    pub fn wrap_method(self, method: String) -> Responder<T, P> {
4803        Responder {
4804            method,
4805            id: self.id,
4806            destination: self.destination,
4807            send_fn: self.send_fn,
4808            drop_guard: self.drop_guard,
4809        }
4810    }
4811
4812    /// Return a new Responder that expects a response of type U.
4813    ///
4814    /// `wrap_fn` will be invoked with the method name and the result to transform
4815    /// type `U` into type `T` before sending.
4816    pub fn wrap_params<U: JsonRpcResponse>(
4817        self,
4818        wrap_fn: impl FnOnce(&str, Result<U, crate::Error>) -> Result<T, crate::Error> + Send + 'static,
4819    ) -> Responder<U, P> {
4820        let method = self.method.clone();
4821        let send_fn = self.send_fn;
4822        Responder {
4823            method: self.method,
4824            id: self.id,
4825            destination: self.destination,
4826            send_fn: Box::new(move |input: Result<U, crate::Error>| {
4827                let t_value = wrap_fn(&method, input);
4828                send_fn(t_value)
4829            }),
4830            drop_guard: self.drop_guard,
4831        }
4832    }
4833
4834    /// Respond to the JSON-RPC request with either a value (`Ok`) or an error (`Err`).
4835    pub fn respond_with_result(
4836        mut self,
4837        response: Result<T, crate::Error>,
4838    ) -> Result<(), crate::Error> {
4839        tracing::debug!(id = ?self.id, "respond called");
4840        self.drop_guard.disarm();
4841        (self.send_fn)(response)
4842    }
4843
4844    /// Respond to the JSON-RPC request with a value.
4845    pub fn respond(self, response: T) -> Result<(), crate::Error> {
4846        self.respond_with_result(Ok(response))
4847    }
4848
4849    /// Respond to the JSON-RPC request with an internal error containing a message.
4850    pub fn respond_with_internal_error(self, message: impl ToString) -> Result<(), crate::Error> {
4851        self.respond_with_error(crate::util::internal_error(message))
4852    }
4853
4854    /// Respond to the JSON-RPC request with an error.
4855    pub fn respond_with_error(self, error: crate::Error) -> Result<(), crate::Error> {
4856        tracing::debug!(id = ?self.id, error = ?crate::util::redacted_error(error.code), "respond_with_error called");
4857        self.respond_with_result(Err(error))
4858    }
4859
4860    /// The same responder for protocol `Q`. Fails only if the request ID is
4861    /// `null` and `Q` does not allow it, which cannot happen for requests
4862    /// received on a connection that speaks `Q`.
4863    pub(crate) fn retag<Q: Protocol>(self) -> Result<Responder<T, Q>, crate::Error> {
4864        Ok(Responder {
4865            method: self.method,
4866            id: self.id.into_protocol()?,
4867            destination: self.destination,
4868            send_fn: self.send_fn,
4869            drop_guard: self.drop_guard,
4870        })
4871    }
4872
4873    /// The same responder with a version-neutral [`Raw`] request ID, for
4874    /// code that is not tied to one protocol version, such as a
4875    /// [`HandleDispatchFrom`] implementation. This never fails.
4876    pub fn into_raw(self) -> Responder<T, Raw> {
4877        Responder {
4878            method: self.method,
4879            id: self.id.into_raw(),
4880            destination: self.destination,
4881            send_fn: self.send_fn,
4882            drop_guard: self.drop_guard,
4883        }
4884    }
4885
4886    fn reply_target(&self) -> RequestReplyTarget {
4887        RequestReplyTarget {
4888            id: self.id.raw().clone(),
4889            method: self.method.clone(),
4890            destination: self.destination.clone(),
4891        }
4892    }
4893}
4894
4895impl<T: JsonRpcResponse> Responder<T, Raw> {
4896    /// Convert this version-neutral responder to protocol `Q`'s responder,
4897    /// for example to pass a responder from a [`HandleDispatchFrom`] or
4898    /// [`MatchDispatch`](crate::util::MatchDispatch) handler to a v2 session
4899    /// helper.
4900    ///
4901    /// Only the request ID's type changes. It fails only when `Q` does not
4902    /// allow the ID: protocol v2 rejects `null` with the Invalid Request
4903    /// error (`-32600`) that a v2 connection sends for a `null` request ID.
4904    /// That cannot happen for a request received on a v2 connection, which
4905    /// rejects such requests before dispatch. On failure the responder is
4906    /// dropped, which answers the request with an error.
4907    ///
4908    /// ```
4909    /// # use agent_client_protocol::{Error, Responder, V1, v1::schema};
4910    /// # fn example(responder: Responder<schema::PromptResponse>) -> Result<(), Error> {
4911    /// let responder: agent_client_protocol::v1::Responder<schema::PromptResponse> =
4912    ///     responder.into_protocol::<V1>()?;
4913    /// let id: &schema::RequestId = responder.id();
4914    /// # let _ = id;
4915    /// # Ok(())
4916    /// # }
4917    /// ```
4918    pub fn into_protocol<Q: Protocol>(self) -> Result<Responder<T, Q>, crate::Error> {
4919        self.retag()
4920    }
4921}
4922
4923/// Context for handling an incoming JSON-RPC response.
4924///
4925/// This is the response-side counterpart to [`Responder`]. While `Responder` handles
4926/// incoming requests (where you send a response over the wire), `ResponseRouter` handles
4927/// incoming responses (where you route the response to a local task waiting for it).
4928///
4929/// Both are fundamentally "sinks" that push the message through a `send_fn`, but they
4930/// represent different points in the message lifecycle and carry different metadata.
4931///
4932/// # Drop Behavior
4933///
4934/// Dropping a `ResponseRouter` without routing the response (for example, from a
4935/// dispatch handler that claims a [`Dispatch::Response`]) discards the
4936/// response: the local awaiter observes the response as never received. The
4937/// request still counts as settled: routing a response this far disarms the
4938/// originating [`SentRequest`]'s drop-time auto-cancellation even if the router
4939/// is never invoked, since the peer has already answered.
4940///
4941/// `P` is the [`Protocol`] marker that types [`id`](Self::id); see
4942/// [`Responder`].
4943#[must_use]
4944pub struct ResponseRouter<T: JsonRpcResponse = serde_json::Value, P: Protocol = Raw> {
4945    /// The method of the original request.
4946    method: String,
4947
4948    /// The `id` of the original request.
4949    id: HandleId<P>,
4950
4951    /// The RoleId to which the original request was sent
4952    /// (and hence from which the reply is expected).
4953    role_id: RoleId,
4954
4955    /// Function to send the response to the waiting task.
4956    send_fn: Box<dyn FnOnce(Result<T, crate::Error>) -> Result<(), crate::Error> + Send>,
4957
4958    /// Shared route used to deliver a dispatch-handler error to the same waiter.
4959    reply_target: ResponseReplyTarget,
4960}
4961
4962impl<T: JsonRpcResponse, P: Protocol> std::fmt::Debug for ResponseRouter<T, P> {
4963    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4964        f.debug_struct("ResponseRouter")
4965            .field("method", &self.method)
4966            .field("id", &self.id)
4967            .field("response_type", &std::any::type_name::<T>())
4968            .finish_non_exhaustive()
4969    }
4970}
4971
4972impl ResponseRouter<serde_json::Value> {
4973    /// Create a new response context for routing a response to a local awaiter.
4974    ///
4975    /// When [`route_with_result`](Self::route_with_result) is called, the response is sent through the oneshot
4976    /// channel to the code that originally sent the request. If that receiver was
4977    /// dropped, the response is discarded because there is no local awaiter left.
4978    fn new(pending_reply: PendingReply, dispatch: ResponseDispatch) -> Self {
4979        let PendingReply {
4980            id,
4981            method,
4982            role_id,
4983            sender,
4984            cancellation_disarm,
4985            ordering,
4986            response_route_hook,
4987            accepts_lower_initialize_version: _,
4988        } = pending_reply;
4989        let reply_target = ResponseReplyTarget {
4990            id: id.clone(),
4991            method: method.clone(),
4992            sender: Arc::new(Mutex::new(Some(sender))),
4993            ordering,
4994            dispatch,
4995        };
4996        let send_target = reply_target.clone();
4997        // A response for the request reached this router, so the request is
4998        // settled from the peer's perspective and a `$/cancel_request` could
4999        // only ever be redundant. Disarm immediately so handlers may retain
5000        // the router without leaving auto-cancellation armed.
5001        cancellation_disarm.disarm();
5002        let hook_method = method.clone();
5003        Self {
5004            method,
5005            id: HandleId::raw_layer(id),
5006            role_id,
5007            send_fn: Box::new(move |response: Result<serde_json::Value, crate::Error>| {
5008                let response = match response {
5009                    Ok(value) => match response_route_hook {
5010                        Some(hook) => hook(&hook_method, &value).map(|()| value),
5011                        None => Ok(value),
5012                    },
5013                    Err(error) => Err(error),
5014                };
5015                send_target.route(response);
5016                Ok(())
5017            }),
5018            reply_target,
5019        }
5020    }
5021}
5022
5023impl<P: Protocol> ResponseRouter<serde_json::Value, P> {
5024    /// Cast this response context to a different response type.
5025    ///
5026    /// The provided type `T` will be serialized to JSON before sending.
5027    pub fn cast<T: JsonRpcResponse>(self) -> ResponseRouter<T, P> {
5028        self.wrap_params(move |method, value| match value {
5029            Ok(value) => T::into_json(value, method),
5030            Err(e) => Err(e),
5031        })
5032    }
5033}
5034
5035impl<T: JsonRpcResponse, P: Protocol> ResponseRouter<T, P> {
5036    /// Method of the original request
5037    #[must_use]
5038    pub fn method(&self) -> &str {
5039        &self.method
5040    }
5041
5042    /// ID of the original request, as this router's protocol version types
5043    /// it.
5044    #[must_use]
5045    pub fn id(&self) -> &P::RequestId {
5046        self.id.typed()
5047    }
5048
5049    /// ID of the original request exactly as it was sent on the wire.
5050    ///
5051    /// This is the same ID as [`id`](Self::id), in the version-neutral form
5052    /// used by routers, forwarders and tracing.
5053    #[must_use]
5054    pub fn raw_id(&self) -> &RawJsonRpcId {
5055        self.id.raw()
5056    }
5057
5058    /// The peer to which the original request was sent.
5059    ///
5060    /// This is the peer from which we expect to receive the response.
5061    #[must_use]
5062    pub fn role_id(&self) -> RoleId {
5063        self.role_id.clone()
5064    }
5065
5066    /// Convert to a `ResponseRouter` that expects a JSON value
5067    /// and which checks (dynamically) that the JSON value it receives
5068    /// can be converted to `T`.
5069    pub fn erase_to_json(self) -> ResponseRouter<serde_json::Value, P> {
5070        self.wrap_params(|method, value| T::from_json(method, value?))
5071    }
5072
5073    /// The same router for protocol `Q`. Fails only if the request ID is not
5074    /// allowed by `Q`, which cannot happen because the SDK never assigns
5075    /// `null` to requests it sends.
5076    pub(crate) fn retag<Q: Protocol>(self) -> Result<ResponseRouter<T, Q>, crate::Error> {
5077        Ok(ResponseRouter {
5078            method: self.method,
5079            id: self.id.into_protocol()?,
5080            role_id: self.role_id,
5081            send_fn: self.send_fn,
5082            reply_target: self.reply_target,
5083        })
5084    }
5085
5086    /// The same router with a version-neutral [`Raw`] request ID. This never
5087    /// fails.
5088    pub fn into_raw(self) -> ResponseRouter<T, Raw> {
5089        ResponseRouter {
5090            method: self.method,
5091            id: self.id.into_raw(),
5092            role_id: self.role_id,
5093            send_fn: self.send_fn,
5094            reply_target: self.reply_target,
5095        }
5096    }
5097
5098    /// Return a new ResponseRouter that expects a response of type U.
5099    ///
5100    /// `wrap_fn` will be invoked with the method name and the result to transform
5101    /// type `U` into type `T` before sending.
5102    fn wrap_params<U: JsonRpcResponse>(
5103        self,
5104        wrap_fn: impl FnOnce(&str, Result<U, crate::Error>) -> Result<T, crate::Error> + Send + 'static,
5105    ) -> ResponseRouter<U, P> {
5106        let method = self.method.clone();
5107        ResponseRouter {
5108            method: self.method,
5109            id: self.id,
5110            role_id: self.role_id,
5111            send_fn: Box::new(move |input: Result<U, crate::Error>| {
5112                let t_value = wrap_fn(&method, input);
5113                (self.send_fn)(t_value)
5114            }),
5115            reply_target: self.reply_target,
5116        }
5117    }
5118
5119    /// Route the response result to the waiting task.
5120    pub fn route_with_result(self, response: Result<T, crate::Error>) -> Result<(), crate::Error> {
5121        tracing::debug!(id = ?self.id, "response routed to awaiter");
5122        (self.send_fn)(response)
5123    }
5124
5125    /// Route a successful response value to the waiting task.
5126    pub fn route(self, response: T) -> Result<(), crate::Error> {
5127        self.route_with_result(Ok(response))
5128    }
5129
5130    /// Route an internal error to the waiting task.
5131    pub fn route_with_internal_error(self, message: impl ToString) -> Result<(), crate::Error> {
5132        self.route_with_error(crate::util::internal_error(message))
5133    }
5134
5135    /// Route an error response to the waiting task.
5136    pub fn route_with_error(self, error: crate::Error) -> Result<(), crate::Error> {
5137        tracing::debug!(id = ?self.id, error = ?crate::util::redacted_error(error.code), "error routed to awaiter");
5138        self.route_with_result(Err(error))
5139    }
5140}
5141
5142impl<T: JsonRpcResponse> ResponseRouter<T, Raw> {
5143    /// Convert this version-neutral router to protocol `Q`'s router.
5144    ///
5145    /// Only the request ID's type changes. The SDK never assigns `null` to
5146    /// requests it sends, so this succeeds for every marker.
5147    pub fn into_protocol<Q: Protocol>(self) -> Result<ResponseRouter<T, Q>, crate::Error> {
5148        self.retag()
5149    }
5150}
5151
5152/// Common bounds for any JSON-RPC message.
5153///
5154/// # Derive Macro
5155///
5156/// For simple message types, you can use the `JsonRpcRequest` or `JsonRpcNotification` derive macros
5157/// which will implement both `JsonRpcMessage` and the respective trait. See [`JsonRpcRequest`] and
5158/// [`JsonRpcNotification`] for examples.
5159pub trait JsonRpcMessage: 'static + Debug + Sized + Send + Clone {
5160    /// Check if this message type matches the given method name.
5161    fn matches_method(method: &str) -> bool;
5162
5163    /// The method name for the message.
5164    fn method(&self) -> &str;
5165
5166    /// Convert this message into an untyped message.
5167    fn to_untyped_message(&self) -> Result<UntypedMessage, crate::Error>;
5168
5169    /// Parse this type from a method name and the message's JSON `params`.
5170    ///
5171    /// Returns an error if the method doesn't match or deserialization fails.
5172    /// Callers should use `matches_method` first to check if this type handles the method.
5173    /// A message without `params` is parsed from [`serde_json::Value::Null`].
5174    fn parse_message(method: &str, params: &serde_json::Value) -> Result<Self, crate::Error>;
5175}
5176
5177/// Defines the "payload" of a successful response to a JSON-RPC request.
5178///
5179/// # Derive Macro
5180///
5181/// Use `#[derive(JsonRpcResponse)]` to automatically implement this trait:
5182///
5183/// ```ignore
5184/// use agent_client_protocol::JsonRpcResponse;
5185/// use serde::{Serialize, Deserialize};
5186///
5187/// #[derive(Debug, Clone, Serialize, Deserialize, JsonRpcResponse)]
5188/// struct HelloResponse {
5189///     greeting: String,
5190/// }
5191/// ```
5192pub trait JsonRpcResponse: 'static + Debug + Sized + Send + Clone {
5193    /// Convert this message into a JSON value.
5194    fn into_json(self, method: &str) -> Result<serde_json::Value, crate::Error>;
5195
5196    /// Parse a JSON value into the response type.
5197    fn from_json(method: &str, value: serde_json::Value) -> Result<Self, crate::Error>;
5198}
5199
5200impl JsonRpcResponse for serde_json::Value {
5201    fn from_json(_method: &str, value: serde_json::Value) -> Result<Self, crate::Error> {
5202        Ok(value)
5203    }
5204
5205    fn into_json(self, _method: &str) -> Result<serde_json::Value, crate::Error> {
5206        Ok(self)
5207    }
5208}
5209
5210/// A struct that represents a notification (JSON-RPC message that does not expect a response).
5211///
5212/// # Derive Macro
5213///
5214/// Use `#[derive(JsonRpcNotification)]` to automatically implement both `JsonRpcMessage` and `JsonRpcNotification`:
5215///
5216/// ```ignore
5217/// use agent_client_protocol::JsonRpcNotification;
5218/// use serde::{Serialize, Deserialize};
5219///
5220/// #[derive(Debug, Clone, Serialize, Deserialize, JsonRpcNotification)]
5221/// #[notification(method = "_ping")]
5222/// struct PingNotification {
5223///     timestamp: u64,
5224/// }
5225/// ```
5226pub trait JsonRpcNotification: JsonRpcMessage {}
5227
5228/// A struct that represents a request (JSON-RPC message expecting a response).
5229///
5230/// # Derive Macro
5231///
5232/// Use `#[derive(JsonRpcRequest)]` to automatically implement both `JsonRpcMessage` and `JsonRpcRequest`:
5233///
5234/// ```ignore
5235/// use agent_client_protocol::{JsonRpcRequest, JsonRpcResponse};
5236/// use serde::{Serialize, Deserialize};
5237///
5238/// #[derive(Debug, Clone, Serialize, Deserialize, JsonRpcRequest)]
5239/// #[request(method = "_hello", response = HelloResponse)]
5240/// struct HelloRequest {
5241///     name: String,
5242/// }
5243///
5244/// #[derive(Debug, Clone, Serialize, Deserialize, JsonRpcResponse)]
5245/// struct HelloResponse {
5246///     greeting: String,
5247/// }
5248/// ```
5249pub trait JsonRpcRequest: JsonRpcMessage {
5250    /// The type of data expected in response.
5251    type Response: JsonRpcResponse;
5252}
5253
5254/// An incoming request, notification, or response being dispatched through handlers.
5255/// Requests include the context used to answer them; responses include the context
5256/// used to route them to the local requester.
5257///
5258/// Type parameters allow specifying the concrete request and notification types.
5259/// By default, both are `UntypedMessage` for dynamic dispatch.
5260/// The request context's response type matches the request's response type.
5261///
5262/// `P` is the [`Protocol`] marker of the request handles. Typed handlers on
5263/// v1 builders receive `Dispatch<Req, Notif, V1>` and those on v2 builders
5264/// `Dispatch<Req, Notif, V2>`. The version-neutral [`HandleDispatchFrom`]
5265/// layer uses the default, [`Raw`], whose `id()` is the wire ID.
5266#[derive(Debug)]
5267pub enum Dispatch<
5268    Req: JsonRpcRequest = UntypedMessage,
5269    Notif: JsonRpcNotification = UntypedMessage,
5270    P: Protocol = Raw,
5271> {
5272    /// Incoming request and the context where the response should be sent.
5273    Request(Req, Responder<Req::Response, P>),
5274
5275    /// Incoming notification.
5276    Notification(Notif),
5277
5278    /// Incoming response to a request we sent.
5279    ///
5280    /// The first field is the response result (success or error from the remote).
5281    /// The second field is the context for forwarding the response to its destination
5282    /// (typically a waiting oneshot channel).
5283    Response(
5284        Result<Req::Response, crate::Error>,
5285        ResponseRouter<Req::Response, P>,
5286    ),
5287}
5288
5289impl<Req: JsonRpcRequest, Notif: JsonRpcNotification, P: Protocol> Dispatch<Req, Notif, P> {
5290    /// Map the request and notification types to new types.
5291    ///
5292    /// Note: Response variants are passed through unchanged since they don't
5293    /// contain a parseable message payload.
5294    pub fn map<Req1, Notif1>(
5295        self,
5296        map_request: impl FnOnce(
5297            Req,
5298            Responder<Req::Response, P>,
5299        ) -> (Req1, Responder<Req1::Response, P>),
5300        map_notification: impl FnOnce(Notif) -> Notif1,
5301    ) -> Dispatch<Req1, Notif1, P>
5302    where
5303        Req1: JsonRpcRequest<Response = Req::Response>,
5304        Notif1: JsonRpcNotification,
5305    {
5306        match self {
5307            Dispatch::Request(request, responder) => {
5308                let (new_request, new_responder) = map_request(request, responder);
5309                Dispatch::Request(new_request, new_responder)
5310            }
5311            Dispatch::Notification(notification) => {
5312                let new_notification = map_notification(notification);
5313                Dispatch::Notification(new_notification)
5314            }
5315            Dispatch::Response(result, router) => Dispatch::Response(result, router),
5316        }
5317    }
5318
5319    /// Convert the message in self to an untyped message.
5320    ///
5321    /// Note: Response variants don't have an untyped message representation.
5322    /// This returns an error for Response variants.
5323    pub fn to_untyped_message(&self) -> Result<UntypedMessage, crate::Error> {
5324        match self {
5325            Dispatch::Request(request, _) => request.to_untyped_message(),
5326            Dispatch::Notification(notification) => notification.to_untyped_message(),
5327            Dispatch::Response(_, _) => Err(crate::util::internal_error(
5328                "Response variant has no untyped message representation",
5329            )),
5330        }
5331    }
5332
5333    /// Convert self to an untyped message context.
5334    ///
5335    /// Note: Response variants cannot be converted. This returns an error for Response variants.
5336    pub fn into_untyped_dispatch(
5337        self,
5338    ) -> Result<Dispatch<UntypedMessage, UntypedMessage, P>, crate::Error> {
5339        match self {
5340            Dispatch::Request(request, responder) => Ok(Dispatch::Request(
5341                request.to_untyped_message()?,
5342                responder.erase_to_json(),
5343            )),
5344            Dispatch::Notification(notification) => {
5345                Ok(Dispatch::Notification(notification.to_untyped_message()?))
5346            }
5347            Dispatch::Response(_, _) => Err(crate::util::internal_error(
5348                "cannot convert Response variant to untyped message context",
5349            )),
5350        }
5351    }
5352
5353    /// Returns the request ID if this is a request or response, None if notification.
5354    ///
5355    /// See [`Responder::id`] and [`ResponseRouter::id`].
5356    pub fn id(&self) -> Option<&P::RequestId> {
5357        match self {
5358            Dispatch::Request(_, cx) => Some(cx.id()),
5359            Dispatch::Notification(_) => None,
5360            Dispatch::Response(_, cx) => Some(cx.id()),
5361        }
5362    }
5363
5364    /// Returns the request ID exactly as it appears on the wire if this is a
5365    /// request or response, None if notification.
5366    ///
5367    /// See [`Responder::raw_id`] and [`ResponseRouter::raw_id`].
5368    #[must_use]
5369    pub fn raw_id(&self) -> Option<&RawJsonRpcId> {
5370        match self {
5371            Dispatch::Request(_, cx) => Some(cx.raw_id()),
5372            Dispatch::Notification(_) => None,
5373            Dispatch::Response(_, cx) => Some(cx.raw_id()),
5374        }
5375    }
5376
5377    /// The same dispatch with request handles for protocol `Q`.
5378    ///
5379    /// Fails only for a request whose `null` ID `Q` does not allow, which
5380    /// cannot happen for a message received on a connection that speaks `Q`.
5381    pub(crate) fn retag<Q: Protocol>(self) -> Result<Dispatch<Req, Notif, Q>, crate::Error> {
5382        Ok(match self {
5383            Dispatch::Request(request, responder) => Dispatch::Request(request, responder.retag()?),
5384            Dispatch::Notification(notification) => Dispatch::Notification(notification),
5385            Dispatch::Response(result, router) => Dispatch::Response(result, router.retag()?),
5386        })
5387    }
5388
5389    /// The same dispatch with version-neutral [`Raw`] request handles, for
5390    /// example to hand a typed dispatch to a [`HandleDispatchFrom`]
5391    /// implementation. This never fails.
5392    pub fn into_raw(self) -> Dispatch<Req, Notif, Raw> {
5393        match self {
5394            Dispatch::Request(request, responder) => {
5395                Dispatch::Request(request, responder.into_raw())
5396            }
5397            Dispatch::Notification(notification) => Dispatch::Notification(notification),
5398            Dispatch::Response(result, router) => Dispatch::Response(result, router.into_raw()),
5399        }
5400    }
5401
5402    fn handler_error_target(&self) -> Option<HandlerErrorTarget> {
5403        match self {
5404            Dispatch::Request(_, responder) => {
5405                Some(HandlerErrorTarget::Request(responder.reply_target()))
5406            }
5407            Dispatch::Notification(_) => None,
5408            Dispatch::Response(_, router) => {
5409                Some(HandlerErrorTarget::Response(router.reply_target.clone()))
5410            }
5411        }
5412    }
5413
5414    /// Returns the method of the message.
5415    ///
5416    /// For requests and notifications, this is the method from the message payload.
5417    /// For responses, this is the method of the original request.
5418    pub fn method(&self) -> &str {
5419        match self {
5420            Dispatch::Request(msg, _) => msg.method(),
5421            Dispatch::Notification(msg) => msg.method(),
5422            Dispatch::Response(_, cx) => cx.method(),
5423        }
5424    }
5425}
5426
5427impl<Req: JsonRpcRequest, Notif: JsonRpcNotification> Dispatch<Req, Notif, Raw> {
5428    /// Convert this version-neutral dispatch to protocol `Q`'s request
5429    /// handles.
5430    ///
5431    /// See [`Responder::into_protocol`]: this fails only for a request whose
5432    /// `null` ID `Q` does not allow, with the Invalid Request error
5433    /// (`-32600`).
5434    pub fn into_protocol<Q: Protocol>(self) -> Result<Dispatch<Req, Notif, Q>, crate::Error> {
5435        self.retag()
5436    }
5437}
5438
5439impl Dispatch {
5440    /// Attempts to parse `self` into a typed message context.
5441    ///
5442    /// # Returns
5443    ///
5444    /// * `Ok(Ok(typed))` if this dispatch matches the requested type for its variant
5445    /// * `Ok(Err(self))` if it does not match the requested type for its variant
5446    /// * `Err` if its method matches the requested type but parsing fails
5447    #[tracing::instrument(skip(self), fields(Request = ?std::any::type_name::<Req>(), Notif = ?std::any::type_name::<Notif>()), level = "trace", ret)]
5448    pub(crate) fn into_typed_dispatch<Req: JsonRpcRequest, Notif: JsonRpcNotification>(
5449        self,
5450    ) -> Result<Result<Dispatch<Req, Notif>, Dispatch>, crate::Error> {
5451        tracing::debug!(
5452            method = self.method(),
5453            id = ?self.raw_id(),
5454            "into_typed_dispatch"
5455        );
5456        match self {
5457            Dispatch::Request(message, responder) => {
5458                if Req::matches_method(&message.method) {
5459                    match Req::parse_message(&message.method, &message.params) {
5460                        Ok(req) => {
5461                            tracing::trace!("parsed ok");
5462                            Ok(Ok(Dispatch::Request(req, responder.cast())))
5463                        }
5464                        Err(err) => {
5465                            tracing::trace!(err = ?crate::util::redacted_error(err.code), "parse error");
5466                            Err(err)
5467                        }
5468                    }
5469                } else {
5470                    tracing::trace!("method doesn't match");
5471                    Ok(Err(Dispatch::Request(message, responder)))
5472                }
5473            }
5474
5475            Dispatch::Notification(message) => {
5476                if Notif::matches_method(&message.method) {
5477                    match Notif::parse_message(&message.method, &message.params) {
5478                        Ok(notif) => {
5479                            tracing::trace!("parse ok");
5480                            Ok(Ok(Dispatch::Notification(notif)))
5481                        }
5482                        Err(err) => {
5483                            tracing::trace!(err = ?crate::util::redacted_error(err.code), "parse error");
5484                            Err(err)
5485                        }
5486                    }
5487                } else {
5488                    tracing::trace!("method doesn't match");
5489                    Ok(Err(Dispatch::Notification(message)))
5490                }
5491            }
5492
5493            Dispatch::Response(result, cx) => {
5494                let method = cx.method();
5495                if Req::matches_method(method) {
5496                    // Parse the response result
5497                    let typed_result = match result {
5498                        Ok(value) => {
5499                            match <Req::Response as JsonRpcResponse>::from_json(method, value) {
5500                                Ok(parsed) => {
5501                                    tracing::trace!("parse ok");
5502                                    Ok(parsed)
5503                                }
5504                                Err(err) => {
5505                                    tracing::trace!(err = ?crate::util::redacted_error(err.code), "parse error");
5506                                    return Err(err);
5507                                }
5508                            }
5509                        }
5510                        Err(err) => {
5511                            tracing::trace!("error, passthrough");
5512                            Err(err)
5513                        }
5514                    };
5515                    Ok(Ok(Dispatch::Response(typed_result, cx.cast())))
5516                } else {
5517                    tracing::trace!("method doesn't match");
5518                    Ok(Err(Dispatch::Response(result, cx)))
5519                }
5520            }
5521        }
5522    }
5523
5524    /// True if this message has a field with the given name.
5525    ///
5526    /// Returns `false` for Response variants.
5527    #[must_use]
5528    pub fn has_field(&self, field_name: &str) -> bool {
5529        self.message()
5530            .and_then(|m| m.params().get(field_name))
5531            .is_some()
5532    }
5533
5534    /// Returns true if this message has a session-id field.
5535    ///
5536    /// Returns `false` for Response variants.
5537    pub(crate) fn has_session_id(&self) -> bool {
5538        self.has_field("sessionId")
5539    }
5540
5541    /// Extract the ACP session-id from this message (if any).
5542    ///
5543    /// Returns `Ok(None)` for Response variants.
5544    pub(crate) fn get_session_id(&self) -> Result<Option<SessionId>, crate::Error> {
5545        let Some(message) = self.message() else {
5546            return Ok(None);
5547        };
5548        let Some(value) = message.params().get("sessionId") else {
5549            return Ok(None);
5550        };
5551        let session_id = serde_json::from_value(value.clone())?;
5552        Ok(Some(session_id))
5553    }
5554
5555    /// Try to parse this as a notification of the given type.
5556    ///
5557    /// # Returns
5558    ///
5559    /// * `Ok(Ok(typed))` if this is a notification of the requested type
5560    /// * `Ok(Err(self))` if this is not a matching notification
5561    /// * `Err` if its method matches the requested type but parsing fails
5562    pub fn into_notification<N: JsonRpcNotification>(
5563        self,
5564    ) -> Result<Result<N, Dispatch>, crate::Error> {
5565        match self {
5566            Dispatch::Notification(msg) => {
5567                if !N::matches_method(&msg.method) {
5568                    return Ok(Err(Dispatch::Notification(msg)));
5569                }
5570                match N::parse_message(&msg.method, &msg.params) {
5571                    Ok(n) => Ok(Ok(n)),
5572                    Err(err) => Err(err),
5573                }
5574            }
5575            Dispatch::Request(..) | Dispatch::Response(..) => Ok(Err(self)),
5576        }
5577    }
5578
5579    /// Try to parse this as a request of the given type.
5580    ///
5581    /// # Returns
5582    ///
5583    /// * `Ok(Ok(typed))` if this is a request of the requested type
5584    /// * `Ok(Err(self))` if this is not a matching request
5585    /// * `Err` if its method matches the requested type but parsing fails
5586    pub fn into_request<Req: JsonRpcRequest>(
5587        self,
5588    ) -> Result<Result<(Req, Responder<Req::Response>), Dispatch>, crate::Error> {
5589        match self {
5590            Dispatch::Request(msg, responder) => {
5591                if !Req::matches_method(&msg.method) {
5592                    return Ok(Err(Dispatch::Request(msg, responder)));
5593                }
5594                match Req::parse_message(&msg.method, &msg.params) {
5595                    Ok(req) => Ok(Ok((req, responder.cast()))),
5596                    Err(err) => Err(err),
5597                }
5598            }
5599            Dispatch::Notification(..) | Dispatch::Response(..) => Ok(Err(self)),
5600        }
5601    }
5602}
5603
5604impl<M: JsonRpcRequest + JsonRpcNotification> Dispatch<M, M> {
5605    /// Returns the message payload for requests and notifications.
5606    ///
5607    /// Returns `None` for Response variants since they don't contain a message payload.
5608    pub fn message(&self) -> Option<&M> {
5609        match self {
5610            Dispatch::Request(msg, _) | Dispatch::Notification(msg) => Some(msg),
5611            Dispatch::Response(_, _) => None,
5612        }
5613    }
5614
5615    /// Map the request/notification message.
5616    ///
5617    /// Response variants pass through unchanged.
5618    pub(crate) fn try_map_message(
5619        self,
5620        map_message: impl FnOnce(M) -> Result<M, crate::Error>,
5621    ) -> Result<Dispatch<M, M>, crate::Error> {
5622        match self {
5623            Dispatch::Request(request, cx) => Ok(Dispatch::Request(map_message(request)?, cx)),
5624            Dispatch::Notification(notification) => {
5625                Ok(Dispatch::<M, M>::Notification(map_message(notification)?))
5626            }
5627            Dispatch::Response(result, cx) => Ok(Dispatch::Response(result, cx)),
5628        }
5629    }
5630}
5631
5632/// An incoming JSON message without any typing. Can be a request or a notification.
5633#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
5634pub struct UntypedMessage {
5635    /// The JSON-RPC method name
5636    pub method: String,
5637    /// The JSON-RPC parameters as a raw JSON value
5638    pub params: serde_json::Value,
5639}
5640
5641impl UntypedMessage {
5642    /// Returns an untyped message with the given method and parameters.
5643    pub fn new(method: &str, params: impl Serialize) -> Result<Self, crate::Error> {
5644        let params = serde_json::to_value(params)?;
5645        Ok(Self {
5646            method: method.to_string(),
5647            params,
5648        })
5649    }
5650
5651    /// Returns the method name
5652    #[must_use]
5653    pub fn method(&self) -> &str {
5654        &self.method
5655    }
5656
5657    /// Returns the parameters as a JSON value
5658    #[must_use]
5659    pub fn params(&self) -> &serde_json::Value {
5660        &self.params
5661    }
5662
5663    /// Consumes this message and returns the method and params
5664    #[must_use]
5665    pub fn into_parts(self) -> (String, serde_json::Value) {
5666        (self.method, self.params)
5667    }
5668
5669    /// Convert `self` to a raw JSON-RPC message.
5670    pub(crate) fn into_raw_jsonrpc_message(
5671        self,
5672        id: Option<RawJsonRpcId>,
5673    ) -> Result<RawJsonRpcMessage, crate::Error> {
5674        let Self { method, params } = self;
5675        match id {
5676            Some(id) => RawJsonRpcMessage::request(method, params, id),
5677            None => RawJsonRpcMessage::notification(method, params),
5678        }
5679    }
5680}
5681
5682impl JsonRpcMessage for UntypedMessage {
5683    fn matches_method(_method: &str) -> bool {
5684        // UntypedMessage matches any method - it's the untyped fallback
5685        true
5686    }
5687
5688    fn method(&self) -> &str {
5689        &self.method
5690    }
5691
5692    fn to_untyped_message(&self) -> Result<UntypedMessage, crate::Error> {
5693        Ok(self.clone())
5694    }
5695
5696    fn parse_message(method: &str, params: &serde_json::Value) -> Result<Self, crate::Error> {
5697        UntypedMessage::new(method, params)
5698    }
5699}
5700
5701impl JsonRpcRequest for UntypedMessage {
5702    type Response = serde_json::Value;
5703}
5704
5705impl JsonRpcNotification for UntypedMessage {}
5706
5707/// Represents a pending response of type `R` from an outgoing request.
5708///
5709/// Returned by [`ConnectionTo::send_request`], this type provides explicit response-consumption
5710/// modes. The API is intentionally designed to make it difficult to accidentally wait for a
5711/// response inside the dispatch loop.
5712///
5713/// # Anti-Footgun Design
5714///
5715/// You cannot directly `.await` a `SentRequest`. Instead, you must choose how to handle
5716/// the response:
5717///
5718/// ## Option 1: Register an Ordered Callback (Safe in Handlers)
5719///
5720/// Calling [`on_receiving_result`](Self::on_receiving_result) registers the callback and returns
5721/// immediately. When ordered consumption is selected before the response is routed during its
5722/// original dispatch, the loop waits for the callback to complete before processing the next
5723/// message:
5724///
5725/// ```no_run
5726/// # use agent_client_protocol_test::*;
5727/// # async fn example(cx: agent_client_protocol::ConnectionTo<agent_client_protocol::UntypedRole>) -> Result<(), agent_client_protocol::Error> {
5728/// cx.send_request(MyRequest {})
5729///     .on_receiving_result(async |result| {
5730///         match result {
5731///             Ok(response) => {
5732///                 // Handle successful response
5733///                 Ok(())
5734///             }
5735///             Err(error) => {
5736///                 // Handle error
5737///                 Err(error)
5738///             }
5739///         }
5740///     })?;
5741/// # Ok(())
5742/// # }
5743/// ```
5744///
5745/// ## Option 2: Wait Outside the Dispatch Loop
5746///
5747/// Use [`block_task`](Self::block_task) only when the current task already runs outside the
5748/// dispatch loop—for example, in the foreground future passed to `connect_with` or in a task
5749/// created with [`ConnectionTo::spawn`]. Never await it in a handler:
5750///
5751/// ```no_run
5752/// # use agent_client_protocol_test::*;
5753/// # async fn example(cx: agent_client_protocol::ConnectionTo<agent_client_protocol::UntypedRole>) -> Result<(), agent_client_protocol::Error> {
5754/// // ✅ Safe: Spawned task runs concurrently
5755/// cx.spawn({
5756///     let cx = cx.clone();
5757///     async move {
5758///         let response = cx.send_request(MyRequest {})
5759///             .block_task()
5760///             .await?;
5761///         // Process response...
5762///         Ok(())
5763///     }
5764/// })?;
5765/// # Ok(())
5766/// # }
5767/// ```
5768///
5769/// ```no_run
5770/// # use agent_client_protocol_test::*;
5771/// # async fn example() -> Result<(), agent_client_protocol::Error> {
5772/// # let connection = mock_connection();
5773/// // ❌ NEVER do this in a handler - blocks the event loop!
5774/// connection.on_receive_request(async |req: MyRequest, responder, cx| {
5775///     let response = cx.send_request(MyRequest {})
5776///         .block_task()  // This will deadlock!
5777///         .await?;
5778///     responder.respond(response)
5779/// }, agent_client_protocol::on_receive_request!())
5780/// # .connect_to(agent_client_protocol_test::MockTransport).await?;
5781/// # Ok(())
5782/// # }
5783/// ```
5784///
5785/// # Why This Design?
5786///
5787/// If you block the event loop while waiting for a response, the connection cannot process
5788/// the incoming response message, creating a deadlock. This API design prevents that footgun
5789/// by making blocking explicit and encouraging non-blocking patterns.
5790///
5791/// # Drop Behavior
5792///
5793/// By default, dropping a `SentRequest` before the SDK has received the
5794/// response sends a `$/cancel_request` notification asking the peer to cancel
5795/// the request, then discards the response when it arrives. Requests whose
5796/// eventual response should be ignored, but which should keep running on the
5797/// peer, should use [`detach`](Self::detach) instead.
5798///
5799/// # Incoming Transport EOF
5800///
5801/// If the incoming transport reaches clean EOF before the response arrives, every
5802/// consumption mode receives an error with the message `Incoming transport
5803/// closed` and data containing
5804/// `{"reason":"incoming_transport_closed","method":"..."}`. Requests made
5805/// after incoming EOF fail immediately with the same error. Use
5806/// [`is_incoming_transport_closed`] to identify it.
5807///
5808/// # Protocol version
5809///
5810/// `P` is the [`Protocol`] marker of the connection handle that sent the
5811/// request: [`Raw`] for the version-neutral [`ConnectionTo`], `V2` for
5812/// `v2::ConnectionTo`. It selects the type [`id`](Self::id) returns.
5813#[must_use = "dropping a SentRequest asks the peer to cancel the request and \
5814              discards the response; consume it with `block_task`, \
5815              `on_receiving_result`, `forward_response_to`, or `detach`"]
5816pub struct SentRequest<T, P: Protocol = Raw> {
5817    id: HandleId<P>,
5818    method: String,
5819    task_tx: TaskTx,
5820    response_rx: oneshot::Receiver<ResponsePayload>,
5821    /// Converts the raw response into the typed result. It receives error
5822    /// responses too, so [`SentRequest::recover_error`] can map an error to a
5823    /// success.
5824    to_result:
5825        Box<dyn FnOnce(Result<serde_json::Value, crate::Error>) -> Result<T, crate::Error> + Send>,
5826    cancellation: SentRequestCancellation,
5827    response_ordering: ResponseOrdering,
5828    /// Cancellation markers of other (incoming) requests whose cancellation
5829    /// should be forwarded to this request. See
5830    /// [`forward_cancellation_from`](Self::forward_cancellation_from).
5831    cancellation_sources: Vec<RequestCancellation>,
5832}
5833
5834/// A request that has not been published to its connection.
5835///
5836/// Created by [`ConnectionTo::prepare_request`] or
5837/// [`ConnectionTo::prepare_request_to`]. Preparation serializes the request but
5838/// does not register a pending reply or enqueue outgoing traffic. Dropping this
5839/// value sends neither the request nor a cancellation notification.
5840///
5841/// A consuming method publishes the request synchronously:
5842///
5843/// - [`on_receiving_result`](Self::on_receiving_result),
5844///   [`on_receiving_ok_result`](Self::on_receiving_ok_result), and
5845///   [`forward_response_to`](Self::forward_response_to) register ordered response
5846///   handling before publication. When a peer response is routed during its
5847///   original dispatch, later inbound messages wait for that handling to finish.
5848/// - [`block_task`](Self::block_task) publishes immediately and returns an
5849///   unordered response future. Publication does not wait for its first poll.
5850/// - [`detach`](Self::detach) publishes immediately and discards the response.
5851///
5852/// Ordered callbacks must do bounded work and must not await later inbound
5853/// traffic on the same connection. EOF failures and responses routed through a
5854/// retained [`ResponseRouter`] after their original dispatch have no ordering
5855/// barrier. See [`crate::concepts::ordering`].
5856///
5857/// # Errors
5858///
5859/// Preparation and publication failures are delivered to the selected response
5860/// consumer. Callback-style methods return an error if their task cannot be
5861/// registered; in that case the request is not published. [`detach`](Self::detach)
5862/// returns preparation or publication errors directly because it has no response
5863/// consumer. A callback returning an error terminates the connection.
5864///
5865/// `P` is the [`Protocol`] marker that types [`id`](Self::id); see
5866/// [`SentRequest`].
5867#[must_use = "a prepared request is not sent until consumed with `block_task`, \
5868              `on_receiving_result`, `forward_response_to`, or `detach`"]
5869pub struct PreparedRequest<T, P: Protocol = Raw> {
5870    sent: SentRequest<T, P>,
5871    publication: RequestPublication,
5872}
5873
5874struct RequestPublication {
5875    message: Result<OutgoingMessage, crate::Error>,
5876    pending_reply: PendingReply,
5877    message_tx: OutgoingMessageTx,
5878    pending_replies: PendingRepliesRegistrar,
5879    incoming_closed: IncomingClosed,
5880}
5881
5882impl RequestPublication {
5883    fn publish(self) -> Result<(), crate::Error> {
5884        let message = if self.incoming_closed.is_closing() {
5885            Err(incoming_transport_closed_error(&self.pending_reply.method))
5886        } else {
5887            self.message
5888        };
5889        let message = match message {
5890            Ok(message) => message,
5891            Err(error) => {
5892                self.pending_reply.fail(error.clone());
5893                return Err(error);
5894            }
5895        };
5896        let OutgoingMessage::Request { id, method, .. } = &message else {
5897            unreachable!();
5898        };
5899        let id = id.clone();
5900        let method = method.clone();
5901        let cancellation_disarm = self.pending_reply.cancellation_disarm.clone();
5902        // Register before enqueueing so incoming EOF can fail every observable
5903        // request before close callbacks begin. The outgoing actor checks that
5904        // the registration still exists before sending the request.
5905        self.pending_replies
5906            .subscribe(id.clone(), self.pending_reply, &self.incoming_closed)?;
5907        if self.message_tx.unbounded_send(message).is_err() {
5908            let error = if self.incoming_closed.is_closing() {
5909                incoming_transport_closed_error(&method)
5910            } else {
5911                crate::util::internal_error(format!("failed to send outgoing request `{method}`"))
5912            };
5913            if let Some(pending_reply) = self.pending_replies.remove(&id) {
5914                pending_reply.fail(error.clone());
5915            }
5916            return Err(error);
5917        }
5918        // An escaped cancellation handle must not enqueue cancellation before
5919        // the request. A fast response or EOF may already have disarmed it.
5920        cancellation_disarm.arm();
5921        Ok(())
5922    }
5923}
5924
5925impl<T: Debug, P: Protocol> Debug for PreparedRequest<T, P> {
5926    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5927        formatter
5928            .debug_struct("PreparedRequest")
5929            .field("request", &self.sent)
5930            .finish_non_exhaustive()
5931    }
5932}
5933
5934impl<T, P: Protocol> PreparedRequest<T, P> {
5935    /// The same prepared request with a version-neutral [`Raw`] request ID,
5936    /// for code that is not tied to one protocol version. This never fails
5937    /// and does not publish the request.
5938    pub fn into_raw(self) -> PreparedRequest<T, Raw> {
5939        PreparedRequest {
5940            sent: self.sent.into_raw(),
5941            publication: self.publication,
5942        }
5943    }
5944}
5945
5946impl<T> PreparedRequest<T, Raw> {
5947    /// Convert this version-neutral prepared request to protocol `Q`'s
5948    /// handle without publishing it.
5949    ///
5950    /// Only the request ID's type changes. The SDK never assigns `null` to
5951    /// requests it sends, so this succeeds for every marker.
5952    pub fn into_protocol<Q: Protocol>(self) -> Result<PreparedRequest<T, Q>, crate::Error> {
5953        Ok(PreparedRequest {
5954            sent: self.sent.into_protocol()?,
5955            publication: self.publication,
5956        })
5957    }
5958}
5959
5960impl<T, P: Protocol> PreparedRequest<T, P> {
5961    /// The ID reserved for this request, which has not been sent yet, as
5962    /// this request's protocol version types it.
5963    ///
5964    /// It is the ID written to the wire when the request is published. The
5965    /// SDK never assigns `null`.
5966    #[must_use]
5967    pub fn id(&self) -> &P::RequestId {
5968        self.sent.id()
5969    }
5970
5971    /// The ID reserved for this request in the version-neutral form used by
5972    /// routers, forwarders and tracing. It is the same ID as
5973    /// [`id`](Self::id).
5974    #[must_use]
5975    pub fn raw_id(&self) -> &RawJsonRpcId {
5976        self.sent.raw_id()
5977    }
5978
5979    /// The method of the prepared request.
5980    #[must_use]
5981    pub fn method(&self) -> &str {
5982        self.sent.method()
5983    }
5984
5985    /// Retain explicit cancellation control without publishing this request.
5986    ///
5987    /// The handle can outlive consumption of this request by an ordered callback
5988    /// or response future. Calling it before publication is a no-op, not a
5989    /// cancellation to apply when the request is later published. Dropping the
5990    /// handle does not cancel. See [`RequestCancellationHandle`].
5991    #[must_use]
5992    pub fn cancellation_handle(&self) -> RequestCancellationHandle {
5993        self.sent.cancellation_handle()
5994    }
5995
5996    /// Map a successful response without publishing the request.
5997    ///
5998    /// The mapper has the same contract as [`SentRequest::map`].
5999    pub fn map<U>(
6000        self,
6001        map_fn: impl FnOnce(T) -> Result<U, crate::Error> + 'static + Send,
6002    ) -> PreparedRequest<U, P>
6003    where
6004        T: 'static,
6005    {
6006        PreparedRequest {
6007            sent: self.sent.map(map_fn),
6008            publication: self.publication,
6009        }
6010    }
6011
6012    /// Register a cancellation source without publishing the request.
6013    ///
6014    /// After publication, cancellation is forwarded while awaiting the response,
6015    /// as described by [`SentRequest::forward_cancellation_from`].
6016    pub fn forward_cancellation_from(mut self, source: RequestCancellation) -> Self {
6017        self.sent = self.sent.forward_cancellation_from(source);
6018        self
6019    }
6020
6021    /// Publish now and return an unordered future for the response.
6022    ///
6023    /// The request is enqueued during this call, not when the future is first
6024    /// polled. Dropping that future asks the peer to cancel a still-outstanding
6025    /// request. Await it only outside the dispatch loop; awaiting it in an
6026    /// incoming handler deadlocks just like [`SentRequest::block_task`].
6027    ///
6028    /// # Errors
6029    ///
6030    /// The returned future delivers preparation, publication, and response errors.
6031    pub fn block_task(self) -> impl Future<Output = Result<T, crate::Error>> {
6032        self.into_sent_request(false).block_task()
6033    }
6034
6035    /// Publish now and discard the eventual response without cancelling.
6036    ///
6037    /// # Errors
6038    ///
6039    /// Returns immediate preparation or enqueue failures. Later local
6040    /// transformation errors and peer response errors are discarded along with
6041    /// successful responses. Transport failures still propagate through the
6042    /// connection future. Retained [`RequestCancellationHandle`] values can
6043    /// still explicitly cancel the request while it remains pending.
6044    pub fn detach(self) -> Result<(), crate::Error> {
6045        let result = self.publication.publish();
6046        self.sent.detach();
6047        result
6048    }
6049
6050    /// Register an ordered callback, then publish the request.
6051    ///
6052    /// Ordering is selected before publication, even when the connection runs
6053    /// concurrently. See [`PreparedRequest`] for barrier limits and deadlock risks.
6054    ///
6055    /// # Errors
6056    ///
6057    /// Returns an error if the callback task cannot be registered, without
6058    /// publishing the request. Preparation and publication errors are delivered
6059    /// to the callback. Returning an error from the callback ends the connection.
6060    #[track_caller]
6061    pub fn on_receiving_result<F>(
6062        self,
6063        task: impl FnOnce(Result<T, crate::Error>) -> F + 'static + Send,
6064    ) -> Result<(), crate::Error>
6065    where
6066        T: 'static,
6067        F: Future<Output = Result<(), crate::Error>> + 'static + Send,
6068    {
6069        self.consume_with(move |response| match response {
6070            Ok(result) => Either::Left(task(result)),
6071            Err(error) => Either::Right(future::ready(Err(error))),
6072        })
6073    }
6074
6075    /// Register an ordered success callback, then publish the request.
6076    ///
6077    /// Errors are forwarded to `responder`, as with
6078    /// [`SentRequest::on_receiving_ok_result`].
6079    ///
6080    /// # Errors
6081    ///
6082    /// Returns a task-registration error without publishing the request.
6083    /// Preparation, publication, and response errors are forwarded to `responder`.
6084    /// Returning an error from the callback ends the connection.
6085    #[track_caller]
6086    pub fn on_receiving_ok_result<F, Q: Protocol>(
6087        self,
6088        responder: Responder<T, Q>,
6089        task: impl FnOnce(T, Responder<T, Q>) -> F + 'static + Send,
6090    ) -> Result<(), crate::Error>
6091    where
6092        T: JsonRpcResponse,
6093        F: Future<Output = Result<(), crate::Error>> + 'static + Send,
6094    {
6095        self.on_receiving_result(async move |result| match result {
6096            Ok(value) => task(value, responder).await,
6097            Err(error) => responder.respond_with_error(error),
6098        })
6099    }
6100
6101    /// Register ordered response forwarding, then publish the request.
6102    ///
6103    /// Cancellation and response errors propagate as with
6104    /// [`SentRequest::forward_response_to`].
6105    ///
6106    /// # Errors
6107    ///
6108    /// Returns a task-registration error without publishing the request.
6109    /// Preparation, publication, and response errors are forwarded to `responder`.
6110    #[track_caller]
6111    pub fn forward_response_to<Q: Protocol>(
6112        self,
6113        responder: Responder<T, Q>,
6114    ) -> Result<(), crate::Error>
6115    where
6116        T: JsonRpcResponse,
6117    {
6118        self.forward_cancellation_from(responder.cancellation())
6119            .consume_with(async move |response| {
6120                responder.respond_with_result(response.unwrap_or_else(Err))
6121            })
6122    }
6123
6124    fn into_sent_request(self, ordered: bool) -> SentRequest<T, P> {
6125        if ordered {
6126            self.sent.response_ordering.mark_ordered();
6127        }
6128        // Publication errors also settle the response channel.
6129        drop(self.publication.publish());
6130        self.sent
6131    }
6132
6133    #[track_caller]
6134    fn consume_with<F>(
6135        self,
6136        handle: impl FnOnce(Result<Result<T, crate::Error>, crate::Error>) -> F + 'static + Send,
6137    ) -> Result<(), crate::Error>
6138    where
6139        T: 'static,
6140        F: Future<Output = Result<(), crate::Error>> + 'static + Send,
6141    {
6142        let published_tx = self.register_consumer(handle)?;
6143        drop(self.publication.publish());
6144        // Keep the cancellation guard here until publication completes. Even
6145        // destruction of the registered task cannot cancel before enqueueing.
6146        drop(published_tx.send(self.sent));
6147        Ok(())
6148    }
6149
6150    #[track_caller]
6151    fn register_consumer<F>(
6152        &self,
6153        handle: impl FnOnce(Result<Result<T, crate::Error>, crate::Error>) -> F + 'static + Send,
6154    ) -> Result<oneshot::Sender<SentRequest<T, P>>, crate::Error>
6155    where
6156        T: 'static,
6157        F: Future<Output = Result<(), crate::Error>> + 'static + Send,
6158    {
6159        self.sent.response_ordering.mark_ordered();
6160        let (published_tx, published_rx) = oneshot::channel::<SentRequest<T, P>>();
6161        Task::new(Location::caller(), async move {
6162            match published_rx.await {
6163                Ok(sent) => sent.handle_response(handle).await,
6164                // Publication was abandoned before the consumer took ownership.
6165                Err(_) => Ok(()),
6166            }
6167        })
6168        .spawn(&self.sent.task_tx)?;
6169        Ok(published_tx)
6170    }
6171}
6172
6173#[derive(Clone, Debug)]
6174pub(crate) struct SentRequestCancellationDisarm {
6175    state: Arc<AtomicU8>,
6176}
6177
6178#[repr(u8)]
6179enum OutgoingCancellationState {
6180    Unpublished,
6181    Armed,
6182    Disarmed,
6183}
6184
6185impl SentRequestCancellationDisarm {
6186    fn new() -> Self {
6187        Self {
6188            state: Arc::new(AtomicU8::new(OutgoingCancellationState::Unpublished as u8)),
6189        }
6190    }
6191
6192    fn disarm(&self) {
6193        self.state
6194            .store(OutgoingCancellationState::Disarmed as u8, Ordering::Release);
6195    }
6196
6197    fn arm(&self) -> bool {
6198        self.state
6199            .compare_exchange(
6200                OutgoingCancellationState::Unpublished as u8,
6201                OutgoingCancellationState::Armed as u8,
6202                Ordering::AcqRel,
6203                Ordering::Acquire,
6204            )
6205            .is_ok()
6206    }
6207
6208    fn take_armed(&self) -> bool {
6209        self.state
6210            .compare_exchange(
6211                OutgoingCancellationState::Armed as u8,
6212                OutgoingCancellationState::Disarmed as u8,
6213                Ordering::AcqRel,
6214                Ordering::Acquire,
6215            )
6216            .is_ok()
6217    }
6218
6219    fn is_armed(&self) -> bool {
6220        self.state.load(Ordering::Acquire) == OutgoingCancellationState::Armed as u8
6221    }
6222}
6223
6224/// Explicit cancellation control for one outgoing request.
6225///
6226/// Obtain this handle from [`PreparedRequest::cancellation_handle`] or
6227/// [`SentRequest::cancellation_handle`] before consuming the request. It retains
6228/// neither the response consumer nor application callback, so cancellation can
6229/// be requested without discarding the eventual response. It does not keep the
6230/// connection driver or response consumer alive, or abort local callback work.
6231///
6232/// Clones share the request's cancellation state with [`SentRequest::cancel`],
6233/// forwarded cancellation, and request-drop automatic cancellation. At most one
6234/// cancellation notification is attempted, on the original request's
6235/// connection. It is a plain `$/cancel_request`, even for a request sent to a
6236/// successor in a `proxy/successor` envelope. Dropping this handle neither cancels the request nor disables its
6237/// automatic cancellation.
6238///
6239/// Cancellation before publication is a no-op and is not remembered for later
6240/// publication. A call racing publication may also be a no-op; call after the
6241/// publishing method returns to target a pending request. Once the SDK routes a
6242/// response or fails the request, subsequent cancellation calls are no-ops,
6243/// even if its callback has not yet run. Detaching the request suppresses only
6244/// automatic cancellation; retained handles can still explicitly cancel it.
6245///
6246/// This controls outgoing requests, unlike [`RequestCancellation`], which
6247/// observes a peer's cancellation of an incoming request.
6248#[derive(Clone)]
6249pub struct RequestCancellationHandle {
6250    message_tx: OutgoingMessageTx,
6251    request_id: RawJsonRpcId,
6252    disarm: SentRequestCancellationDisarm,
6253}
6254
6255impl RequestCancellationHandle {
6256    /// Ask the peer to cancel this request without discarding its response.
6257    ///
6258    /// Cancellation is cooperative: the peer may respond normally or with a
6259    /// cancellation error. Repeated calls, including calls through other clones
6260    /// or the original request, return `Ok(())` without sending another
6261    /// notification. Calls before publication or after settlement are no-ops.
6262    /// An attempt begun before settlement may still enqueue afterward.
6263    ///
6264    /// `Ok(())` means this call encountered no immediate error, not that a
6265    /// notification was sent or the peer stopped work. This method does not
6266    /// wait for transmission or acknowledgment.
6267    ///
6268    /// # Errors
6269    ///
6270    /// Only the call that attempts to send reports serialization or enqueue
6271    /// failure. A failed send is not retried by later cancellation calls.
6272    pub fn cancel(&self) -> Result<(), crate::Error> {
6273        if !self.disarm.take_armed() {
6274            return Ok(());
6275        }
6276
6277        // Build the notification lazily: most requests are never cancelled,
6278        // so this avoids serializing a notification per outgoing request.
6279        //
6280        // `$/cancel_request` is hop-local and always sent plain, even for a
6281        // request sent to a successor: its `requestId` names the
6282        // `proxy/successor` request on this connection.
6283        let untyped = crate::v1::schema::CancelRequestNotification::new(self.request_id.clone())
6284            .to_untyped_message()?;
6285
6286        send_raw_message(&self.message_tx, OutgoingMessage::Notification { untyped })
6287    }
6288}
6289
6290impl Debug for RequestCancellationHandle {
6291    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
6292        formatter
6293            .debug_struct("RequestCancellationHandle")
6294            .field("request_id", &self.request_id)
6295            .field("armed", &self.disarm.is_armed())
6296            .finish_non_exhaustive()
6297    }
6298}
6299
6300#[derive(Debug)]
6301struct SentRequestCancellation {
6302    handle: RequestCancellationHandle,
6303    cancel_on_drop: bool,
6304}
6305
6306impl SentRequestCancellation {
6307    fn new(message_tx: OutgoingMessageTx, request_id: RawJsonRpcId) -> Self {
6308        Self {
6309            handle: RequestCancellationHandle {
6310                message_tx,
6311                request_id,
6312                disarm: SentRequestCancellationDisarm::new(),
6313            },
6314            cancel_on_drop: true,
6315        }
6316    }
6317
6318    fn disarm(&self) {
6319        self.handle.disarm.disarm();
6320    }
6321
6322    fn disarm_handle(&self) -> SentRequestCancellationDisarm {
6323        self.handle.disarm.clone()
6324    }
6325
6326    fn send(&self) -> Result<(), crate::Error> {
6327        self.handle.cancel()
6328    }
6329}
6330
6331impl Drop for SentRequestCancellation {
6332    fn drop(&mut self) {
6333        if !self.cancel_on_drop {
6334            return;
6335        }
6336        if let Err(error) = self.send() {
6337            tracing::debug!(
6338                error = ?crate::util::redacted_error(error.code),
6339                "failed to auto-cancel dropped request"
6340            );
6341        }
6342    }
6343}
6344
6345/// Await the response payload for an outgoing request, watching `sources` for
6346/// cancellation of the upstream requests it was registered with.
6347///
6348/// When any source reports cancellation, a `$/cancel_request` is forwarded to
6349/// the outgoing request (at most once, shared with [`SentRequest::cancel`] and
6350/// drop-time auto-cancellation), and the response is *still* awaited: the peer
6351/// always answers, with normal data or a cancellation error.
6352///
6353/// Watching is deliberately bounded by response arrival so that completed
6354/// requests do not leak waiters on markers that will never fire.
6355async fn await_response_forwarding_cancellation(
6356    response_rx: oneshot::Receiver<ResponsePayload>,
6357    cancellation: &SentRequestCancellation,
6358    sources: &[RequestCancellation],
6359) -> Result<ResponsePayload, oneshot::Canceled> {
6360    // Failing to forward the cancellation must not abort the wait: the
6361    // response (normal data or a cancellation error) may still arrive and
6362    // must still be processed.
6363    let forward_cancellation = || {
6364        if let Err(error) = cancellation.send() {
6365            tracing::debug!(
6366                error = ?crate::util::redacted_error(error.code),
6367                "failed to forward cancellation to downstream request"
6368            );
6369        }
6370    };
6371
6372    let response = if sources.is_empty() {
6373        response_rx.await
6374    } else if sources.iter().any(RequestCancellation::is_cancelled) {
6375        forward_cancellation();
6376        response_rx.await
6377    } else {
6378        let cancelled = sources.iter().map(|source| source.state.signal_rx.clone());
6379        match future::select(future::select_all(cancelled), response_rx).await {
6380            Either::Left((_, response_rx)) => {
6381                forward_cancellation();
6382                response_rx.await
6383            }
6384            Either::Right((response, _)) => response,
6385        }
6386    };
6387
6388    cancellation.disarm();
6389    response
6390}
6391
6392impl<T: Debug, P: Protocol> Debug for SentRequest<T, P> {
6393    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
6394        let mut debug = f.debug_struct("SentRequest");
6395        debug
6396            .field("id", &self.id)
6397            .field("method", &self.method)
6398            .field("task_tx", &self.task_tx)
6399            .field("response_rx", &self.response_rx);
6400        debug
6401            .field("cancellation", &self.cancellation)
6402            .field("cancellation_sources", &self.cancellation_sources);
6403        debug.finish_non_exhaustive()
6404    }
6405}
6406
6407impl<P: Protocol> SentRequest<serde_json::Value, P> {
6408    fn new(
6409        id: HandleId<P>,
6410        method: String,
6411        task_tx: mpsc::UnboundedSender<Task>,
6412        response_rx: oneshot::Receiver<ResponsePayload>,
6413        cancellation: SentRequestCancellation,
6414        response_ordering: ResponseOrdering,
6415    ) -> Self {
6416        Self {
6417            id,
6418            method,
6419            response_rx,
6420            task_tx,
6421            to_result: Box::new(|result| result),
6422            cancellation,
6423            response_ordering,
6424            cancellation_sources: Vec::new(),
6425        }
6426    }
6427}
6428
6429impl<T, P: Protocol> SentRequest<T, P> {
6430    /// Detach this request handle without waiting for its response.
6431    ///
6432    /// The response will be discarded when it arrives. This also disables the
6433    /// drop-time automatic cancellation described in
6434    /// [Drop Behavior](Self#drop-behavior), so use it for requests whose
6435    /// eventual response should be ignored, but which should keep running on
6436    /// the peer. The peer is still expected to answer the JSON-RPC request
6437    /// eventually; use a notification instead when no response is expected at
6438    /// all.
6439    ///
6440    /// To ask the peer to stop the request, call `cancel` instead, or drop the
6441    /// handle while automatic cancellation is enabled. A retained
6442    /// [`RequestCancellationHandle`] can still explicitly cancel the detached
6443    /// request until the SDK receives its response or fails it.
6444    pub fn detach(mut self) {
6445        self.cancellation.cancel_on_drop = false;
6446    }
6447
6448    /// Send a `$/cancel_request` notification for this outgoing request.
6449    ///
6450    /// The notification goes over the connection the original request used,
6451    /// with that request's ID, so this is the preferred way to cancel a
6452    /// [`SentRequest`] when the request handle is still available. It is sent
6453    /// plain, never wrapped in `proxy/successor`: for a request sent to a
6454    /// successor, the ID names the `proxy/successor` request on this
6455    /// connection, as the proxy chains RFD specifies.
6456    ///
6457    /// At most one cancellation attempt is made per request, shared with
6458    /// retained handles, forwarded cancellation, and automatic cancellation
6459    /// described in [Drop Behavior](Self#drop-behavior). Later calls return
6460    /// `Ok(())` without another attempt, including when the first attempt failed.
6461    /// Once the SDK has routed the response, a new call is a no-op; an attempt
6462    /// begun before settlement may still enqueue afterward.
6463    ///
6464    /// `Ok(())` means this call encountered no immediate error, not that a
6465    /// notification was sent or the peer stopped work.
6466    ///
6467    /// Errors are only reported by the call that attempts to send the
6468    /// notification.
6469    pub fn cancel(&self) -> Result<(), crate::Error> {
6470        self.cancellation.send()
6471    }
6472
6473    /// Obtain a handle that remains usable after this request is consumed.
6474    ///
6475    /// The handle shares the once-only cancellation state used by
6476    /// [`cancel`](Self::cancel), response routing, and automatic request-drop
6477    /// cancellation, but has no cancel-on-drop behavior of its own.
6478    #[must_use]
6479    pub fn cancellation_handle(&self) -> RequestCancellationHandle {
6480        self.cancellation.handle.clone()
6481    }
6482
6483    /// Forward cancellation of another request to this one.
6484    ///
6485    /// When the request that `source` belongs to is cancelled by its peer,
6486    /// a `$/cancel_request` for *this* request is sent to its peer, plain and
6487    /// with this request's ID, as [`cancel`](Self::cancel) sends it. The response is still awaited
6488    /// and delivered as usual (normal data or a cancellation error), so this
6489    /// composes with [`block_task`](Self::block_task) and
6490    /// [`on_receiving_result`](Self::on_receiving_result).
6491    ///
6492    /// This is the building block for proxies that forward a request with
6493    /// custom logic instead of [`forward_response_to`](Self::forward_response_to)
6494    /// (which wires this up automatically from its responder). Without it,
6495    /// custom forwarding *absorbs* cancellation: the upstream marker is still
6496    /// set, but nothing is sent downstream.
6497    ///
6498    /// ```
6499    /// # use agent_client_protocol::{ConnectionTo, Error, Responder, UntypedRole};
6500    /// # use agent_client_protocol_test::{MyRequest, MyResponse};
6501    /// # async fn example(request: MyRequest, responder: Responder<MyResponse>, backend: ConnectionTo<UntypedRole>) -> Result<(), Error> {
6502    /// backend
6503    ///     .send_request(request)
6504    ///     .forward_cancellation_from(responder.cancellation())
6505    ///     .on_receiving_result(async move |result| {
6506    ///         // Custom result handling, e.g. bookkeeping or rewriting.
6507    ///         responder.respond_with_result(result)
6508    ///     })?;
6509    /// # Ok(())
6510    /// # }
6511    /// ```
6512    ///
6513    /// May be called multiple times; cancellation of any registered source
6514    /// triggers the forwarding (at most one `$/cancel_request` is ever sent
6515    /// per request). Sources are observed while the response is being
6516    /// awaited — that is, once the handle is consumed with
6517    /// [`block_task`](Self::block_task),
6518    /// [`on_receiving_result`](Self::on_receiving_result), or
6519    /// [`forward_response_to`](Self::forward_response_to); a source that was
6520    /// already cancelled by then is honored immediately.
6521    pub fn forward_cancellation_from(mut self, source: RequestCancellation) -> Self {
6522        self.cancellation_sources.push(source);
6523        self
6524    }
6525}
6526
6527impl<T, P: Protocol> SentRequest<T, P> {
6528    /// The same request handle with a version-neutral [`Raw`] request ID, for
6529    /// code that is not tied to one protocol version. This never fails.
6530    pub fn into_raw(self) -> SentRequest<T, Raw> {
6531        self.retag_id(HandleId::into_raw)
6532    }
6533
6534    fn retag_id<Q: Protocol>(
6535        self,
6536        retag: impl FnOnce(HandleId<P>) -> HandleId<Q>,
6537    ) -> SentRequest<T, Q> {
6538        SentRequest {
6539            id: retag(self.id),
6540            method: self.method,
6541            task_tx: self.task_tx,
6542            response_rx: self.response_rx,
6543            to_result: self.to_result,
6544            cancellation: self.cancellation,
6545            response_ordering: self.response_ordering,
6546            cancellation_sources: self.cancellation_sources,
6547        }
6548    }
6549}
6550
6551impl<T> SentRequest<T, Raw> {
6552    /// Convert this version-neutral request handle to protocol `Q`'s handle.
6553    ///
6554    /// Only the request ID's type changes. The SDK never assigns `null` to
6555    /// requests it sends, so this succeeds for every marker.
6556    pub fn into_protocol<Q: Protocol>(self) -> Result<SentRequest<T, Q>, crate::Error> {
6557        let id = self.id.clone().into_protocol()?;
6558        Ok(self.retag_id(|_| id))
6559    }
6560}
6561
6562impl<T, P: Protocol> SentRequest<T, P> {
6563    /// The id of the outgoing request, as this request's protocol version
6564    /// types it. It is the ID written to the wire; the SDK never assigns
6565    /// `null`.
6566    #[must_use]
6567    pub fn id(&self) -> &P::RequestId {
6568        self.id.typed()
6569    }
6570
6571    /// The id of the outgoing request in the version-neutral form used by
6572    /// routers, forwarders and tracing. It is the same ID as
6573    /// [`id`](Self::id).
6574    #[must_use]
6575    pub fn raw_id(&self) -> &RawJsonRpcId {
6576        self.id.raw()
6577    }
6578
6579    /// The method of the request this is in response to.
6580    #[must_use]
6581    pub fn method(&self) -> &str {
6582        &self.method
6583    }
6584
6585    /// Map a JSON-RPC error response to a result of the same type.
6586    ///
6587    /// The recovery function only sees error responses from the peer, not
6588    /// local failures to decode a successful response. Return `Ok` to treat
6589    /// the error as success, or `Err` to keep failing.
6590    #[cfg_attr(not(feature = "unstable_protocol_v2"), allow(dead_code))]
6591    pub(crate) fn recover_error(
6592        self,
6593        recover: impl FnOnce(crate::Error) -> Result<T, crate::Error> + 'static + Send,
6594    ) -> SentRequest<T, P>
6595    where
6596        T: 'static,
6597    {
6598        let to_result = self.to_result;
6599        SentRequest {
6600            to_result: Box::new(move |result| match result {
6601                Ok(value) => to_result(Ok(value)),
6602                Err(error) => recover(error),
6603            }),
6604            ..self
6605        }
6606    }
6607
6608    /// Map a successful JSON-RPC response into an application type.
6609    ///
6610    /// The mapped type does not need to implement [`JsonRpcResponse`]. The
6611    /// mapper runs at most once and may consume captured state. JSON-RPC error
6612    /// responses bypass the mapper. The mapped type may carry a non-`'static`
6613    /// lifetime when it is consumed with [`block_task`](Self::block_task);
6614    /// callback-style consumption still requires a `'static` mapped type
6615    /// because its work is spawned onto the connection.
6616    pub fn map<U>(
6617        self,
6618        map_fn: impl FnOnce(T) -> Result<U, crate::Error> + 'static + Send,
6619    ) -> SentRequest<U, P>
6620    where
6621        T: 'static,
6622    {
6623        SentRequest {
6624            id: self.id,
6625            method: self.method,
6626            response_rx: self.response_rx,
6627            task_tx: self.task_tx,
6628            to_result: Box::new(move |result| map_fn((self.to_result)(result)?)),
6629            cancellation: self.cancellation,
6630            response_ordering: self.response_ordering,
6631            cancellation_sources: self.cancellation_sources,
6632        }
6633    }
6634
6635    /// Forward the response (success or error) to a request context when it arrives.
6636    ///
6637    /// This is a convenience method for proxying messages between connections. When the
6638    /// response arrives, it will be automatically sent to the provided request context,
6639    /// whether it's a successful response or an error.
6640    ///
6641    /// # Example: Proxying requests
6642    ///
6643    /// ```
6644    /// # use agent_client_protocol::UntypedRole;
6645    /// # use agent_client_protocol::{Builder, ConnectionTo};
6646    /// # use agent_client_protocol_test::*;
6647    /// # async fn example(cx: ConnectionTo<UntypedRole>) -> Result<(), agent_client_protocol::Error> {
6648    /// // Set up backend connection builder
6649    /// let backend = UntypedRole.builder()
6650    ///     .on_receive_request(async |req: MyRequest, responder, cx| {
6651    ///         responder.respond(MyResponse { status: "ok".into() })
6652    ///     }, agent_client_protocol::on_receive_request!());
6653    ///
6654    /// // Spawn backend and get a context to send to it
6655    /// let backend_connection = cx.spawn_connection(backend, MockTransport)?;
6656    ///
6657    /// // Set up proxy that forwards requests to backend
6658    /// UntypedRole.builder()
6659    ///     .on_receive_request({
6660    ///         let backend_connection = backend_connection.clone();
6661    ///         async move |req: MyRequest, responder, cx| {
6662    ///             // Forward the request to backend and proxy the response back
6663    ///             backend_connection.send_request(req)
6664    ///                 .forward_response_to(responder)?;
6665    ///             Ok(())
6666    ///         }
6667    ///     }, agent_client_protocol::on_receive_request!());
6668    /// # Ok(())
6669    /// # }
6670    /// ```
6671    ///
6672    /// # Type Safety
6673    ///
6674    /// The request context's response type must match the request's response type,
6675    /// ensuring type-safe message forwarding.
6676    ///
6677    /// # When to Use
6678    ///
6679    /// Use this when:
6680    /// - You're implementing a proxy or gateway pattern
6681    /// - You want to forward responses without processing them
6682    /// - The response types match between the outgoing request and incoming request
6683    ///
6684    /// This is equivalent to calling `on_receiving_result` and manually forwarding
6685    /// the result, with two proxy-specific additions:
6686    ///
6687    /// - If the pending response cannot be delivered, the incoming request is
6688    ///   answered with an internal error instead of being left unanswered.
6689    ///   Known clean incoming EOF is delivered like any other response
6690    ///   error; an unexpected response-channel loss is forwarded as an outer
6691    ///   consumption error.
6692    /// - When the peer cancels the incoming request, the cancellation is
6693    ///   forwarded to the outgoing request, and the downstream response
6694    ///   (normal data or a cancellation error) is still forwarded back. This is
6695    ///   equivalent to registering the responder's marker with
6696    ///   `forward_cancellation_from`.
6697    #[track_caller]
6698    pub fn forward_response_to<Q: Protocol>(
6699        self,
6700        responder: Responder<T, Q>,
6701    ) -> Result<(), crate::Error>
6702    where
6703        T: JsonRpcResponse,
6704    {
6705        let this = self.forward_cancellation_from(responder.cancellation());
6706
6707        this.consume_with(async move |response| {
6708            // An unexpected response-channel loss (outer `Err`) is forwarded
6709            // as an error: the incoming request must not be left unanswered.
6710            responder.respond_with_result(response.unwrap_or_else(Err))
6711        })
6712    }
6713
6714    /// Spawn the response-consumption task shared by
6715    /// [`on_receiving_result`](Self::on_receiving_result) and
6716    /// [`forward_response_to`](Self::forward_response_to).
6717    ///
6718    /// The task awaits the response (forwarding cancellation from registered
6719    /// sources while waiting, converts the payload, and invokes `handle` with
6720    /// the typed result (`Ok(Result<T, _>)`). The dispatch loop's ack, if any,
6721    /// is sent after `handle` completes.
6722    ///
6723    /// Clean incoming EOF is delivered as `Ok(Err(error))`, just like
6724    /// a peer response error, so callback-style consumers still run. If the
6725    /// response channel disappears for another reason, `handle` receives an
6726    /// outer `Err` describing that unexpected loss; there is no ack then.
6727    #[track_caller]
6728    fn consume_with<F>(
6729        self,
6730        handle: impl FnOnce(Result<Result<T, crate::Error>, crate::Error>) -> F + 'static + Send,
6731    ) -> Result<(), crate::Error>
6732    where
6733        T: 'static,
6734        F: Future<Output = Result<(), crate::Error>> + 'static + Send,
6735    {
6736        self.response_ordering.mark_ordered();
6737        let task_tx = self.task_tx.clone();
6738        Task::new(Location::caller(), self.handle_response(handle)).spawn(&task_tx)
6739    }
6740
6741    fn handle_response<F>(
6742        self,
6743        handle: impl FnOnce(Result<Result<T, crate::Error>, crate::Error>) -> F + 'static + Send,
6744    ) -> impl Future<Output = Result<(), crate::Error>> + Send
6745    where
6746        T: 'static,
6747        F: Future<Output = Result<(), crate::Error>> + 'static + Send,
6748    {
6749        let method = self.method;
6750        let response_rx = self.response_rx;
6751        let to_result = self.to_result;
6752        let cancellation = self.cancellation;
6753        let cancellation_sources = self.cancellation_sources;
6754        async move {
6755            let response = await_response_forwarding_cancellation(
6756                response_rx,
6757                &cancellation,
6758                &cancellation_sources,
6759            )
6760            .await;
6761
6762            match response {
6763                Ok(ResponsePayload { result, ack_tx }) => {
6764                    let typed_result = to_result(result);
6765
6766                    let outcome = handle(Ok(typed_result)).await;
6767
6768                    // Ack AFTER the handler completes - this is the key
6769                    // difference from block_task. The dispatch loop waits for
6770                    // this ack.
6771                    if let Some(tx) = ack_tx {
6772                        let _ = tx.send(());
6773                    }
6774
6775                    outcome
6776                }
6777                Err(err) => {
6778                    handle(Err(crate::util::internal_error(format!(
6779                        "response to `{method}` never received: {err}"
6780                    ))))
6781                    .await
6782                }
6783            }
6784        }
6785    }
6786
6787    /// Block the current task until the response is received.
6788    ///
6789    /// **Warning:** This method blocks the current async task. It is safe only when that task
6790    /// already runs outside the dispatch loop, such as the foreground future passed to
6791    /// `connect_with` or a task created with [`ConnectionTo::spawn`]. Using it directly in a
6792    /// handler callback will deadlock the connection.
6793    ///
6794    /// # Safe Usage (outside the dispatch loop)
6795    ///
6796    /// ```no_run
6797    /// # use agent_client_protocol_test::*;
6798    /// # async fn example() -> Result<(), agent_client_protocol::Error> {
6799    /// # let connection = mock_connection();
6800    /// connection.on_receive_request(async |req: MyRequest, responder, cx| {
6801    ///     // Spawn a task to handle the request
6802    ///     cx.spawn({
6803    ///         let connection = cx.clone();
6804    ///         async move {
6805    ///             // Safe: We're in a spawned task, not blocking the event loop
6806    ///             let response = connection.send_request(OtherRequest {})
6807    ///                 .block_task()
6808    ///                 .await?;
6809    ///
6810    ///             // Process the response...
6811    ///             Ok(())
6812    ///         }
6813    ///     })?;
6814    ///
6815    ///     // Respond immediately
6816    ///     responder.respond(MyResponse { status: "ok".into() })
6817    /// }, agent_client_protocol::on_receive_request!())
6818    /// # .connect_to(agent_client_protocol_test::MockTransport).await?;
6819    /// # Ok(())
6820    /// # }
6821    /// ```
6822    ///
6823    /// # Unsafe Usage (in handlers - will deadlock!)
6824    ///
6825    /// ```no_run
6826    /// # use agent_client_protocol_test::*;
6827    /// # async fn example() -> Result<(), agent_client_protocol::Error> {
6828    /// # let connection = mock_connection();
6829    /// connection.on_receive_request(async |req: MyRequest, responder, cx| {
6830    ///     // ❌ DEADLOCK: Handler blocks event loop, which can't process the response
6831    ///     let response = cx.send_request(OtherRequest {})
6832    ///         .block_task()
6833    ///         .await?;
6834    ///
6835    ///     responder.respond(MyResponse { status: response.value })
6836    /// }, agent_client_protocol::on_receive_request!())
6837    /// # .connect_to(agent_client_protocol_test::MockTransport).await?;
6838    /// # Ok(())
6839    /// # }
6840    /// ```
6841    ///
6842    /// # When to Use
6843    ///
6844    /// Use this method when:
6845    /// - Your current task already runs outside the dispatch loop
6846    /// - You need the response value to proceed with your logic
6847    /// - Linear control flow is more natural than callbacks
6848    ///
6849    /// For handler callbacks, use [`on_receiving_result`](Self::on_receiving_result) instead.
6850    pub async fn block_task(self) -> Result<T, crate::Error> {
6851        let response = await_response_forwarding_cancellation(
6852            self.response_rx,
6853            &self.cancellation,
6854            &self.cancellation_sources,
6855        )
6856        .await;
6857
6858        match response {
6859            Ok(ResponsePayload { result, ack_tx }) => {
6860                // Blocking consumers ack before converting or returning the
6861                // value, so dispatch can continue while the caller processes it.
6862                if let Some(tx) = ack_tx {
6863                    let _ = tx.send(());
6864                }
6865                (self.to_result)(result)
6866            }
6867            Err(err) => Err(crate::util::internal_error(format!(
6868                "response to `{}` never received: {}",
6869                self.method, err
6870            ))),
6871        }
6872    }
6873
6874    /// Block the current task and transform the typed result before releasing
6875    /// the ordered-response barrier.
6876    ///
6877    /// Framework lifecycle code uses this when success transfers local state
6878    /// to the returned value while an error must drop that state before later
6879    /// messages from the same transport frame are dispatched. The synchronous
6880    /// transform must not wait for additional connection traffic.
6881    pub(crate) async fn block_task_with_ordered_result<U>(
6882        self,
6883        transform: impl FnOnce(Result<T, crate::Error>) -> Result<U, crate::Error>,
6884    ) -> Result<U, crate::Error> {
6885        let response = await_response_forwarding_cancellation(
6886            self.response_rx,
6887            &self.cancellation,
6888            &self.cancellation_sources,
6889        )
6890        .await;
6891
6892        let (result, ack_tx) = match response {
6893            Ok(ResponsePayload { result, ack_tx }) => ((self.to_result)(result), ack_tx),
6894            Err(error) => (
6895                Err(crate::util::internal_error(format!(
6896                    "response to `{}` never received: {error}",
6897                    self.method
6898                ))),
6899                None,
6900            ),
6901        };
6902
6903        let outcome = transform(result);
6904        if let Some(acknowledgment) = ack_tx {
6905            let _ = acknowledgment.send(());
6906        }
6907        outcome
6908    }
6909
6910    /// Schedule an async task to run when a successful response is received.
6911    ///
6912    /// This is a convenience wrapper around [`on_receiving_result`](Self::on_receiving_result)
6913    /// for the common pattern of forwarding errors to a request context while only processing
6914    /// successful responses.
6915    ///
6916    /// # Behavior
6917    ///
6918    /// - If the response is `Ok(value)`, your task receives the value and the request context
6919    /// - If the response is `Err(error)`, the error is automatically sent to `responder`
6920    ///   and your task is not called
6921    ///
6922    /// # Example: Chaining requests
6923    ///
6924    /// ```no_run
6925    /// # use agent_client_protocol_test::*;
6926    /// # async fn example() -> Result<(), agent_client_protocol::Error> {
6927    /// # let connection = mock_connection();
6928    /// connection.on_receive_request(async |req: ValidateRequest, responder, cx| {
6929    ///     // Send initial request
6930    ///     cx.send_request(ValidateRequest { data: req.data.clone() })
6931    ///         .on_receiving_ok_result(responder, async |validation, responder| {
6932    ///             // Only runs if validation succeeded
6933    ///             if validation.is_valid {
6934    ///                 // Respond to original request
6935    ///                 responder.respond(ValidateResponse { is_valid: true, error: None })
6936    ///             } else {
6937    ///                 responder.respond_with_error(agent_client_protocol::Error::internal_error().data("validation failed"))
6938    ///             }
6939    ///         })?;
6940    ///
6941    ///     Ok(())
6942    /// }, agent_client_protocol::on_receive_request!())
6943    /// # .connect_to(agent_client_protocol_test::MockTransport).await?;
6944    /// # Ok(())
6945    /// # }
6946    /// ```
6947    ///
6948    /// # Ordering
6949    ///
6950    /// Like [`on_receiving_result`](Self::on_receiving_result), response handling holds the
6951    /// dispatch loop through callback completion when ordered consumption is selected before a
6952    /// peer response is routed during its original dispatch. Pending-request failures delivered
6953    /// without an incoming response and delayed routes do not carry that barrier. The callback
6954    /// must not await later inbound traffic on the same connection. See the
6955    /// [`ordering`](crate::concepts::ordering) module for details.
6956    ///
6957    /// # When to Use
6958    ///
6959    /// Use this when:
6960    /// - You need to respond to a request based on another request's result
6961    /// - You want errors to automatically propagate to the request context
6962    /// - You only care about the success case
6963    ///
6964    /// For more control over error handling, use [`on_receiving_result`](Self::on_receiving_result).
6965    #[track_caller]
6966    pub fn on_receiving_ok_result<F, Q: Protocol>(
6967        self,
6968        responder: Responder<T, Q>,
6969        task: impl FnOnce(T, Responder<T, Q>) -> F + 'static + Send,
6970    ) -> Result<(), crate::Error>
6971    where
6972        F: Future<Output = Result<(), crate::Error>> + 'static + Send,
6973        T: JsonRpcResponse,
6974    {
6975        self.on_receiving_result(async move |result| match result {
6976            Ok(value) => task(value, responder).await,
6977            Err(err) => responder.respond_with_error(err),
6978        })
6979    }
6980
6981    /// Register an async callback to run when the response is received.
6982    ///
6983    /// This is the recommended way to select response handling from inside a handler because
6984    /// registration returns immediately. The response-consumption task waits concurrently for
6985    /// the response; once the response is dispatched, the ordered callback may hold the dispatch
6986    /// loop until it completes.
6987    ///
6988    /// # Example: Handle response in callback
6989    ///
6990    /// ```no_run
6991    /// # use agent_client_protocol_test::*;
6992    /// # async fn example() -> Result<(), agent_client_protocol::Error> {
6993    /// # let connection = mock_connection();
6994    /// connection.on_receive_request(async |req: MyRequest, responder, cx| {
6995    ///     // Send a request and schedule a callback for the response
6996    ///     cx.send_request(QueryRequest { id: 22 })
6997    ///         .on_receiving_result({
6998    ///             let connection = cx.clone();
6999    ///             async move |result| {
7000    ///                 match result {
7001    ///                     Ok(response) => {
7002    ///                         println!("Got response: {:?}", response);
7003    ///                         // Can send more messages here
7004    ///                         connection.send_notification(QueryComplete {})?;
7005    ///                         Ok(())
7006    ///                 }
7007    ///                     Err(error) => {
7008    ///                         eprintln!("Request failed: {}", error);
7009    ///                         Err(error)
7010    ///                     }
7011    ///                 }
7012    ///             }
7013    ///         })?;
7014    ///
7015    ///     // Handler continues immediately after registering the callback
7016    ///     responder.respond(MyResponse { status: "processing".into() })
7017    /// }, agent_client_protocol::on_receive_request!())
7018    /// # .connect_to(agent_client_protocol_test::MockTransport).await?;
7019    /// # Ok(())
7020    /// # }
7021    /// ```
7022    ///
7023    /// # Ordering
7024    ///
7025    /// When ordered consumption is selected before a peer response is routed during its original
7026    /// dispatch, the callback runs in a connection-managed task and the dispatch loop waits for
7027    /// it to complete before processing the next message.
7028    ///
7029    /// The barrier does not apply when the pending request is failed without an incoming response,
7030    /// such as on EOF. If the response was already routed, or an interceptor routes a retained
7031    /// [`ResponseRouter`] after its original dispatch, the callback still runs but cannot
7032    /// retroactively block messages that were already released.
7033    ///
7034    /// While the barrier is held, the callback must not await a later response, notification, or
7035    /// other inbound traffic on the same connection: that traffic cannot be dispatched until the
7036    /// callback completes. Spawn follow-up work with [`ConnectionTo::spawn`] and return, or use
7037    /// [`block_task`](Self::block_task) from a task already outside the dispatch loop.
7038    ///
7039    /// This differs from [`block_task`](Self::block_task), which does not select ordered
7040    /// consumption: dispatch remains free while the caller processes the delivered response.
7041    ///
7042    /// See the [`ordering`](crate::concepts::ordering) module for details on ordering guarantees
7043    /// and how to avoid deadlocks.
7044    ///
7045    /// # Error Handling
7046    ///
7047    /// If the scheduled task returns `Err`, the entire server will shut down. Make sure to handle
7048    /// errors appropriately within your task.
7049    ///
7050    /// # When to Use
7051    ///
7052    /// Use this method when:
7053    /// - You need to register response handling from a handler callback
7054    /// - You want a peer response callback to complete before later messages are dispatched
7055    /// - The callback performs bounded work that does not depend on later inbound traffic
7056    ///
7057    /// When already outside the dispatch loop and you do not need ordering guarantees, consider
7058    /// [`block_task`](Self::block_task).
7059    #[track_caller]
7060    pub fn on_receiving_result<F>(
7061        self,
7062        task: impl FnOnce(Result<T, crate::Error>) -> F + 'static + Send,
7063    ) -> Result<(), crate::Error>
7064    where
7065        T: 'static,
7066        F: Future<Output = Result<(), crate::Error>> + 'static + Send,
7067    {
7068        self.consume_with(move |response| match response {
7069            // Invoke the callback before constructing its future so the
7070            // response value does not need to be `Send` across an await.
7071            Ok(result) => Either::Left(task(result)),
7072            // A response that was never delivered fails the consuming
7073            // task instead of invoking the callback.
7074            Err(err) => Either::Right(future::ready(Err(err))),
7075        })
7076    }
7077}
7078
7079// ============================================================================
7080// IntoJrConnectionTransport Implementations
7081// ============================================================================
7082
7083/// A component that communicates over line streams.
7084///
7085/// `Lines` implements the [`ConnectTo`] trait for any pair of line-based streams
7086/// (a `Stream<Item = io::Result<String>>` for incoming and a `Sink<String>` for outgoing),
7087/// handling serialization of JSON-RPC messages to/from newline-delimited JSON.
7088/// Each line carries one JSON-RPC message. JSON-RPC batch arrays are not supported: an
7089/// incoming array is answered with a single invalid-request (`-32600`) error with `id: null`.
7090///
7091/// This is a lower-level primitive than [`ByteStreams`] that enables interception and
7092/// transformation of individual lines before they are parsed or after they are serialized.
7093/// This is particularly useful for debugging, logging, or implementing custom line-based
7094/// protocols.
7095///
7096/// An `Err` from the incoming stream ends the connection. A stream that decodes bytes itself
7097/// should replace invalid UTF-8, as [`ByteStreams`] does, instead of yielding an error for it.
7098///
7099/// # Use Cases
7100///
7101/// - **Line-by-line logging**: Intercept and log each line before parsing
7102/// - **Custom protocols**: Transform lines before/after JSON-RPC processing
7103/// - **Debugging**: Inspect raw message strings
7104/// - **Line filtering**: Skip or modify specific messages
7105///
7106/// Most users should use [`ByteStreams`] instead, which provides a simpler interface
7107/// for byte-based I/O.
7108///
7109/// [`ConnectTo`]: crate::ConnectTo
7110#[derive(Debug)]
7111pub struct Lines<OutgoingSink, IncomingStream> {
7112    outgoing: OutgoingSink,
7113    incoming: IncomingStream,
7114}
7115
7116impl<OutgoingSink, IncomingStream> Lines<OutgoingSink, IncomingStream>
7117where
7118    OutgoingSink: futures::Sink<String, Error = std::io::Error> + Send + 'static,
7119    IncomingStream: futures::Stream<Item = std::io::Result<String>> + Send + 'static,
7120{
7121    /// Create a new line stream transport.
7122    pub fn new(outgoing: OutgoingSink, incoming: IncomingStream) -> Self {
7123        Self { outgoing, incoming }
7124    }
7125
7126    fn into_channel_transport(self) -> (Channel, crate::ConnectionDriver) {
7127        let Self { outgoing, incoming } = self;
7128        let (channel_for_caller, channel_for_lines) = Channel::duplex();
7129        let Channel { mut rx, tx } = channel_for_lines;
7130        let (finish_tx, finish_rx) = oneshot::channel();
7131        let finish = async move {
7132            // Losing a finish handle is not a shutdown request.
7133            if finish_rx.await.is_err() {
7134                future::pending::<()>().await;
7135            }
7136        }
7137        .boxed()
7138        .shared();
7139        let outgoing_frames = futures::stream::poll_fn({
7140            let mut finish = finish.clone();
7141            let mut finishing = false;
7142            move |cx| {
7143                if !finishing && std::pin::Pin::new(&mut finish).poll(cx).is_ready() {
7144                    rx.close();
7145                    finishing = true;
7146                }
7147                rx.poll_next_unpin(cx)
7148            }
7149        });
7150        let discard_incoming = Arc::new(AtomicBool::new(false));
7151        let incoming = incoming.filter_map({
7152            let discard_incoming = discard_incoming.clone();
7153            move |item| {
7154                let discard = discard_incoming.load(Ordering::Acquire);
7155                future::ready((!discard || item.is_err()).then_some(item))
7156            }
7157        });
7158        let outgoing = transport_actor::transport_outgoing_lines_actor(outgoing_frames, outgoing)
7159            .boxed()
7160            .shared();
7161        let serve_self = Box::pin({
7162            let outgoing = outgoing.clone();
7163            async move {
7164                futures::try_join!(
7165                    outgoing,
7166                    transport_actor::transport_incoming_lines_actor(incoming, tx),
7167                )?;
7168                Ok(())
7169            }
7170        });
7171        let server_future = crate::ConnectionDriver::with_finish(
7172            async move {
7173                match future::select(finish, serve_self).await {
7174                    Either::Left(((), serve_self)) => {
7175                        discard_incoming.store(true, Ordering::Release);
7176                        // Keep reading while flushing, but do not require remote
7177                        // read EOF. Poll incoming errors before clean sink drain.
7178                        match future::select(serve_self, outgoing).await {
7179                            Either::Left((result, _)) | Either::Right((result, _)) => result,
7180                        }
7181                    }
7182                    Either::Right((result, _)) => result,
7183                }
7184            },
7185            move || {
7186                let _ = finish_tx.send(());
7187            },
7188        );
7189
7190        (channel_for_caller, server_future)
7191    }
7192}
7193
7194impl<OutgoingSink, IncomingStream, R: Role> ConnectTo<R> for Lines<OutgoingSink, IncomingStream>
7195where
7196    OutgoingSink: futures::Sink<String, Error = std::io::Error> + Send + 'static,
7197    IncomingStream: futures::Stream<Item = std::io::Result<String>> + Send + 'static,
7198{
7199    async fn connect_to(self, client: impl ConnectTo<R::Counterpart>) -> Result<(), crate::Error> {
7200        let (channel, mut serve_self) = self.into_channel_transport();
7201        let mut finish = serve_self
7202            .take_finish()
7203            .expect("built-in Lines transport supports explicit finishing");
7204        let client_future = Box::pin(ConnectTo::<R>::connect_to(channel, client));
7205
7206        match futures::future::select(client_future, serve_self).await {
7207            Either::Left((result, serve_self)) => {
7208                result?;
7209                // The local bridge has transferred all accepted client output.
7210                // Finish the physical sink without waiting for remote read EOF.
7211                finish.request();
7212                serve_self.await
7213            }
7214            Either::Right((result, _)) => result,
7215        }
7216    }
7217
7218    fn into_channel_and_future(self) -> (Channel, Option<crate::ConnectionDriver>) {
7219        let (channel, driver) = self.into_channel_transport();
7220        (channel, Some(driver))
7221    }
7222}
7223
7224/// A component that communicates over byte streams (stdin/stdout, sockets, pipes, etc.).
7225///
7226/// `ByteStreams` implements the [`ConnectTo`] trait for any pair of `AsyncRead` and `AsyncWrite`
7227/// streams, handling serialization of JSON-RPC messages to/from newline-delimited JSON.
7228/// This is the standard way to communicate with external processes or network connections.
7229///
7230/// Incoming bytes that are not valid UTF-8 are replaced with U+FFFD, so a line that contains
7231/// them is parsed like any other and does not end the connection.
7232///
7233/// # Use Cases
7234///
7235/// - **Stdio communication**: Connect to agents or proxies via stdin/stdout
7236/// - **Network sockets**: TCP, Unix domain sockets, or other stream-based protocols
7237/// - **Named pipes**: Cross-process communication on the same machine
7238/// - **File I/O**: Reading from and writing to file descriptors
7239///
7240/// # Example
7241///
7242/// Connecting to an agent via stdio:
7243///
7244/// ```no_run
7245/// use agent_client_protocol::UntypedRole;
7246/// # use agent_client_protocol::{ByteStreams};
7247/// use tokio_util::compat::{TokioAsyncReadCompatExt, TokioAsyncWriteCompatExt};
7248///
7249/// # async fn example() -> Result<(), agent_client_protocol::Error> {
7250/// let component = ByteStreams::new(
7251///     tokio::io::stdout().compat_write(),
7252///     tokio::io::stdin().compat(),
7253/// );
7254///
7255/// // Use as a component in a connection
7256/// agent_client_protocol::UntypedRole.builder()
7257///     .name("my-client")
7258///     .connect_to(component)
7259///     .await?;
7260/// # Ok(())
7261/// # }
7262/// ```
7263///
7264/// [`ConnectTo`]: crate::ConnectTo
7265#[derive(Debug)]
7266pub struct ByteStreams<OB, IB> {
7267    outgoing: OB,
7268    incoming: IB,
7269}
7270
7271impl<OB, IB> ByteStreams<OB, IB>
7272where
7273    OB: AsyncWrite + Send + 'static,
7274    IB: AsyncRead + Send + 'static,
7275{
7276    /// Create a new byte stream transport.
7277    pub fn new(outgoing: OB, incoming: IB) -> Self {
7278        Self { outgoing, incoming }
7279    }
7280
7281    fn into_lines(
7282        self,
7283    ) -> Lines<
7284        impl futures::Sink<String, Error = std::io::Error> + Send + 'static,
7285        impl futures::Stream<Item = std::io::Result<String>> + Send + 'static,
7286    > {
7287        let Self { outgoing, incoming } = self;
7288
7289        let incoming_lines = Box::pin(lossy_lines(incoming));
7290        let outgoing_lines = transport_actor::LineWriter::new(outgoing);
7291
7292        Lines::new(outgoing_lines, incoming_lines)
7293    }
7294}
7295
7296/// Splits `reader` into lines, without their `\n` or `\r\n` endings.
7297///
7298/// Bytes that are not valid UTF-8 are replaced with U+FFFD. Reporting them as
7299/// a read error would end the connection over one message. A line that is
7300/// JSON after the replacement is delivered, for example one with such a byte
7301/// inside a string. Any other line is a [`TransportFrame::Malformed`].
7302pub(crate) fn lossy_lines<R>(
7303    reader: R,
7304) -> impl futures::Stream<Item = std::io::Result<String>> + Send + 'static
7305where
7306    R: AsyncRead + Send + 'static,
7307{
7308    use futures::AsyncBufReadExt as _;
7309
7310    let reader = Box::pin(futures::io::BufReader::new(reader));
7311    futures::stream::try_unfold(reader, async |mut reader| {
7312        let mut line = Vec::new();
7313        if reader.read_until(b'\n', &mut line).await? == 0 {
7314            return Ok::<_, std::io::Error>(None);
7315        }
7316        if line.ends_with(b"\n") {
7317            line.pop();
7318            if line.ends_with(b"\r") {
7319                line.pop();
7320            }
7321        }
7322        let line = String::from_utf8(line).unwrap_or_else(|error| {
7323            // The line's content may be private, so it is not logged.
7324            tracing::debug!("Replaced invalid UTF-8 in an incoming line");
7325            String::from_utf8_lossy(error.as_bytes()).into_owned()
7326        });
7327        Ok(Some((line, reader)))
7328    })
7329}
7330
7331#[cfg(any(
7332    all(
7333        any(feature = "process", feature = "stdio"),
7334        not(target_family = "wasm")
7335    ),
7336    test
7337))]
7338pub(crate) async fn write_line<W>(writer: &mut W, line: String) -> std::io::Result<()>
7339where
7340    W: AsyncWrite + Unpin + ?Sized,
7341{
7342    use futures::AsyncWriteExt as _;
7343
7344    let mut bytes = line.into_bytes();
7345    bytes.push(b'\n');
7346    writer.write_all(&bytes).await?;
7347    writer.flush().await
7348}
7349
7350impl<OB, IB, R: Role> ConnectTo<R> for ByteStreams<OB, IB>
7351where
7352    OB: AsyncWrite + Send + 'static,
7353    IB: AsyncRead + Send + 'static,
7354{
7355    async fn connect_to(self, client: impl ConnectTo<R::Counterpart>) -> Result<(), crate::Error> {
7356        ConnectTo::<R>::connect_to(self.into_lines(), client).await
7357    }
7358
7359    fn into_channel_and_future(self) -> (Channel, Option<crate::ConnectionDriver>) {
7360        ConnectTo::<R>::into_channel_and_future(self.into_lines())
7361    }
7362}
7363
7364/// A channel endpoint representing one side of a bidirectional JSON-RPC transport.
7365///
7366/// A channel carries complete TransportFrame values across in-process components and
7367/// transport adapters. Malformed wire input is an
7368/// explicit frame; failures while driving a physical transport are returned by that
7369/// transport's future.
7370///
7371/// The unbounded [`futures::channel::mpsc`] pair is the intended contract:
7372/// frames are never dropped and sends never wait, so the transport or
7373/// component on each side applies its own backpressure. Build a channel from
7374/// an existing pair with [`Channel::new`] and take it apart with
7375/// [`Channel::into_parts`] or by destructuring with `..`.
7376///
7377/// # Example
7378///
7379/// ```no_run
7380/// # use agent_client_protocol::UntypedRole;
7381/// # use agent_client_protocol::Channel;
7382/// # async fn example() -> Result<(), agent_client_protocol::Error> {
7383/// let (channel_a, _channel_b) = Channel::duplex();
7384///
7385/// UntypedRole.builder()
7386///     .name("connection-a")
7387///     .connect_to(channel_a)
7388///     .await?;
7389/// # Ok(())
7390/// # }
7391/// ```
7392#[derive(Debug)]
7393#[non_exhaustive]
7394pub struct Channel {
7395    /// Receives frames from the counterpart.
7396    pub rx: mpsc::UnboundedReceiver<TransportFrame>,
7397    /// Sends frames to the counterpart.
7398    pub tx: mpsc::UnboundedSender<TransportFrame>,
7399}
7400
7401impl Channel {
7402    /// Create a channel endpoint that receives frames on `rx` and sends them
7403    /// on `tx`.
7404    #[must_use]
7405    pub fn new(
7406        rx: mpsc::UnboundedReceiver<TransportFrame>,
7407        tx: mpsc::UnboundedSender<TransportFrame>,
7408    ) -> Self {
7409        Self { rx, tx }
7410    }
7411
7412    /// Split this endpoint into its receiving and sending halves, `(rx, tx)`.
7413    #[must_use]
7414    pub fn into_parts(
7415        self,
7416    ) -> (
7417        mpsc::UnboundedReceiver<TransportFrame>,
7418        mpsc::UnboundedSender<TransportFrame>,
7419    ) {
7420        (self.rx, self.tx)
7421    }
7422
7423    /// Create a pair of connected channel endpoints.
7424    ///
7425    /// Frames sent through either endpoint are received by the other endpoint.
7426    #[must_use]
7427    pub fn duplex() -> (Self, Self) {
7428        let (a_tx, b_rx) = mpsc::unbounded();
7429        let (b_tx, a_rx) = mpsc::unbounded();
7430
7431        (Self { rx: a_rx, tx: a_tx }, Self { rx: b_rx, tx: b_tx })
7432    }
7433
7434    /// Copy frames from `rx` to `tx` until the input closes.
7435    ///
7436    /// # Errors
7437    ///
7438    /// Returns an error if the receiving endpoint closes before the input.
7439    pub(crate) async fn copy(mut self) -> Result<(), crate::Error> {
7440        while let Some(frame) = self.rx.next().await {
7441            self.tx
7442                .unbounded_send(frame)
7443                .map_err(crate::util::internal_error)?;
7444        }
7445        Ok(())
7446    }
7447
7448    /// Copy output concurrently with its owning driver, then drain accepted frames.
7449    /// Passive endpoints instead retain the channel's independent half-close lifetime.
7450    pub(crate) async fn copy_with_driver(
7451        self,
7452        driver: Option<crate::ConnectionDriver>,
7453    ) -> Result<(), crate::Error> {
7454        self.copy_with_driver_until(driver, future::pending()).await
7455    }
7456
7457    /// After the destination's owned foreground finishes, keep driving source
7458    /// errors and sink work, but never deliver queued or new input to it.
7459    pub(crate) async fn copy_with_driver_until(
7460        mut self,
7461        mut driver: Option<crate::ConnectionDriver>,
7462        stop_delivery: impl Future<Output = ()>,
7463    ) -> Result<(), crate::Error> {
7464        let mut stop_delivery = pin!(stop_delivery);
7465        let mut delivering = true;
7466        let mut done = false;
7467        loop {
7468            let event = future::poll_fn(|cx| {
7469                if delivering && stop_delivery.as_mut().poll(cx).is_ready() {
7470                    delivering = false;
7471                }
7472                // Driver errors remain authoritative even when stop or EOF is ready.
7473                if !done
7474                    && let Some(driver) = driver.as_mut()
7475                    && let std::task::Poll::Ready(result) = std::pin::Pin::new(driver).poll(cx)
7476                {
7477                    return std::task::Poll::Ready(Either::Left(result));
7478                }
7479                if !delivering && driver.is_none() {
7480                    return std::task::Poll::Ready(Either::Right(None));
7481                }
7482                self.rx.poll_next_unpin(cx).map(Either::Right)
7483            })
7484            .await;
7485            let frame = match event {
7486                Either::Left(result) => {
7487                    result?;
7488                    done = true;
7489                    self.rx.close();
7490                    continue;
7491                }
7492                Either::Right(frame) => frame,
7493            };
7494            let Some(frame) = frame else {
7495                break;
7496            };
7497            if delivering {
7498                self.tx
7499                    .unbounded_send(frame)
7500                    .map_err(crate::util::internal_error)?;
7501            }
7502        }
7503        // Propagate this half-close before waiting for a still-running driver.
7504        drop(self);
7505        if !done && let Some(driver) = driver {
7506            driver.await?;
7507        }
7508        Ok(())
7509    }
7510
7511    /// Bridge two endpoints while inspecting every valid message.
7512    ///
7513    /// Observers are invoked in source order for each valid message. The
7514    /// original frame is forwarded unchanged after inspection.
7515    ///
7516    /// # Errors
7517    ///
7518    /// Returns an observer error or an error if a destination closes before its
7519    /// source.
7520    pub async fn bridge_with_inspection(
7521        left: Self,
7522        right: Self,
7523        mut left_to_right: impl FnMut(&RawJsonRpcMessage) -> Result<(), crate::Error> + Send,
7524        mut right_to_left: impl FnMut(&RawJsonRpcMessage) -> Result<(), crate::Error> + Send,
7525    ) -> Result<(), crate::Error> {
7526        let Self {
7527            rx: mut left_rx,
7528            tx: left_tx,
7529        } = left;
7530        let Self {
7531            rx: mut right_rx,
7532            tx: right_tx,
7533        } = right;
7534
7535        let left_to_right = async move {
7536            while let Some(frame) = left_rx.next().await {
7537                frame.inspect_messages(&mut left_to_right)?;
7538                right_tx
7539                    .unbounded_send(frame)
7540                    .map_err(crate::util::internal_error)?;
7541            }
7542            Ok::<(), crate::Error>(())
7543        };
7544        let right_to_left = async move {
7545            while let Some(frame) = right_rx.next().await {
7546                frame.inspect_messages(&mut right_to_left)?;
7547                left_tx
7548                    .unbounded_send(frame)
7549                    .map_err(crate::util::internal_error)?;
7550            }
7551            Ok::<(), crate::Error>(())
7552        };
7553
7554        futures::try_join!(left_to_right, right_to_left)?;
7555        Ok(())
7556    }
7557}
7558
7559impl<R: Role> ConnectTo<R> for Channel {
7560    async fn connect_to(self, client: impl ConnectTo<R::Counterpart>) -> Result<(), crate::Error> {
7561        let (client_channel, client_future) = client.into_channel_and_future();
7562
7563        let passive = client_future.is_none();
7564        let outgoing = Box::pin(
7565            Channel {
7566                rx: client_channel.rx,
7567                tx: self.tx,
7568            }
7569            .copy_with_driver(client_future),
7570        );
7571        let incoming = Box::pin(
7572            Channel {
7573                rx: self.rx,
7574                tx: client_channel.tx,
7575            }
7576            .copy(),
7577        );
7578        if passive {
7579            futures::try_join!(outgoing, incoming)?;
7580            return Ok(());
7581        }
7582
7583        match future::select(outgoing, incoming).await {
7584            Either::Left((result, _)) => result,
7585            Either::Right((result, outgoing)) => {
7586                result?;
7587                outgoing.await
7588            }
7589        }
7590    }
7591
7592    fn into_channel_and_future(self) -> (Channel, Option<crate::ConnectionDriver>) {
7593        (self, None)
7594    }
7595}
7596
7597#[cfg(test)]
7598mod tests {
7599    use super::*;
7600    use crate::Client;
7601    #[cfg(feature = "unstable_protocol_v2")]
7602    use crate::Proxy;
7603
7604    #[test]
7605    fn raw_notification_round_trips_and_drops_unknown_envelope_members() {
7606        let message: RawJsonRpcMessage = serde_json::from_value(serde_json::json!({
7607            "jsonrpc": "2.0",
7608            "method": "_vendor/ping",
7609            "params": { "n": 1 },
7610            "extra": true,
7611        }))
7612        .unwrap();
7613        let mut params = serde_json::Map::new();
7614        params.insert("n".into(), 1.into());
7615        assert_eq!(
7616            message,
7617            RawJsonRpcMessage::Notification(RawJsonRpcNotification {
7618                method: "_vendor/ping".into(),
7619                params: Some(RawJsonRpcParams::Object(params)),
7620            })
7621        );
7622        assert_eq!(
7623            serde_json::to_value(&message).unwrap(),
7624            serde_json::json!({
7625                "jsonrpc": "2.0",
7626                "method": "_vendor/ping",
7627                "params": { "n": 1 },
7628            })
7629        );
7630
7631        let without_params =
7632            RawJsonRpcMessage::notification("ping".into(), serde_json::Value::Null).unwrap();
7633        assert_eq!(
7634            serde_json::to_value(&without_params).unwrap(),
7635            serde_json::json!({ "jsonrpc": "2.0", "method": "ping" })
7636        );
7637    }
7638
7639    #[test]
7640    fn protected_cleanup_keeps_scoped_runners_polled_on_every_shutdown_path() {
7641        #[derive(Clone, Copy, Debug)]
7642        enum Stop {
7643            ForegroundSuccess,
7644            ForegroundError,
7645            InputEof,
7646            TransportError,
7647            TaskError,
7648            RunnerError,
7649            SupervisorError,
7650        }
7651
7652        struct Dropped(Arc<AtomicBool>);
7653        impl Drop for Dropped {
7654            fn drop(&mut self) {
7655                self.0.store(true, Ordering::Release);
7656            }
7657        }
7658
7659        for stop in [
7660            Stop::ForegroundSuccess,
7661            Stop::ForegroundError,
7662            Stop::InputEof,
7663            Stop::TransportError,
7664            Stop::TaskError,
7665            Stop::RunnerError,
7666            Stop::SupervisorError,
7667        ] {
7668            let cleaned = Arc::new(AtomicBool::new(false));
7669            let disposable_dropped = Arc::new(AtomicBool::new(false));
7670            let close_finished = Arc::new(AtomicBool::new(false));
7671            let (cleanup_tx, cleanup_rx) = oneshot::channel::<()>();
7672            let (scoped_done_tx, scoped_done_rx) = completion_signal();
7673            let (stop_tx, stop_rx) = oneshot::channel::<()>();
7674            let stop_signal = stop_rx.map(|_| ()).boxed().shared();
7675            let (incoming_tx, incoming_rx) = mpsc::unbounded();
7676            let outgoing = futures::sink::unfold((), |(), _line: String| {
7677                future::ready(Ok::<_, std::io::Error>(()))
7678            });
7679            let builder = Client
7680                .v1()
7681                .with_spawned({
7682                    let cleaned = cleaned.clone();
7683                    async move |cx: crate::v1::ConnectionTo<Agent>| {
7684                        cx.raw_connection().shutdown_requested().await;
7685                        // This stands in for the actual scoped native operation:
7686                        // its async cleanup only advances if this runner is polled.
7687                        cleanup_rx.await.unwrap();
7688                        cleaned.store(true, Ordering::Release);
7689                        let _ = scoped_done_tx.send(());
7690                        Ok(())
7691                    }
7692                })
7693                .with_spawned({
7694                    let stop_signal = stop_signal.clone();
7695                    async move |_cx| {
7696                        stop_signal.await;
7697                        if matches!(stop, Stop::RunnerError) {
7698                            Err(crate::Error::internal_error().data("runner failure"))
7699                        } else {
7700                            future::pending().await
7701                        }
7702                    }
7703                })
7704                .on_close({
7705                    let close_finished = close_finished.clone();
7706                    let scoped_done = scoped_done_rx.clone();
7707                    async move |cx: crate::v1::ConnectionTo<Agent>| {
7708                        // EOF cancellation must precede, not await, close callbacks.
7709                        cx.raw_connection().shutdown_requested().await;
7710                        assert!(!cx.is_incoming_closed());
7711                        scoped_done.await;
7712                        close_finished.store(true, Ordering::Release);
7713                        Ok(())
7714                    }
7715                });
7716            let (connection, driver) =
7717                builder.into_connection_and_future(Lines::new(outgoing, incoming_rx), false, {
7718                    let stop_signal = stop_signal.clone();
7719                    async move |cx| {
7720                        if matches!(stop, Stop::InputEof) {
7721                            cx.incoming_closed().await;
7722                            return Ok(());
7723                        }
7724                        stop_signal.await;
7725                        match stop {
7726                            Stop::ForegroundSuccess | Stop::SupervisorError => Ok(()),
7727                            Stop::ForegroundError => {
7728                                Err(crate::Error::internal_error().data("foreground failure"))
7729                            }
7730                            _ => future::pending().await,
7731                        }
7732                    }
7733                });
7734            let disposable = Dropped(disposable_dropped.clone());
7735            connection
7736                .spawn(async move {
7737                    let _disposable = disposable;
7738                    future::pending().await
7739                })
7740                .unwrap();
7741            connection
7742                .spawn({
7743                    let stop_signal = stop_signal.clone();
7744                    async move {
7745                        stop_signal.await;
7746                        if matches!(stop, Stop::TaskError) {
7747                            Err(crate::Error::internal_error().data("task failure"))
7748                        } else {
7749                            future::pending().await
7750                        }
7751                    }
7752                })
7753                .unwrap();
7754            connection
7755                .spawn_protected({
7756                    let connection = connection.clone();
7757                    async move {
7758                        connection.shutdown_requested().await;
7759                        scoped_done_rx.await;
7760                        if matches!(stop, Stop::SupervisorError) {
7761                            Err(crate::Error::internal_error().data("supervisor failure"))
7762                        } else {
7763                            Ok(())
7764                        }
7765                    }
7766                })
7767                .unwrap();
7768            let mut driver = Box::pin(driver);
7769            assert!(driver.as_mut().now_or_never().is_none(), "{stop:?}");
7770            assert!(connection.shutdown_requested().now_or_never().is_none());
7771            let _ = stop_tx.send(());
7772            let incoming_tx = match stop {
7773                Stop::InputEof => {
7774                    drop(incoming_tx);
7775                    None
7776                }
7777                Stop::TransportError => {
7778                    incoming_tx
7779                        .unbounded_send(Err(std::io::Error::other("transport failure")))
7780                        .unwrap();
7781                    Some(incoming_tx)
7782                }
7783                _ => Some(incoming_tx),
7784            };
7785            for _ in 0..10 {
7786                assert!(driver.as_mut().now_or_never().is_none(), "{stop:?}");
7787                if connection.shutdown_requested().now_or_never().is_some() {
7788                    break;
7789                }
7790            }
7791            assert!(
7792                connection.shutdown_requested().now_or_never().is_some(),
7793                "{stop:?}"
7794            );
7795            assert!(!cleaned.load(Ordering::Acquire), "{stop:?}");
7796            assert!(!disposable_dropped.load(Ordering::Acquire), "{stop:?}");
7797            cleanup_tx.send(()).unwrap();
7798            // Task acknowledgments may wake an actor already polled in this turn.
7799            // Bound the probe so a broken scoped-runner join fails, not hangs.
7800            let mut result = None;
7801            for _ in 0..10 {
7802                result = driver.as_mut().now_or_never();
7803                if result.is_some() {
7804                    break;
7805                }
7806            }
7807            let result =
7808                result.unwrap_or_else(|| panic!("driver did not finish owned cleanup: {stop:?}"));
7809            match stop {
7810                Stop::ForegroundSuccess | Stop::InputEof => result.unwrap(),
7811                _ => {
7812                    let error = result.expect_err("shutdown must preserve the first error");
7813                    let expected = match stop {
7814                        Stop::ForegroundError => "foreground failure",
7815                        Stop::TransportError => "transport failure",
7816                        Stop::TaskError => "task failure",
7817                        Stop::RunnerError => "runner failure",
7818                        Stop::SupervisorError => "supervisor failure",
7819                        _ => unreachable!(),
7820                    };
7821                    assert!(
7822                        error.data.unwrap().to_string().contains(expected),
7823                        "{stop:?}"
7824                    );
7825                }
7826            }
7827            assert!(cleaned.load(Ordering::Acquire), "{stop:?}");
7828            assert!(disposable_dropped.load(Ordering::Acquire), "{stop:?}");
7829            assert_eq!(
7830                close_finished.load(Ordering::Acquire),
7831                matches!(stop, Stop::InputEof),
7832                "{stop:?}",
7833            );
7834            assert!(connection.spawn_protected(async { Ok(()) }).is_err());
7835            drop(incoming_tx);
7836        }
7837    }
7838
7839    #[test]
7840    fn protected_operation_acknowledgments_are_reaped_and_join_seals_registration() {
7841        let (connection, _message_rx, _pending_replies) = connection_for_response_hook_tests();
7842        // The helper drops its task receiver, so use a live receiver for this probe.
7843        let (task_tx, mut task_rx) = mpsc::unbounded();
7844        let connection = ConnectionTo {
7845            task_tx,
7846            ..connection
7847        };
7848        for _ in 0..100 {
7849            connection.spawn_protected(async { Ok(()) }).unwrap();
7850            assert_eq!(
7851                connection
7852                    .protected_operations
7853                    .lock()
7854                    .unwrap()
7855                    .pending
7856                    .len(),
7857                1
7858            );
7859            let task = task_rx.next().now_or_never().unwrap().unwrap();
7860            futures::executor::block_on(task.run_for_test()).unwrap();
7861        }
7862        assert!(
7863            connection
7864                .wait_protected_operations()
7865                .now_or_never()
7866                .is_some()
7867        );
7868        assert!(
7869            connection
7870                .wait_protected_operations()
7871                .now_or_never()
7872                .is_some()
7873        );
7874        assert!(
7875            connection
7876                .protected_operations
7877                .lock()
7878                .unwrap()
7879                .pending
7880                .is_empty()
7881        );
7882        assert!(connection.spawn_protected(async { Ok(()) }).is_err());
7883        assert!(task_rx.next().now_or_never().is_none());
7884    }
7885
7886    #[test]
7887    fn dropping_unused_finish_signal_preserves_physical_half_closes() {
7888        let outgoing = futures::sink::unfold((), |(), _line: String| {
7889            future::ready(Ok::<_, std::io::Error>(()))
7890        });
7891        let (incoming_tx, incoming_rx) = mpsc::unbounded();
7892        let (Channel { mut rx, tx }, mut driver) =
7893            Lines::new(outgoing, incoming_rx).into_channel_transport();
7894
7895        drop(
7896            driver
7897                .take_finish()
7898                .expect("built-in Lines driver is finishable"),
7899        );
7900        drop(tx);
7901        assert!((&mut driver).now_or_never().is_none());
7902        incoming_tx
7903            .unbounded_send(Ok(
7904                r#"{"jsonrpc":"2.0","method":"test/after-output-eof"}"#.into()
7905            ))
7906            .unwrap();
7907        assert!((&mut driver).now_or_never().is_none());
7908        assert!(rx.next().now_or_never().unwrap().is_some());
7909
7910        drop(incoming_tx);
7911        futures::executor::block_on(driver).unwrap();
7912        assert!(rx.next().now_or_never().unwrap().is_none());
7913    }
7914
7915    #[test]
7916    fn explicit_physical_finish_does_not_hide_a_ready_read_error() {
7917        let outgoing = futures::sink::unfold((), |(), _line: String| {
7918            future::ready(Ok::<_, std::io::Error>(()))
7919        });
7920        let incoming = futures::stream::iter([Err(std::io::Error::other("finish read failed"))]);
7921        let (_channel, mut driver) = Lines::new(outgoing, incoming).into_channel_transport();
7922        assert!(driver.request_finish());
7923
7924        let error = futures::executor::block_on(driver).unwrap_err();
7925        assert_eq!(
7926            error
7927                .data
7928                .and_then(|value| value.as_str().map(str::to_owned)),
7929            Some("finish read failed".into())
7930        );
7931    }
7932
7933    #[cfg(feature = "unstable_protocol_v2")]
7934    fn connection_with_task_receiver() -> (
7935        ConnectionTo<crate::role::UntypedRole>,
7936        mpsc::UnboundedReceiver<Task>,
7937    ) {
7938        let (message_tx, _message_rx) = mpsc::unbounded();
7939        let (task_tx, task_rx) = mpsc::unbounded();
7940        let (dynamic_handler_tx, _dynamic_handler_rx) = mpsc::unbounded();
7941        let transport_completion: SharedTransportCompletion =
7942            future::ready(Ok::<(), crate::Error>(())).boxed().shared();
7943        let pending_replies = PendingReplies::default();
7944
7945        (
7946            ConnectionTo::new(
7947                crate::role::UntypedRole,
7948                message_tx,
7949                task_tx,
7950                dynamic_handler_tx,
7951                transport_completion,
7952                pending_replies.registrar(),
7953                ProtocolMode::disabled(),
7954            ),
7955            task_rx,
7956        )
7957    }
7958
7959    #[cfg(feature = "unstable_protocol_v2")]
7960    #[test]
7961    fn v2_builder_exposes_typed_context_to_user_callbacks() {
7962        fn assert_v2_context(_connection: &crate::v2::ConnectionTo<Agent>) {}
7963
7964        let _builder = Client
7965            .v2()
7966            .on_receive_request(
7967                async |_request: UntypedMessage, _responder, connection| {
7968                    assert_v2_context(&connection);
7969                    Ok(())
7970                },
7971                crate::on_receive_request!(),
7972            )
7973            .on_receive_notification(
7974                async |_notification: UntypedMessage, connection| {
7975                    assert_v2_context(&connection);
7976                    Ok(())
7977                },
7978                crate::on_receive_notification!(),
7979            )
7980            .on_receive_dispatch(
7981                async |_dispatch: Dispatch<UntypedMessage, UntypedMessage, V2>, connection| {
7982                    assert_v2_context(&connection);
7983                    Ok(())
7984                },
7985                crate::on_receive_dispatch!(),
7986            )
7987            .on_receive_request_from(
7988                Agent,
7989                async |_request: UntypedMessage, _responder, connection| {
7990                    assert_v2_context(&connection);
7991                    Ok(())
7992                },
7993                crate::on_receive_request!(),
7994            )
7995            .on_receive_notification_from(
7996                Agent,
7997                async |_notification: UntypedMessage, connection| {
7998                    assert_v2_context(&connection);
7999                    Ok(())
8000                },
8001                crate::on_receive_notification!(),
8002            )
8003            .on_receive_dispatch_from(
8004                Agent,
8005                async |_dispatch: Dispatch<UntypedMessage, UntypedMessage, V2>, connection| {
8006                    assert_v2_context(&connection);
8007                    Ok(())
8008                },
8009                crate::on_receive_dispatch!(),
8010            )
8011            .with_spawned(async |connection| {
8012                assert_v2_context(&connection);
8013                Ok(())
8014            })
8015            .on_close(async |connection| {
8016                assert_v2_context(&connection);
8017                Ok(())
8018            });
8019    }
8020
8021    #[cfg(feature = "unstable_protocol_v2")]
8022    #[test]
8023    fn proxy_builders_negotiate_proxy_initialize_like_agents() -> Result<(), crate::Error> {
8024        use crate::schema::ProtocolVersion;
8025
8026        // A v1 proxy selects v1 for a newer request.
8027        let mode = Proxy.v1().protocol_mode;
8028        assert_eq!(mode.api_protocol_version(), Some(ProtocolVersion::V1));
8029        let request = ProtocolCompat::new(mode).incoming_message(UntypedMessage::new(
8030            "proxy/initialize",
8031            serde_json::json!({ "protocolVersion": ProtocolVersion::V2 }),
8032        )?)?;
8033        assert_eq!(request.params()["protocolVersion"], serde_json::json!(1));
8034
8035        // A v2 proxy supports no version at or below v1.
8036        let mode = Proxy.v2().protocol_mode;
8037        assert_eq!(mode.api_protocol_version(), Some(ProtocolVersion::V2));
8038        let error = ProtocolCompat::new(mode)
8039            .incoming_message(UntypedMessage::new(
8040                "proxy/initialize",
8041                serde_json::json!({ "protocolVersion": ProtocolVersion::V1 }),
8042            )?)
8043            .expect_err("a v2 proxy builder must reject v1");
8044        assert_eq!(i32::from(error.code), -32022);
8045
8046        Ok(())
8047    }
8048
8049    #[cfg(feature = "unstable_protocol_v2")]
8050    #[test]
8051    fn v2_proxy_rejects_explicitly_prewrapped_initialize_request() {
8052        let (message_tx, message_rx) = mpsc::unbounded();
8053        let (task_tx, _task_rx) = mpsc::unbounded();
8054        let (dynamic_handler_tx, _dynamic_handler_rx) = mpsc::unbounded();
8055        let transport_completion: SharedTransportCompletion =
8056            future::ready(Ok::<(), crate::Error>(())).boxed().shared();
8057        let pending_replies = PendingReplies::default();
8058        let connection = ConnectionTo::new(
8059            crate::Conductor,
8060            message_tx,
8061            task_tx,
8062            dynamic_handler_tx,
8063            transport_completion,
8064            pending_replies.registrar(),
8065            ProtocolMode::v2_proxy(),
8066        );
8067
8068        let request = crate::schema::SuccessorMessage::new(
8069            UntypedMessage::new(
8070                "initialize",
8071                serde_json::json!({ "protocolVersion": crate::schema::ProtocolVersion::V1 }),
8072            )
8073            .expect("test initialize request should serialize"),
8074        );
8075        let sent = connection.send_request_to(Agent, request);
8076
8077        let (transport_tx, mut transport_rx) = mpsc::unbounded();
8078        let mut actor = Box::pin(outgoing_actor::outgoing_protocol_actor(
8079            message_rx,
8080            pending_replies,
8081            transport_tx,
8082            ProtocolCompat::new(ProtocolMode::v2_proxy()),
8083            future::pending::<()>().boxed().shared(),
8084        ));
8085        assert!(
8086            actor.as_mut().now_or_never().is_none(),
8087            "the outgoing actor should continue after rejecting the request"
8088        );
8089        assert!(
8090            transport_rx.next().now_or_never().is_none(),
8091            "an explicitly prewrapped initialize must not reach the transport"
8092        );
8093
8094        let error = futures::executor::block_on(sent.block_task())
8095            .expect_err("connection routing must own successor wrapping");
8096        let data = error
8097            .data
8098            .as_ref()
8099            .and_then(|data| data.as_str())
8100            .unwrap_or_default();
8101        assert!(data.contains("logical `initialize`"), "{error:?}");
8102        assert!(data.contains("proxy/successor"), "{error:?}");
8103    }
8104
8105    #[cfg(feature = "unstable_protocol_v2")]
8106    #[test]
8107    fn v2_proxy_builder_exposes_typed_context_to_user_callbacks() {
8108        fn assert_v2_context(_connection: &crate::v2::ConnectionTo<crate::Conductor>) {}
8109
8110        let _builder = Proxy
8111            .v2()
8112            .on_receive_request_from(
8113                Client,
8114                async |_request: UntypedMessage, _responder, connection| {
8115                    assert_v2_context(&connection);
8116                    Ok(())
8117                },
8118                crate::on_receive_request!(),
8119            )
8120            .on_receive_notification_from(
8121                Agent,
8122                async |_notification: UntypedMessage, connection| {
8123                    assert_v2_context(&connection);
8124                    Ok(())
8125                },
8126                crate::on_receive_notification!(),
8127            )
8128            .on_receive_dispatch_from(
8129                Client,
8130                async |_dispatch: Dispatch<UntypedMessage, UntypedMessage, V2>, connection| {
8131                    assert_v2_context(&connection);
8132                    Ok(())
8133                },
8134                crate::on_receive_dispatch!(),
8135            )
8136            .with_spawned(async |connection| {
8137                assert_v2_context(&connection);
8138                Ok(())
8139            })
8140            .on_close(async |connection| {
8141                assert_v2_context(&connection);
8142                Ok(())
8143            });
8144    }
8145
8146    #[cfg(feature = "unstable_protocol_v2")]
8147    #[test]
8148    fn raw_connection_spawns_v2_builder_with_typed_child_callback() {
8149        let (parent, mut task_rx) = connection_with_task_receiver();
8150        let (transport, _peer) = Channel::duplex();
8151        let (callback_tx, callback_rx) = oneshot::channel();
8152
8153        let child: crate::v2::ConnectionTo<Agent> = parent
8154            .spawn_connection(
8155                Client.v2().with_spawned(
8156                    async move |_connection: crate::v2::ConnectionTo<Agent>| {
8157                        callback_tx.send(()).map_err(|()| {
8158                            crate::util::internal_error("typed child callback receiver was dropped")
8159                        })
8160                    },
8161                ),
8162                transport,
8163            )
8164            .expect("v2 child connection should be spawned");
8165
8166        let task = futures::FutureExt::now_or_never(futures::StreamExt::next(&mut task_rx))
8167            .expect("child connection task should already be queued")
8168            .expect("parent task queue should remain open");
8169        futures::executor::block_on(async {
8170            match future::select(Box::pin(task.run_for_test()), Box::pin(callback_rx)).await {
8171                Either::Right((Ok(()), child_task)) => drop(child_task),
8172                Either::Right((Err(error), _)) => {
8173                    panic!("typed child callback sender was dropped: {error}")
8174                }
8175                Either::Left((result, _)) => {
8176                    panic!("child connection stopped before its typed callback ran: {result:?}")
8177                }
8178            }
8179        });
8180
8181        drop(child);
8182    }
8183
8184    #[cfg(feature = "unstable_protocol_v2")]
8185    #[test]
8186    fn raw_connection_returns_raw_context_for_raw_builder() {
8187        let (parent, mut task_rx) = connection_with_task_receiver();
8188        let (transport, _peer) = Channel::duplex();
8189
8190        let child: ConnectionTo<Agent> = parent
8191            .spawn_connection(Builder::new(Client), transport)
8192            .expect("raw child connection should be spawned");
8193        assert_eq!(child.protocol_version(), None);
8194
8195        let child_task = futures::FutureExt::now_or_never(futures::StreamExt::next(&mut task_rx))
8196            .expect("child connection task should already be queued")
8197            .expect("parent task queue should remain open");
8198
8199        drop((child, child_task));
8200    }
8201
8202    fn connection_with_dynamic_handler_receiver() -> (
8203        ConnectionTo<crate::role::UntypedRole>,
8204        mpsc::UnboundedReceiver<DynamicHandlerMessage<crate::role::UntypedRole>>,
8205    ) {
8206        let (message_tx, _message_rx) = mpsc::unbounded();
8207        let (task_tx, _task_rx) = mpsc::unbounded();
8208        let (dynamic_handler_tx, dynamic_handler_rx) = mpsc::unbounded();
8209        let transport_completion: SharedTransportCompletion =
8210            future::ready(Ok::<(), crate::Error>(())).boxed().shared();
8211        let pending_replies = PendingReplies::default();
8212
8213        (
8214            ConnectionTo::new(
8215                crate::role::UntypedRole,
8216                message_tx,
8217                task_tx,
8218                dynamic_handler_tx,
8219                transport_completion,
8220                pending_replies.registrar(),
8221                ProtocolMode::disabled(),
8222            ),
8223            dynamic_handler_rx,
8224        )
8225    }
8226
8227    struct ClaimingDynamicHandler;
8228
8229    impl HandleDispatchFrom<crate::role::UntypedRole> for ClaimingDynamicHandler {
8230        fn handle_dispatch_from(
8231            &mut self,
8232            _message: Dispatch,
8233            _connection: ConnectionTo<crate::role::UntypedRole>,
8234        ) -> impl Future<Output = Result<Handled<Dispatch>, crate::Error>> + Send {
8235            future::ready(Ok(Handled::Yes))
8236        }
8237
8238        fn describe_chain(&self) -> impl Debug {
8239            "ClaimingDynamicHandler"
8240        }
8241    }
8242
8243    fn connection_for_response_hook_tests() -> (
8244        ConnectionTo<crate::role::UntypedRole>,
8245        mpsc::UnboundedReceiver<OutgoingMessage>,
8246        PendingReplies,
8247    ) {
8248        let (message_tx, message_rx) = mpsc::unbounded();
8249        let (task_tx, _task_rx) = mpsc::unbounded();
8250        let (dynamic_handler_tx, _dynamic_handler_rx) = mpsc::unbounded();
8251        let transport_completion: SharedTransportCompletion =
8252            future::ready(Ok::<(), crate::Error>(())).boxed().shared();
8253        let pending_replies = PendingReplies::default();
8254
8255        (
8256            ConnectionTo::new(
8257                crate::role::UntypedRole,
8258                message_tx,
8259                task_tx,
8260                dynamic_handler_tx,
8261                transport_completion,
8262                pending_replies.registrar(),
8263                ProtocolMode::disabled(),
8264            ),
8265            message_rx,
8266            pending_replies,
8267        )
8268    }
8269
8270    #[cfg(feature = "unstable_protocol_v2")]
8271    fn route_test_response(
8272        request_id: RawJsonRpcId,
8273        pending_replies: &PendingReplies,
8274        result: Result<serde_json::Value, crate::Error>,
8275    ) {
8276        let pending_reply = pending_replies
8277            .remove(&request_id)
8278            .expect("the request should have a pending reply");
8279        let (dispatch, _) = incoming_actor::dispatch_from_response(pending_reply, result);
8280        let Dispatch::Response(result, router) = dispatch else {
8281            panic!("expected a response dispatch");
8282        };
8283        router
8284            .route_with_result(result)
8285            .expect("response should route to the pending request");
8286    }
8287
8288    #[cfg(feature = "unstable_protocol_v2")]
8289    #[test]
8290    fn handle_ids_are_typed_by_protocol_and_match_the_wire_id() {
8291        let (connection, _message_rx, pending_replies) = connection_for_response_hook_tests();
8292        let raw_sent = connection.send_request_to(
8293            crate::role::UntypedRole,
8294            UntypedMessage::new("probe", serde_json::json!({}))
8295                .expect("test request should serialize"),
8296        );
8297        let raw_sent_id: &RawJsonRpcId = raw_sent.id();
8298        assert_eq!(raw_sent_id, raw_sent.raw_id());
8299        raw_sent.detach();
8300
8301        let v2_connection = crate::v2::ConnectionTo { inner: connection };
8302        let sent = v2_connection.send_request_to(
8303            crate::role::UntypedRole,
8304            UntypedMessage::new("probe", serde_json::json!({}))
8305                .expect("test request should serialize"),
8306        );
8307        let v2_id: crate::v2::schema::RequestId = sent.id().clone();
8308        let raw_id = sent.raw_id().clone();
8309        assert_eq!(
8310            serde_json::to_value(&v2_id).expect("v2 id should serialize"),
8311            serde_json::to_value(&raw_id).expect("raw id should serialize"),
8312        );
8313
8314        let pending_reply = pending_replies
8315            .remove(&raw_id)
8316            .expect("the request should have a pending reply");
8317        let (dispatch, _) =
8318            incoming_actor::dispatch_from_response(pending_reply, Ok(serde_json::json!({})));
8319        assert_eq!(dispatch.raw_id(), Some(&raw_id));
8320        let dispatch = dispatch
8321            .into_protocol::<V2>()
8322            .expect("SDK-assigned ids are valid v2 ids");
8323        assert_eq!(dispatch.id(), Some(&v2_id));
8324        let Dispatch::Response(_, router) = dispatch else {
8325            panic!("expected a response dispatch");
8326        };
8327        assert_eq!(router.id(), &v2_id);
8328        assert_eq!(router.raw_id(), &raw_id);
8329        sent.detach();
8330    }
8331
8332    #[cfg(feature = "unstable_protocol_v2")]
8333    #[test]
8334    fn response_hook_runs_when_success_is_routed_before_consumption() {
8335        let (connection, _message_rx, pending_replies) = connection_for_response_hook_tests();
8336        let hook_ran = Arc::new(AtomicBool::new(false));
8337        let sent = connection.send_request_to_with_response_hook_after::<Raw, _, _, _>(
8338            crate::role::UntypedRole,
8339            UntypedMessage::new("hooked", serde_json::json!({}))
8340                .expect("test request should serialize"),
8341            future::ready(Ok(())),
8342            {
8343                let hook_ran = hook_ran.clone();
8344                move |response| {
8345                    assert_eq!(response, &serde_json::json!({"ok": true}));
8346                    hook_ran.store(true, Ordering::Release);
8347                    Ok(())
8348                }
8349            },
8350        );
8351        let request_id = sent.raw_id().clone();
8352
8353        route_test_response(
8354            request_id,
8355            &pending_replies,
8356            Ok(serde_json::json!({"ok": true})),
8357        );
8358
8359        assert!(hook_ran.load(Ordering::Acquire));
8360        assert_eq!(
8361            futures::executor::block_on(sent.block_task())
8362                .expect("routed response should remain consumable"),
8363            serde_json::json!({"ok": true})
8364        );
8365    }
8366
8367    #[cfg(feature = "unstable_protocol_v2")]
8368    #[test]
8369    fn response_hook_skips_errors_but_outlives_a_dropped_consumer() {
8370        let (connection, _message_rx, pending_replies) = connection_for_response_hook_tests();
8371        let peer_error_hook_ran = Arc::new(AtomicBool::new(false));
8372        let peer_error = connection.send_request_to_with_response_hook_after::<Raw, _, _, _>(
8373            crate::role::UntypedRole,
8374            UntypedMessage::new("peer-error", serde_json::json!({}))
8375                .expect("test request should serialize"),
8376            future::ready(Ok(())),
8377            {
8378                let hook_ran = peer_error_hook_ran.clone();
8379                move |_| {
8380                    hook_ran.store(true, Ordering::Release);
8381                    Ok(())
8382                }
8383            },
8384        );
8385        let peer_error_id = peer_error.raw_id().clone();
8386        route_test_response(
8387            peer_error_id,
8388            &pending_replies,
8389            Err(crate::Error::invalid_request()),
8390        );
8391        assert!(
8392            futures::executor::block_on(peer_error.block_task()).is_err(),
8393            "the peer error should reach the consumer"
8394        );
8395        assert!(!peer_error_hook_ran.load(Ordering::Acquire));
8396
8397        let dropped_hook_ran = Arc::new(AtomicBool::new(false));
8398        let dropped = connection.send_request_to_with_response_hook_after::<Raw, _, _, _>(
8399            crate::role::UntypedRole,
8400            UntypedMessage::new("dropped", serde_json::json!({}))
8401                .expect("test request should serialize"),
8402            future::ready(Ok(())),
8403            {
8404                let hook_ran = dropped_hook_ran.clone();
8405                move |_| {
8406                    hook_ran.store(true, Ordering::Release);
8407                    Ok(())
8408                }
8409            },
8410        );
8411        let dropped_id = dropped.raw_id().clone();
8412        drop(dropped);
8413        route_test_response(
8414            dropped_id,
8415            &pending_replies,
8416            Ok(serde_json::json!({"ok": true})),
8417        );
8418        assert!(dropped_hook_ran.load(Ordering::Acquire));
8419    }
8420
8421    #[cfg(feature = "unstable_protocol_v2")]
8422    #[test]
8423    fn response_hook_failure_replaces_the_success_result() {
8424        let (connection, _message_rx, pending_replies) = connection_for_response_hook_tests();
8425        let sent = connection.send_request_to_with_response_hook_after::<Raw, _, _, _>(
8426            crate::role::UntypedRole,
8427            UntypedMessage::new("hook-failure", serde_json::json!({}))
8428                .expect("test request should serialize"),
8429            future::ready(Ok(())),
8430            |_| Err(crate::Error::internal_error().data("response hook failed")),
8431        );
8432        let request_id = sent.raw_id().clone();
8433        route_test_response(
8434            request_id,
8435            &pending_replies,
8436            Ok(serde_json::json!({"ok": true})),
8437        );
8438
8439        let error = futures::executor::block_on(sent.block_task())
8440            .expect_err("the hook failure should replace the successful response");
8441        assert_eq!(error.code, crate::ErrorCode::INTERNAL_ERROR);
8442        assert_eq!(error.data, Some(serde_json::json!("response hook failed")));
8443    }
8444
8445    #[test]
8446    fn ordered_request_waits_for_readiness_before_publication() {
8447        let (connection, message_rx, pending_replies) = connection_for_response_hook_tests();
8448        let (ready_tx, ready_rx) = oneshot::channel();
8449        let sent = connection.send_ordered_request_to_after::<Raw, _, _, _>(
8450            crate::role::UntypedRole,
8451            UntypedMessage::new("after-ready", serde_json::json!({}))
8452                .expect("test request should serialize"),
8453            async move { ready_rx.await.map_err(crate::Error::into_internal_error) },
8454        );
8455
8456        let (transport_tx, mut transport_rx) = mpsc::unbounded();
8457        let mut actor = Box::pin(outgoing_actor::outgoing_protocol_actor(
8458            message_rx,
8459            pending_replies,
8460            transport_tx,
8461            ProtocolCompat::new(ProtocolMode::disabled()),
8462            future::pending::<()>().boxed().shared(),
8463        ));
8464
8465        assert!(
8466            actor.as_mut().now_or_never().is_none(),
8467            "the outgoing actor should wait for readiness"
8468        );
8469        assert!(
8470            transport_rx.next().now_or_never().is_none(),
8471            "the request must not be published before readiness"
8472        );
8473
8474        ready_tx
8475            .send(())
8476            .expect("the readiness receiver should remain active");
8477        assert!(
8478            actor.as_mut().now_or_never().is_none(),
8479            "the outgoing actor should continue serving after publication"
8480        );
8481        let frame = transport_rx
8482            .next()
8483            .now_or_never()
8484            .expect("the ready request should be published")
8485            .expect("the transport queue should remain open");
8486        assert!(matches!(
8487            frame,
8488            TransportFrame::Single(RawJsonRpcMessage::Request(_))
8489        ));
8490
8491        drop(sent);
8492    }
8493
8494    #[test]
8495    fn foreground_finish_settles_unready_requests_and_preserves_ready_output_fifo() {
8496        let (connection, message_rx, pending_replies) = connection_for_response_hook_tests();
8497        let unready = connection.send_ordered_request_to_after::<Raw, _, _, _>(
8498            crate::role::UntypedRole,
8499            UntypedMessage::new("unready", serde_json::json!({})).unwrap(),
8500            future::pending(),
8501        );
8502        let unready_id = unready.raw_id().clone();
8503        send_raw_message(
8504            &connection.message_tx,
8505            OutgoingMessage::Notification {
8506                untyped: UntypedMessage::new("first", serde_json::json!({})).unwrap(),
8507            },
8508        )
8509        .unwrap();
8510        let ready = connection.send_ordered_request_to_after::<Raw, _, _, _>(
8511            crate::role::UntypedRole,
8512            UntypedMessage::new("ready", serde_json::json!({})).unwrap(),
8513            future::ready(Ok(())),
8514        );
8515        let unready_after = connection.send_ordered_request_to_after::<Raw, _, _, _>(
8516            crate::role::UntypedRole,
8517            UntypedMessage::new("unready-after", serde_json::json!({})).unwrap(),
8518            future::pending(),
8519        );
8520        let unready_after_id = unready_after.raw_id().clone();
8521        send_raw_message(
8522            &connection.message_tx,
8523            OutgoingMessage::Notification {
8524                untyped: UntypedMessage::new("last", serde_json::json!({})).unwrap(),
8525            },
8526        )
8527        .unwrap();
8528        let (done_tx, done_rx) = oneshot::channel();
8529        send_raw_message(
8530            &connection.message_tx,
8531            OutgoingMessage::CloseAfterDraining { done: done_tx },
8532        )
8533        .unwrap();
8534        let (transport_tx, transport_rx) = mpsc::unbounded();
8535        futures::executor::block_on(outgoing_actor::outgoing_protocol_actor(
8536            message_rx,
8537            pending_replies.clone(),
8538            transport_tx,
8539            ProtocolCompat::new(ProtocolMode::disabled()),
8540            future::ready(()).boxed().shared(),
8541        ))
8542        .unwrap();
8543        futures::executor::block_on(done_rx).unwrap();
8544        let error = futures::executor::block_on(unready.block_task())
8545            .expect_err("an unresolved gate must explicitly fail its consumer");
8546        assert!(
8547            error
8548                .data
8549                .unwrap()
8550                .to_string()
8551                .contains("foreground completed before outgoing request readiness")
8552        );
8553        assert!(!pending_replies.contains(&unready_id));
8554        let error = futures::executor::block_on(unready_after.block_task())
8555            .expect_err("each unresolved gate must fail without repolling a consumed signal");
8556        assert!(
8557            error
8558                .data
8559                .unwrap()
8560                .to_string()
8561                .contains("foreground completed before outgoing request readiness")
8562        );
8563        assert!(!pending_replies.contains(&unready_after_id));
8564        assert!(pending_replies.contains(ready.raw_id()));
8565        let frames = futures::executor::block_on(transport_rx.collect::<Vec<_>>());
8566        let methods = frames
8567            .into_iter()
8568            .map(|frame| match frame {
8569                TransportFrame::Single(RawJsonRpcMessage::Notification(message)) => {
8570                    message.method.to_string()
8571                }
8572                TransportFrame::Single(RawJsonRpcMessage::Request(message)) => {
8573                    message.method.to_string()
8574                }
8575                _ => panic!("expected ready request/notification output"),
8576            })
8577            .collect::<Vec<_>>();
8578        assert_eq!(methods, ["first", "ready", "last"]);
8579    }
8580
8581    #[test]
8582    fn ordered_blocking_transform_precedes_response_acknowledgment() {
8583        let (connection, _message_rx, pending_replies) = connection_for_response_hook_tests();
8584        let sent = connection.send_ordered_request_to::<Raw, _, _>(
8585            crate::role::UntypedRole,
8586            UntypedMessage::new("ordered-transform", serde_json::json!({}))
8587                .expect("test request should serialize"),
8588        );
8589        let request_id = sent.raw_id().clone();
8590        let pending_reply = pending_replies
8591            .remove(&request_id)
8592            .expect("the request should have a pending reply");
8593        let (dispatch, response_dispatch) = incoming_actor::dispatch_from_response(
8594            pending_reply,
8595            Err(crate::Error::invalid_params()),
8596        );
8597        let Dispatch::Response(result, router) = dispatch else {
8598            panic!("expected a response dispatch");
8599        };
8600        router
8601            .route_with_result(result)
8602            .expect("response should route to the pending request");
8603        let acknowledgment = response_dispatch
8604            .complete()
8605            .expect("an ordered response should wait for acknowledgment");
8606        let acknowledgment = Arc::new(Mutex::new(Some(acknowledgment)));
8607        let acknowledgment_probe = acknowledgment.clone();
8608
8609        let error =
8610            futures::executor::block_on(sent.block_task_with_ordered_result(move |result| {
8611                assert_eq!(
8612                    acknowledgment_probe
8613                        .lock()
8614                        .expect("acknowledgment mutex poisoned")
8615                        .as_mut()
8616                        .expect("acknowledgment receiver should remain available")
8617                        .try_recv()
8618                        .expect("acknowledgment sender should remain open"),
8619                    None,
8620                    "the ordered response was acknowledged before its transform"
8621                );
8622                result
8623            }))
8624            .expect_err("the peer error should survive the ordered transform");
8625        assert_eq!(error.code, crate::ErrorCode::INVALID_PARAMS);
8626
8627        let acknowledgment = acknowledgment
8628            .lock()
8629            .expect("acknowledgment mutex poisoned")
8630            .take()
8631            .expect("acknowledgment receiver should remain available");
8632        futures::executor::block_on(acknowledgment)
8633            .expect("the transform should release the ordered response");
8634    }
8635
8636    #[cfg(feature = "unstable_protocol_v2")]
8637    #[test]
8638    fn outgoing_request_readiness_failure_rejects_without_publication() {
8639        let (connection, message_rx, pending_replies) = connection_for_response_hook_tests();
8640        let hook_ran = Arc::new(AtomicBool::new(false));
8641        let sent = connection.send_request_to_with_response_hook_after::<Raw, _, _, _>(
8642            crate::role::UntypedRole,
8643            UntypedMessage::new("never-published", serde_json::json!({}))
8644                .expect("test request should serialize"),
8645            future::ready(Err(crate::Error::internal_error().data("readiness failed"))),
8646            {
8647                let hook_ran = hook_ran.clone();
8648                move |_| {
8649                    hook_ran.store(true, Ordering::Release);
8650                    Ok(())
8651                }
8652            },
8653        );
8654
8655        let (transport_tx, mut transport_rx) = mpsc::unbounded();
8656        let mut actor = Box::pin(outgoing_actor::outgoing_protocol_actor(
8657            message_rx,
8658            pending_replies,
8659            transport_tx,
8660            ProtocolCompat::new(ProtocolMode::disabled()),
8661            future::pending::<()>().boxed().shared(),
8662        ));
8663
8664        assert!(
8665            actor.as_mut().now_or_never().is_none(),
8666            "the outgoing actor should continue serving after rejecting the request"
8667        );
8668        assert!(
8669            transport_rx.next().now_or_never().is_none(),
8670            "a request whose readiness failed must not be published"
8671        );
8672        let error = futures::executor::block_on(sent.block_task())
8673            .expect_err("the readiness error should reach the request consumer");
8674        assert_eq!(error.code, crate::ErrorCode::INTERNAL_ERROR);
8675        assert_eq!(error.data, Some(serde_json::json!("readiness failed")));
8676        assert!(!hook_ran.load(Ordering::Acquire));
8677    }
8678
8679    #[test]
8680    fn ordered_request_is_marked_before_entering_outgoing_queue() {
8681        let (message_tx, mut message_rx) = mpsc::unbounded();
8682        let (task_tx, mut task_rx) = mpsc::unbounded();
8683        let (dynamic_handler_tx, _dynamic_handler_rx) = mpsc::unbounded();
8684        let transport_completion: SharedTransportCompletion =
8685            future::ready(Ok::<(), crate::Error>(())).boxed().shared();
8686        let pending_replies = PendingReplies::default();
8687        let connection = ConnectionTo::new(
8688            crate::role::UntypedRole,
8689            message_tx,
8690            task_tx,
8691            dynamic_handler_tx,
8692            transport_completion,
8693            pending_replies.registrar(),
8694            ProtocolMode::disabled(),
8695        );
8696
8697        let sent = connection.send_ordered_request_to::<Raw, _, _>(
8698            crate::role::UntypedRole,
8699            UntypedMessage::new("ordered", serde_json::json!({}))
8700                .expect("test request should serialize"),
8701        );
8702        let request_id = sent.raw_id().clone();
8703        let message = futures::FutureExt::now_or_never(futures::StreamExt::next(&mut message_rx))
8704            .expect("outgoing request should already be queued")
8705            .expect("outgoing request queue should remain open");
8706        let OutgoingMessage::Request { id, .. } = message else {
8707            panic!("expected an outgoing request");
8708        };
8709        assert_eq!(id, request_id);
8710
8711        let pending_reply = pending_replies
8712            .remove(&request_id)
8713            .expect("the request should have a pending reply");
8714        assert!(
8715            pending_reply.ordering.is_ordered(),
8716            "the response ordering barrier must be installed before publication"
8717        );
8718
8719        // Route the response before the callback is registered. The pre-set
8720        // ordering marker must hold dispatch until the callback task is
8721        // subsequently installed and completes.
8722        let (dispatch, response_dispatch) = incoming_actor::dispatch_from_response(
8723            pending_reply,
8724            Ok(serde_json::json!({"ok": true})),
8725        );
8726        let Dispatch::Response(result, router) = dispatch else {
8727            panic!("expected a response dispatch");
8728        };
8729        router
8730            .route_with_result(result)
8731            .expect("response should route to the pending request");
8732        let acknowledgment = response_dispatch
8733            .complete()
8734            .expect("an ordered response should require acknowledgment");
8735
8736        let callback_ran = Arc::new(AtomicBool::new(false));
8737        sent.on_receiving_result({
8738            let callback_ran = callback_ran.clone();
8739            async move |result| {
8740                assert_eq!(result?, serde_json::json!({"ok": true}));
8741                callback_ran.store(true, Ordering::Release);
8742                Ok(())
8743            }
8744        })
8745        .expect("ordered callback should be scheduled");
8746
8747        let task = futures::FutureExt::now_or_never(futures::StreamExt::next(&mut task_rx))
8748            .expect("callback task should already be queued")
8749            .expect("callback task queue should remain open");
8750        futures::executor::block_on(task.run_for_test()).expect("callback task should succeed");
8751        futures::executor::block_on(acknowledgment)
8752            .expect("callback completion should acknowledge dispatch");
8753        assert!(callback_ran.load(Ordering::Acquire));
8754    }
8755
8756    fn next_dynamic_handler_message<Counterpart: Role>(
8757        receiver: &mut mpsc::UnboundedReceiver<DynamicHandlerMessage<Counterpart>>,
8758    ) -> Option<DynamicHandlerMessage<Counterpart>> {
8759        futures::FutureExt::now_or_never(futures::StreamExt::next(receiver))
8760            .expect("dynamic-handler receiver should be ready")
8761    }
8762
8763    #[cfg(feature = "unstable_protocol_v2")]
8764    #[test]
8765    fn v2_dynamic_handler_guard_registers_and_removes_handler() {
8766        let (message_tx, _message_rx) = mpsc::unbounded();
8767        let (task_tx, _task_rx) = mpsc::unbounded();
8768        let (dynamic_handler_tx, mut dynamic_handler_rx) = mpsc::unbounded();
8769        let transport_completion: SharedTransportCompletion =
8770            future::ready(Ok::<(), crate::Error>(())).boxed().shared();
8771        let pending_replies = PendingReplies::default();
8772        let connection = crate::v2::ConnectionTo {
8773            inner: ConnectionTo::new(
8774                Agent,
8775                message_tx,
8776                task_tx,
8777                dynamic_handler_tx,
8778                transport_completion,
8779                pending_replies.registrar(),
8780                ProtocolMode::v2_client(),
8781            ),
8782        };
8783
8784        let guard = connection
8785            .add_dynamic_handler(NullHandler)
8786            .expect("v2 dynamic handler should register");
8787        let added_uuid = match next_dynamic_handler_message(&mut dynamic_handler_rx) {
8788            Some(DynamicHandlerMessage::AddDynamicHandler(uuid, _, _)) => uuid,
8789            other => panic!("expected v2 handler registration, got {other:?}"),
8790        };
8791
8792        drop(guard);
8793
8794        match next_dynamic_handler_message(&mut dynamic_handler_rx) {
8795            Some(DynamicHandlerMessage::RemoveDynamicHandler(uuid)) => {
8796                assert_eq!(uuid, added_uuid);
8797            }
8798            other => panic!("expected v2 handler removal, got {other:?}"),
8799        }
8800    }
8801
8802    #[test]
8803    fn dropping_dynamic_handler_guard_unregisters_handler() {
8804        let (connection, mut receiver) = connection_with_dynamic_handler_receiver();
8805        let guard = connection.add_dynamic_handler(NullHandler).unwrap();
8806
8807        let added_uuid = match next_dynamic_handler_message(&mut receiver) {
8808            Some(DynamicHandlerMessage::AddDynamicHandler(uuid, _, _)) => uuid,
8809            other => panic!("expected handler registration, got {other:?}"),
8810        };
8811
8812        drop(guard);
8813
8814        match next_dynamic_handler_message(&mut receiver) {
8815            Some(DynamicHandlerMessage::RemoveDynamicHandler(uuid)) => {
8816                assert_eq!(uuid, added_uuid);
8817            }
8818            other => panic!("expected handler removal, got {other:?}"),
8819        }
8820    }
8821
8822    #[test]
8823    fn dropping_dynamic_handler_guard_deactivates_queued_handler_immediately() {
8824        let (connection, mut receiver) = connection_with_dynamic_handler_receiver();
8825        let guard = connection
8826            .add_dynamic_handler(ClaimingDynamicHandler)
8827            .expect("dynamic handler should register");
8828        let mut handler = match next_dynamic_handler_message(&mut receiver) {
8829            Some(DynamicHandlerMessage::AddDynamicHandler(_, handler, _)) => handler,
8830            other => panic!("expected handler registration, got {other:?}"),
8831        };
8832
8833        drop(guard);
8834
8835        let message = Dispatch::Notification(
8836            UntypedMessage::new("stale", serde_json::json!({}))
8837                .expect("test notification should serialize"),
8838        );
8839        let handled =
8840            futures::executor::block_on(handler.dyn_handle_dispatch_from(message, connection))
8841                .expect("inactive handler should decline cleanly");
8842        assert!(matches!(handled, Handled::No { retry: false, .. }));
8843    }
8844
8845    #[test]
8846    fn dynamic_handler_barrier_acknowledges_prior_messages() {
8847        let (connection, mut receiver) = connection_with_dynamic_handler_receiver();
8848        let _guard = connection.add_dynamic_handler(NullHandler).unwrap();
8849        let mut barrier = Box::pin(connection.dynamic_handler_barrier());
8850
8851        assert!(matches!(
8852            next_dynamic_handler_message(&mut receiver),
8853            Some(DynamicHandlerMessage::AddDynamicHandler(_, _, _))
8854        ));
8855        assert!(
8856            barrier.as_mut().now_or_never().is_none(),
8857            "the barrier must wait for the incoming actor"
8858        );
8859
8860        let acknowledgment = match next_dynamic_handler_message(&mut receiver) {
8861            Some(DynamicHandlerMessage::AcknowledgedBarrier(acknowledgment)) => acknowledgment,
8862            other => panic!("expected acknowledged barrier, got {other:?}"),
8863        };
8864        acknowledgment
8865            .send(())
8866            .expect("the barrier receiver should remain active");
8867        futures::executor::block_on(barrier)
8868            .expect("the acknowledged dynamic-handler barrier should complete");
8869    }
8870
8871    #[test]
8872    fn detaching_dynamic_handler_guard_does_not_leak_connection() {
8873        let (connection, mut receiver) = connection_with_dynamic_handler_receiver();
8874        let guard = connection.add_dynamic_handler(NullHandler).unwrap();
8875
8876        assert!(matches!(
8877            next_dynamic_handler_message(&mut receiver),
8878            Some(DynamicHandlerMessage::AddDynamicHandler(_, _, _))
8879        ));
8880
8881        drop(connection);
8882        guard.detach();
8883
8884        assert!(
8885            next_dynamic_handler_message(&mut receiver).is_none(),
8886            "detach should retain the handler without retaining a connection sender"
8887        );
8888    }
8889
8890    #[tokio::test]
8891    async fn write_line_flushes_buffered_writers() {
8892        let mut writer =
8893            futures::io::BufWriter::with_capacity(4096, futures::io::Cursor::new(Vec::new()));
8894
8895        write_line(&mut writer, "message".into()).await.unwrap();
8896
8897        assert_eq!(writer.into_inner().into_inner(), b"message\n");
8898    }
8899
8900    #[tokio::test]
8901    async fn lossy_lines_strip_line_endings_and_replace_invalid_utf8() {
8902        use futures::TryStreamExt as _;
8903
8904        let reader = futures::io::Cursor::new(b"crlf\r\n\ninva\xfflid\nno ending".to_vec());
8905
8906        let lines: Vec<String> = lossy_lines(reader).try_collect().await.unwrap();
8907
8908        assert_eq!(lines, ["crlf", "", "inva\u{FFFD}lid", "no ending"]);
8909    }
8910
8911    #[test]
8912    fn peel_successor_envelopes_returns_plain_messages_unchanged() {
8913        let params = serde_json::json!({ "key": "value" });
8914        let (method, peeled) = peel_successor_envelopes("session/update", &params);
8915        assert_eq!(method, "session/update");
8916        assert_eq!(peeled, &params);
8917    }
8918
8919    #[test]
8920    fn peel_successor_envelopes_unwraps_nested_envelopes() {
8921        let params = serde_json::json!({
8922            "method": "proxy/successor",
8923            "params": {
8924                "method": "$/cancel_request",
8925                "params": { "requestId": "req-1" }
8926            }
8927        });
8928        let (method, peeled) = peel_successor_envelopes("proxy/successor", &params);
8929        assert_eq!(method, "$/cancel_request");
8930        assert_eq!(peeled, &serde_json::json!({ "requestId": "req-1" }));
8931    }
8932
8933    #[test]
8934    fn peel_successor_envelopes_leaves_malformed_envelopes_intact() {
8935        // No string `method` field: the envelope cannot be peeled, so the
8936        // message is returned as-is for the handler chain to deal with.
8937        let params = serde_json::json!({ "unexpected": true });
8938        let (method, peeled) = peel_successor_envelopes("proxy/successor", &params);
8939        assert_eq!(method, "proxy/successor");
8940        assert_eq!(peeled, &params);
8941    }
8942
8943    mod cancel_request {
8944        use super::super::*;
8945
8946        fn notification(method: &str, params: serde_json::Value) -> UntypedMessage {
8947            UntypedMessage::new(method, params).expect("well-formed JSON")
8948        }
8949
8950        #[test]
8951        fn cancellation_request_id_is_extracted_from_wrapped_notifications() {
8952            let message = notification(
8953                "proxy/successor",
8954                serde_json::json!({
8955                    "method": "$/cancel_request",
8956                    "params": { "requestId": "req-1" }
8957                }),
8958            );
8959            let request_id = cancellation_request_id_from_message(&message)
8960                .expect("wrapped cancel should parse");
8961            assert_eq!(request_id, Some(RawJsonRpcId::Str("req-1".into())));
8962        }
8963
8964        #[test]
8965        fn malformed_successor_envelope_is_not_treated_as_cancellation() {
8966            // The envelope cannot be peeled; the message must flow on to the
8967            // handler chain instead of erroring the dispatch.
8968            let message = notification("proxy/successor", serde_json::json!({ "bogus": true }));
8969            let request_id = cancellation_request_id_from_message(&message)
8970                .expect("malformed envelope should be left to the handler chain");
8971            assert_eq!(request_id, None);
8972        }
8973
8974        #[test]
8975        fn cancel_request_notifications_are_detected_even_when_wrapped() {
8976            let plain = notification("$/cancel_request", serde_json::json!({ "requestId": 1 }));
8977            assert!(is_cancel_request_notification(&plain));
8978
8979            let wrapped = notification(
8980                "proxy/successor",
8981                serde_json::json!({
8982                    "method": "$/cancel_request",
8983                    "params": { "requestId": 1 }
8984                }),
8985            );
8986            assert!(is_cancel_request_notification(&wrapped));
8987
8988            let other_wrapped = notification(
8989                "proxy/successor",
8990                serde_json::json!({
8991                    "method": "session/update",
8992                    "params": {}
8993                }),
8994            );
8995            assert!(!is_cancel_request_notification(&other_wrapped));
8996
8997            let malformed_envelope =
8998                notification("proxy/successor", serde_json::json!({ "bogus": true }));
8999            assert!(!is_cancel_request_notification(&malformed_envelope));
9000        }
9001
9002        #[test]
9003        fn malformed_cancel_request_params_error() {
9004            let message = notification(
9005                "$/cancel_request",
9006                serde_json::json!({ "requestId": { "not": "an id" } }),
9007            );
9008            cancellation_request_id_from_message(&message)
9009                .expect_err("malformed cancel params should error");
9010        }
9011
9012        #[test]
9013        fn registry_marks_and_removes_requests() {
9014            let registry = RequestCancellationRegistry::new();
9015            let id = RawJsonRpcId::Str("req-1".into());
9016
9017            let responder_cancellation = registry.register(&id);
9018            let marker = responder_cancellation.cancellation();
9019            assert!(!marker.is_cancelled());
9020
9021            assert!(registry.cancel(&id));
9022            assert!(marker.is_cancelled());
9023            assert!(responder_cancellation.cancellation().is_cancelled());
9024
9025            drop(responder_cancellation);
9026            assert!(!registry.cancel(&id), "slot should be removed on drop");
9027        }
9028
9029        #[test]
9030        fn reused_request_id_does_not_cross_wire_cancellation_state() {
9031            let registry = RequestCancellationRegistry::new();
9032            let id = RawJsonRpcId::Str("dup".into());
9033
9034            // A protocol-violating peer reuses an in-flight request ID.
9035            let first = registry.register(&id);
9036            let first_marker = first.cancellation();
9037            let second = registry.register(&id);
9038            let second_marker = second.cancellation();
9039
9040            // A cancellation targets whichever request currently owns the ID.
9041            assert!(registry.cancel(&id));
9042            assert!(second_marker.is_cancelled());
9043            assert!(
9044                !first_marker.is_cancelled(),
9045                "the stale request must not observe the newer request's cancellation"
9046            );
9047
9048            // The stale responder must hand out detached markers, not the
9049            // newer request's marker.
9050            assert!(!first.cancellation().is_cancelled());
9051
9052            // Dropping the stale responder must not remove the newer
9053            // request's slot.
9054            drop(first);
9055            assert!(registry.cancel(&id), "newer slot should still be present");
9056
9057            drop(second);
9058            assert!(!registry.cancel(&id), "slot should be removed on drop");
9059        }
9060    }
9061}