Skip to main content

ConnectionTo

Struct ConnectionTo 

Source
pub struct ConnectionTo<Counterpart: Role> { /* private fields */ }
Available on crate feature unstable_protocol_v2 only.
Expand description

A protocol-v2 connection context.

Values of this type are supplied to callbacks registered on a v2::Builder. It exposes the general connection operations that are valid for protocol v2 while keeping version-specific high-level helpers for other protocol versions out of the typed context. The generic JSON-RPC send methods remain intentionally schema-agnostic.

This is a thin, cheaply cloneable handle to the underlying JSON-RPC connection. It intentionally does not implement Deref to the version-neutral ConnectionTo; convert explicitly with into_raw and ConnectionTo::into_protocol.

Implementations§

Source§

impl ConnectionTo<Agent>

Source

pub fn send_initialize( &self, request: InitializeRequest, ) -> SentRequest<InitializeOutcome, V2>

Send the client’s initialize request and report how the agent negotiated.

Unlike send_request, a v1-only agent’s valid v1 response resolves successfully as InitializeOutcome::LowerVersion with the agent’s typed response, so the caller can decide whether to fall back to a v1 client implementation. The connection stays uninitialized in that case; the SDK never converts it to v1.

The request still resolves with an error for errors returned by the agent (including the -32022 version mismatch), malformed responses, and transport failures.

After an initialization completes, initialize may be sent again before any other request; the agent treats the latest one as authoritative. Once another request has been sent, a repeat resolves with an -32600 error without being sent.

use agent_client_protocol::SelectedInitializeResponse;
use agent_client_protocol::v2::InitializeOutcome;
let outcome = Client
    .v2()
    .connect_with(agent, async |cx| {
        let request = schema::InitializeRequest::new(
            ProtocolVersion::V2,
            schema::Implementation::new("example", "0.1.0"),
        );
        match cx.send_initialize(request).block_task().await? {
            InitializeOutcome::Initialized(_response) => {
                // Continue with v2 traffic.
                Ok(None)
            }
            InitializeOutcome::LowerVersion(mismatch) => Ok(Some(mismatch)),
            _ => Err(agent_client_protocol::Error::internal_error().data("unexpected outcome")),
        }
    })
    .await?;
if let Some(mismatch) = outcome
    && let SelectedInitializeResponse::V1(_v1_response) = mismatch.response
{
    // Reconnect with a v1 client implementation.
}
Source§

impl<Counterpart: Role> ConnectionTo<Counterpart>

Source

pub fn into_raw(self) -> RawConnectionTo<Counterpart>

The underlying version-neutral connection.

Requests sent through it return Raw handles. Convert back with ConnectionTo::into_protocol.

Source

pub fn counterpart(&self) -> Counterpart

Return the counterpart role this connection is talking to.

Source

pub async fn incoming_closed(&self)

Wait until the incoming transport reaches clean EOF.

Source

pub fn is_incoming_closed(&self) -> bool

Return whether clean incoming-EOF processing has completed.

Source

pub async fn terminated(&self) -> ConnectionTermination

Wait until the connection driver has terminated, for any reason.

See ConnectionTo::terminated.

Source

pub fn termination(&self) -> Option<ConnectionTermination>

Return the termination reason if the connection driver has terminated.

Source

