Skip to main content

agent_client_protocol/jsonrpc/
v1_connection.rs

1//! The protocol-v1 connection type, `agent_client_protocol::v1::ConnectionTo`.
2
3use super::ConnectionTo as RawConnectionTo;
4use super::{
5    Builder, ConnectTo, ConnectionTermination, Dispatch, DynamicHandlerGuard,
6    HandleConnectionClose, HandleDispatchFrom, JsonRpcNotification, JsonRpcRequest,
7    PreparedRequest, Protocol, SentRequest, V1, run::RunWithConnectionTo,
8};
9use crate::role::{HasPeer, Role};
10
11/// A protocol-v1 connection context.
12///
13/// Values of this type are supplied to callbacks registered on a
14/// [`v1::Builder`](crate::v1::Builder). It exposes the general connection
15/// operations, typed for protocol v1, and the v1 session helpers such as
16/// [`build_session`](Self::build_session). Requests sent through it return
17/// [`v1::SentRequest`](crate::v1::SentRequest) and
18/// [`v1::PreparedRequest`](crate::v1::PreparedRequest), whose `id()` is a
19/// [`v1::schema::RequestId`](crate::v1::schema::RequestId). The generic
20/// JSON-RPC send methods remain schema-agnostic.
21///
22/// This is a thin, cheaply cloneable handle to the underlying JSON-RPC
23/// connection. It intentionally does not implement [`Deref`](std::ops::Deref)
24/// to the version-neutral [`ConnectionTo`](crate::ConnectionTo); convert
25/// explicitly with [`into_raw`](Self::into_raw) and
26/// [`ConnectionTo::into_protocol`](crate::ConnectionTo::into_protocol).
27#[derive(Clone, Debug)]
28pub struct ConnectionTo<Counterpart: Role> {
29    pub(crate) inner: RawConnectionTo<Counterpart>,
30}
31
32impl<Counterpart: Role> From<ConnectionTo<Counterpart>> for RawConnectionTo<Counterpart> {
33    /// The same as [`ConnectionTo::into_raw`]. Generic code over
34    /// [`Protocol`] uses it to turn a `P::Connection<Counterpart>` back into
35    /// the version-neutral connection.
36    fn from(connection: ConnectionTo<Counterpart>) -> Self {
37        connection.into_raw()
38    }
39}
40
41impl<Counterpart: Role> ConnectionTo<Counterpart> {
42    /// Access the underlying version-neutral connection inside the SDK.
43    pub(crate) fn raw_connection(&self) -> &RawConnectionTo<Counterpart> {
44        &self.inner
45    }
46
47    /// The underlying version-neutral connection.
48    ///
49    /// Requests sent through it return [`Raw`](crate::Raw) handles. Convert
50    /// back with [`ConnectionTo::into_protocol`](crate::ConnectionTo::into_protocol).
51    #[must_use]
52    pub fn into_raw(self) -> RawConnectionTo<Counterpart> {
53        self.inner
54    }
55
56    /// Return the counterpart role this connection is talking to.
57    pub fn counterpart(&self) -> Counterpart {
58        self.inner.counterpart()
59    }
60
61    /// Wait until the incoming transport reaches clean EOF.
62    pub async fn incoming_closed(&self) {
63        self.inner.incoming_closed().await;
64    }
65
66    /// Return whether clean incoming-EOF processing has completed.
67    #[must_use]
68    pub fn is_incoming_closed(&self) -> bool {
69        self.inner.is_incoming_closed()
70    }
71
72    /// Wait until the connection driver has terminated, for any reason.
73    ///
74    /// See [`ConnectionTo::terminated`](crate::ConnectionTo::terminated).
75    pub async fn terminated(&self) -> ConnectionTermination {
76        self.inner.terminated().await
77    }
78
79    /// Return the termination reason if the connection driver has terminated.
80    #[must_use]
81    pub fn termination(&self) -> Option<ConnectionTermination> {
82        self.inner.termination()
83    }
84
85    /// Spawn a task that runs for as long as the JSON-RPC connection is served.
86    ///
87    /// # Errors
88    ///
89    /// Returns an error if the connection's task queue is closed.
90    #[track_caller]
91    pub fn spawn(
92        &self,
93        task: impl IntoFuture<Output = Result<(), crate::Error>, IntoFuture: Send + 'static>,
94    ) -> Result<(), crate::Error> {
95        self.inner.spawn(task)
96    }
97
98    /// Spawn a JSON-RPC connection in the background.
99    ///
100    /// The returned connection context is selected by `builder`; spawning a
101    /// [`v1::Builder`](crate::v1::Builder) therefore returns another
102    /// [`v1::ConnectionTo`](ConnectionTo).
103    ///
104    /// # Errors
105    ///
106    /// Returns an error if the parent connection cannot queue the child connection's task.
107    ///
108    /// ```no_run
109    /// # use agent_client_protocol::{
110    /// #     Agent, Client, ConnectTo, Error,
111    /// # };
112    /// # use agent_client_protocol::v1::ConnectionTo;
113    /// # fn example(
114    /// #     connection: ConnectionTo<Agent>,
115    /// #     transport: impl ConnectTo<Client> + 'static,
116    /// # ) -> Result<(), Error> {
117    /// let child: ConnectionTo<Agent> =
118    ///     connection.spawn_connection(Client.v1(), transport)?;
119    /// # drop(child);
120    /// # Ok(())
121    /// # }
122    /// ```
123    #[track_caller]
124    pub fn spawn_connection<R: Role, P: Protocol>(
125        &self,
126        builder: Builder<
127            R,
128            impl HandleDispatchFrom<R::Counterpart> + 'static,
129            impl RunWithConnectionTo<R::Counterpart> + 'static,
130            impl HandleConnectionClose<R::Counterpart> + 'static,
131            P,
132        >,
133        transport: impl ConnectTo<R> + 'static,
134    ) -> Result<P::Connection<R::Counterpart>, crate::Error> {
135        self.inner.spawn_connection(builder, transport)
136    }
137
138    /// Send a request or notification and forward its response appropriately.
139    ///
140    /// # Errors
141    ///
142    /// Returns the forwarding error from [`send_proxied_message_to`](crate::ConnectionTo::send_proxied_message_to).
143    pub fn send_proxied_message<
144        Req: JsonRpcRequest<Response: Send>,
145        Notif: JsonRpcNotification,
146        Q: Protocol,
147    >(
148        &self,
149        message: Dispatch<Req, Notif, Q>,
150    ) -> Result<(), crate::Error>
151    where
152        Counterpart: HasPeer<Counterpart>,
153    {
154        self.inner.send_proxied_message(message)
155    }
156
157    /// Send a request or notification to a specific peer and forward its
158    /// response appropriately.
159    ///
160    /// # Errors
161    ///
162    /// Returns the forwarding error from [`send_proxied_message_to`](crate::ConnectionTo::send_proxied_message_to).
163    pub fn send_proxied_message_to<
164        Peer: Role,
165        Req: JsonRpcRequest<Response: Send>,
166        Notif: JsonRpcNotification,
167        Q: Protocol,
168    >(
169        &self,
170        peer: Peer,
171        message: Dispatch<Req, Notif, Q>,
172    ) -> Result<(), crate::Error>
173    where
174        Counterpart: HasPeer<Peer>,
175    {
176        self.inner.send_proxied_message_to(peer, message)
177    }
178
179    /// Send an outgoing request to the default counterpart peer.
180    pub fn send_request<Req: JsonRpcRequest>(&self, request: Req) -> SentRequest<Req::Response, V1>
181    where
182        Counterpart: HasPeer<Counterpart>,
183    {
184        self.send_request_to(self.inner.counterpart(), request)
185    }
186
187    /// Send an outgoing request to a specific peer.
188    pub fn send_request_to<Peer: Role, Req: JsonRpcRequest>(
189        &self,
190        peer: Peer,
191        request: Req,
192    ) -> SentRequest<Req::Response, V1>
193    where
194        Counterpart: HasPeer<Peer>,
195    {
196        self.inner
197            .send_request_to_with_options(peer, request, false, None, None)
198    }
199
200    /// Prepare a request without sending it until response handling is selected.
201    ///
202    /// See [`ConnectionTo::prepare_request`](crate::ConnectionTo::prepare_request) for publication and ordering semantics.
203    pub fn prepare_request<Req: JsonRpcRequest>(
204        &self,
205        request: Req,
206    ) -> PreparedRequest<Req::Response, V1>
207    where
208        Counterpart: HasPeer<Counterpart>,
209    {
210        self.prepare_request_to(self.inner.counterpart(), request)
211    }
212
213    /// Prepare a request to a specific peer without sending it.
214    ///
215    /// See [`ConnectionTo::prepare_request_to`](crate::ConnectionTo::prepare_request_to) for publication and ordering semantics.
216    pub fn prepare_request_to<Peer: Role, Req: JsonRpcRequest>(
217        &self,
218        peer: Peer,
219        request: Req,
220    ) -> PreparedRequest<Req::Response, V1>
221    where
222        Counterpart: HasPeer<Peer>,
223    {
224        self.inner
225            .prepare_request_to_with_options(peer, request, None, None)
226    }
227
228    /// Send an outgoing notification to the default counterpart peer.
229    ///
230    /// # Errors
231    ///
232    /// Returns an error if the notification cannot be encoded or queued.
233    pub fn send_notification<N: JsonRpcNotification>(
234        &self,
235        notification: N,
236    ) -> Result<(), crate::Error>
237    where
238        Counterpart: HasPeer<Counterpart>,
239    {
240        self.inner.send_notification(notification)
241    }
242
243    /// Send an outgoing notification to a specific peer.
244    ///
245    /// # Errors
246    ///
247    /// Returns an error if the notification cannot be encoded for the peer or queued.
248    pub fn send_notification_to<Peer: Role, N: JsonRpcNotification>(
249        &self,
250        peer: Peer,
251        notification: N,
252    ) -> Result<(), crate::Error>
253    where
254        Counterpart: HasPeer<Peer>,
255    {
256        self.inner.send_notification_to(peer, notification)
257    }
258
259    /// Send a `$/cancel_request` notification to the default counterpart peer.
260    ///
261    /// Prefer [`SentRequest::cancel`](crate::SentRequest::cancel) when you
262    /// have the request handle. `request_id` is a v1 request ID, such as the
263    /// [`id`](crate::SentRequest::id) of a request sent through this
264    /// connection. The raw [`ConnectionTo::send_cancel_request`](crate::ConnectionTo::send_cancel_request)
265    /// takes any [`RawJsonRpcId`](crate::RawJsonRpcId).
266    ///
267    /// # Errors
268    ///
269    /// Returns an error if the cancellation notification cannot be encoded or queued.
270    pub fn send_cancel_request(
271        &self,
272        request_id: impl Into<crate::v1::schema::RequestId>,
273    ) -> Result<(), crate::Error>
274    where
275        Counterpart: HasPeer<Counterpart>,
276    {
277        self.inner.send_cancel_request(request_id.into())
278    }
279
280    /// Send a `$/cancel_request` notification to a specific peer.
281    ///
282    /// The notification is always sent plain, never wrapped in
283    /// `proxy/successor`, as the raw
284    /// [`ConnectionTo::send_cancel_request_to`](crate::ConnectionTo::send_cancel_request_to)
285    /// describes. See [`send_cancel_request`](Self::send_cancel_request).
286    ///
287    /// # Errors
288    ///
289    /// Returns an error if the cancellation notification cannot be encoded or queued.
290    pub fn send_cancel_request_to<Peer: Role>(
291        &self,
292        peer: Peer,
293        request_id: impl Into<crate::v1::schema::RequestId>,
294    ) -> Result<(), crate::Error>
295    where
296        Counterpart: HasPeer<Peer>,
297    {
298        self.inner.send_cancel_request_to(peer, request_id.into())
299    }
300
301    /// Register a low-level dynamic message handler.
302    ///
303    /// Dynamic handlers use the version-neutral [`HandleDispatchFrom`] trait,
304    /// so their callback receives the underlying version-neutral
305    /// [`ConnectionTo`](crate::ConnectionTo). Prefer typed handlers on
306    /// [`v1::Builder`](crate::v1::Builder) when registration can happen before the
307    /// connection starts.
308    ///
309    /// # Errors
310    ///
311    /// Returns an error if the connection no longer accepts handler registrations.
312    ///
313    /// ```no_run
314    /// # use agent_client_protocol::{
315    /// #     Agent, Client, ConnectTo, DynamicHandlerGuard, Error, NullHandler,
316    /// # };
317    /// # async fn example(
318    /// #     transport: impl ConnectTo<Client> + 'static,
319    /// # ) -> Result<(), Error> {
320    /// Client.v1().connect_with(transport, async |connection| {
321    ///     let guard: DynamicHandlerGuard<Agent> =
322    ///         connection.add_dynamic_handler(NullHandler)?;
323    ///
324    ///     // Keep `guard` alive for as long as the modal handler is needed.
325    ///     drop(guard);
326    ///     Ok(())
327    /// }).await
328    /// # }
329    /// ```
330    pub fn add_dynamic_handler(
331        &self,
332        handler: impl HandleDispatchFrom<Counterpart> + 'static,
333    ) -> Result<DynamicHandlerGuard<Counterpart>, crate::Error> {
334        self.inner.add_dynamic_handler(handler)
335    }
336}