pub fn spawn( &self, task: impl IntoFuture<Output = Result<(), Error>, IntoFuture: Send + 'static>, ) -> Result<(), Error>

Spawn a task that runs for as long as the JSON-RPC connection is served.

Source

pub fn spawn_connection<R: Role, P: Protocol>( &self, builder: Builder<R, impl HandleDispatchFrom<R::Counterpart> + 'static, impl RunWithConnectionTo<R::Counterpart> + 'static, impl HandleConnectionClose<R::Counterpart> + 'static, P>, transport: impl ConnectTo<R> + 'static, ) -> Result<P::Connection<R::Counterpart>, Error>

Spawn a JSON-RPC connection in the background.

The returned connection context is selected by builder; spawning a v2::Builder therefore returns another v2::ConnectionTo.

let child: ConnectionTo<Agent> =
    connection.spawn_connection(Client.v2(), transport)?;
Source

pub fn send_proxied_message<Req: JsonRpcRequest<Response: Send>, Notif: JsonRpcNotification, Q: Protocol>( &self, message: Dispatch<Req, Notif, Q>, ) -> Result<(), Error>
where Counterpart: HasPeer<Counterpart>,

Send a request or notification and forward its response appropriately.

Source

pub fn send_proxied_message_to<Peer: Role, Req: JsonRpcRequest<Response: Send>, Notif: JsonRpcNotification, Q: Protocol>( &self, peer: Peer, message: Dispatch<Req, Notif, Q>, ) -> Result<(), Error>
where Counterpart: HasPeer<Peer>,

Send a request or notification to a specific peer and forward its response appropriately.

Source

pub fn send_request<Req: JsonRpcRequest>( &self, request: Req, ) -> SentRequest<Req::Response, V2>
where Counterpart: HasPeer<Counterpart>,

Send an outgoing request to the default counterpart peer.

Source

pub fn send_request_to<Peer: Role, Req: JsonRpcRequest>( &self, peer: Peer, request: Req, ) -> SentRequest<Req::Response, V2>
where Counterpart: HasPeer<Peer>,

Send an outgoing request to a specific peer.

Source

pub fn prepare_request<Req: JsonRpcRequest>( &self, request: Req, ) -> PreparedRequest<Req::Response, V2>
where Counterpart: HasPeer<Counterpart>,

Prepare a request without sending it until response handling is selected.

See ConnectionTo::prepare_request for publication and ordering semantics.

Source

pub fn prepare_request_to<Peer: Role, Req: JsonRpcRequest>( &self, peer: Peer, request: Req, ) -> PreparedRequest<Req::Response, V2>
where Counterpart: HasPeer<Peer>,

Prepare a request to a specific peer without sending it.

See ConnectionTo::prepare_request_to for publication and ordering semantics.

Source

pub fn send_notification<N: JsonRpcNotification>( &self, notification: N, ) -> Result<(), Error>
where Counterpart: HasPeer<Counterpart>,

Send an outgoing notification to the default counterpart peer.

Source

pub fn send_notification_to<Peer: Role, N: JsonRpcNotification>( &self, peer: Peer, notification: N, ) -> Result<(), Error>
where Counterpart: HasPeer<Peer>,

Send an outgoing notification to a specific peer.

Source

pub fn send_cancel_request( &self, request_id: impl Into<RequestId>, ) -> Result<(), Error>
where Counterpart: HasPeer<Counterpart>,

Send a $/cancel_request notification to the default counterpart peer.

Prefer SentRequest::cancel when you have the request handle. request_id is a v2 request ID, such as the id of a request sent through this connection. The raw ConnectionTo::send_cancel_request takes any RawJsonRpcId.

Source

pub fn send_cancel_request_to<Peer: Role>( &self, peer: Peer, request_id: impl Into<RequestId>, ) -> Result<(), Error>
where Counterpart: HasPeer<Peer>,

Send a $/cancel_request notification to a specific peer.

The notification is always sent plain, never wrapped in proxy/successor, as the raw ConnectionTo::send_cancel_request_to describes. See send_cancel_request.

Source

pub fn add_dynamic_handler( &self, handler: impl HandleDispatchFrom<Counterpart> + 'static, ) -> Result<DynamicHandlerGuard<Counterpart>, Error>

Register a low-level dynamic message handler.

Dynamic handlers use the version-neutral HandleDispatchFrom trait, so their callback receives the underlying version-neutral ConnectionTo. Prefer typed handlers on v2::Builder when registration can happen before the connection starts.

Client.v2().connect_with(transport, async |connection| {
    let guard: DynamicHandlerGuard<Agent> =
        connection.add_dynamic_handler(NullHandler)?;

    // Keep `guard` alive for as long as the modal handler is needed.
    drop(guard);
    Ok(())
}).await
Source§

impl<Counterpart> ConnectionTo<Counterpart>
where Counterpart: HasPeer<Agent>,

Source

pub fn build_session( &self, cwd: impl AsRef<Path>, ) -> SessionBuilder<Counterpart>

Build a draft protocol v2 session/new request.

cwd must be an absolute path: ACP requires one, and the SDK sends it without checking.

Source

pub fn build_session_cwd(&self) -> Result<SessionBuilder<Counterpart>, Error>

Build a draft protocol v2 session using the current working directory.

Returns an error if the current directory cannot be determined.

Source

pub fn build_session_from( &self, request: NewSessionRequest, ) -> SessionBuilder<Counterpart>

Build a draft protocol v2 session from an existing session/new request.

Source

pub fn fork_session( &self, session_id: impl Into<SessionId>, cwd: impl AsRef<Path>, ) -> ForkSessionBuilder<Counterpart>

Available on crate feature unstable_session_fork only.

Build an unstable draft protocol v2 session/fork request.

This helper is available with the unstable_session_fork feature. Call ForkSessionBuilder::start_session to publish the request and obtain a command handle for the newly created fork.

cwd must be an absolute path: ACP requires one, and the SDK sends it without checking.

Source

pub fn fork_session_from( &self, request: ForkSessionRequest, ) -> ForkSessionBuilder<Counterpart>

Available on crate feature unstable_session_fork only.

Build an unstable draft protocol v2 session/fork request from an existing request.

This helper is available with the unstable_session_fork feature. Call ForkSessionBuilder::start_session to publish the request.

Source

pub fn resume_session( &self, session_id: impl Into<SessionId>, cwd: impl AsRef<Path>, ) -> ResumeSessionBuilder<Counterpart>

Build a draft protocol v2 session/resume request.

Use Self::resume_session_from to request history replay or set other optional resume parameters. Call ResumeSessionBuilder::start_session to publish the request.

cwd must be an absolute path: ACP requires one, and the SDK sends it without checking.

Source

pub fn resume_session_from( &self, request: ResumeSessionRequest, ) -> ResumeSessionBuilder<Counterpart>

Build a draft protocol v2 session/resume request from an existing request.

Register typed session update handlers before connecting. When the request asks for replay, the agent sends those updates before the v2::schema::ResumeSessionResponse. Call ResumeSessionBuilder::start_session to publish the request.

Trait Implementations§

Source§

impl<Counterpart: Clone + Role> Clone for ConnectionTo<Counterpart>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<Counterpart: Debug + Role> Debug for ConnectionTo<Counterpart>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<Counterpart: Role> From<ConnectionTo<Counterpart>> for ConnectionTo<Counterpart>

Source§

fn from(connection: ConnectionTo<Counterpart>) -> Self

The same as ConnectionTo::into_raw. Generic code over Protocol uses it to turn a P::Connection<Counterpart> back into the version-neutral connection.

Auto Trait Implementations§

§

impl<Counterpart> !RefUnwindSafe for ConnectionTo<Counterpart>

§

impl<Counterpart> !UnwindSafe for ConnectionTo<Counterpart>

§

impl<Counterpart> Freeze for ConnectionTo<Counterpart>
where ConnectionTo<Counterpart>: Freeze,

§

impl<Counterpart> Send for ConnectionTo<Counterpart>
where ConnectionTo<Counterpart>: Send,

§

impl<Counterpart> Sync for ConnectionTo<Counterpart>
where ConnectionTo<Counterpart>: Sync,

§

impl<Counterpart> Unpin for ConnectionTo<Counterpart>
where ConnectionTo<Counterpart>: Unpin,

§

impl<Counterpart> UnsafeUnpin for ConnectionTo<Counterpart>
where ConnectionTo<Counterpart>: UnsafeUnpin,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoMaybeUndefined<T> for T

Source§

fn into_maybe_undefined(self) -> MaybeUndefined<T>

Converts this value into a three-state builder argument.
Source§

impl<T> IntoOption<T> for T

Source§

fn into_option(self) -> Option<T>

Converts this value into an optional builder argument.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more