agent_client_protocol/session.rs
1use std::{future::Future, marker::PhantomData, path::Path, sync::Arc};
2
3use futures::channel::mpsc;
4use futures::future::{self, Either};
5
6use crate::{
7 Agent, Client, ConnectionTo as RawConnectionTo, Dispatch, HandleDispatchFrom, Handled,
8 JsonRpcRequest, Responder, Role,
9 jsonrpc::{
10 DynamicHandlerCleanup, DynamicHandlerGuard,
11 run::{NullRun, RunWithConnectionTo, RunnerErrorScope},
12 },
13 role::{HasPeer, acp::ProxySessionMessages},
14 util::{MatchDispatch, MatchDispatchFrom},
15 v1::ConnectionTo,
16 v1::schema::{
17 ContentBlock, ContentChunk, LoadSessionRequest, LoadSessionResponse, NewSessionRequest,
18 NewSessionResponse, PromptRequest, PromptResponse, ResumeSessionRequest,
19 ResumeSessionResponse, SessionId, SessionNotification, SessionUpdate,
20 },
21};
22
23use crate::Raw;
24#[cfg(feature = "unstable_mcp_over_acp")]
25use crate::{jsonrpc::run::ChainRun, mcp_server::McpServer};
26
27#[cfg(feature = "unstable_protocol_v2")]
28pub(crate) mod v2;
29
30type SessionCleanup = Vec<Arc<dyn DynamicHandlerCleanup>>;
31
32fn session_cleanup<R: Role>(guards: &[DynamicHandlerGuard<R>]) -> SessionCleanup {
33 guards
34 .iter()
35 .filter_map(DynamicHandlerGuard::cleanup)
36 .collect()
37}
38
39fn close_session_registrations(cleanup: &SessionCleanup) {
40 for registration in cleanup {
41 registration.close();
42 }
43}
44
45async fn wait_session_cleanup(cleanup: SessionCleanup) {
46 future::join_all(cleanup.iter().map(|registration| registration.wait())).await;
47}
48
49fn session_runner_connection<R: Role>(
50 connection: RawConnectionTo<R>,
51 cleanup: &SessionCleanup,
52) -> (RawConnectionTo<R>, RunnerErrorScope) {
53 let closing = cleanup.clone();
54 let scope = RunnerErrorScope::new(
55 move || close_session_registrations(&closing),
56 wait_session_cleanup(cleanup.clone()),
57 );
58 (connection.with_runner_error_scope(scope.clone()), scope)
59}
60
61/// Keep the actual (possibly borrowed) runner alive until only these
62/// registrations finish. Never seal connection-wide protected admission here.
63async fn drive_session_cleanup(
64 run: impl Future<Output = Result<(), crate::Error>>,
65 cleanup: SessionCleanup,
66) -> Result<(), crate::Error> {
67 match future::select(
68 Box::pin(wait_session_cleanup(cleanup.clone())),
69 Box::pin(run),
70 )
71 .await
72 {
73 Either::Left(((), _run)) => Ok(()),
74 Either::Right((result, waiting)) => {
75 if result.is_err() {
76 close_session_registrations(&cleanup);
77 }
78 waiting.await;
79 result
80 }
81 }
82}
83
84async fn run_attached_session_runner(
85 run: impl Future<Output = Result<(), crate::Error>>,
86 cleanup: SessionCleanup,
87 error_scope: RunnerErrorScope,
88) -> Result<(), crate::Error> {
89 let result = if cleanup.is_empty() {
90 run.await
91 } else {
92 drive_session_cleanup(run, cleanup).await
93 };
94 // Local cleanup can win the race against the retained chain's final poll.
95 // Once attached, an observed runner failure must still reach the task actor.
96 error_scope.error().map_or(result, Err)
97}
98
99async fn run_session_scope<T>(
100 run: impl Future<Output = Result<(), crate::Error>>,
101 op: impl Future<Output = Result<T, crate::Error>>,
102 cleanup: SessionCleanup,
103 error_scope: RunnerErrorScope,
104) -> Result<T, crate::Error> {
105 let result = match future::select(Box::pin(run), Box::pin(op)).await {
106 Either::Left((run_result, op)) => {
107 let result = match run_result {
108 Ok(()) => op.await,
109 Err(error) => {
110 drop(op);
111 Err(error)
112 }
113 };
114 close_session_registrations(&cleanup);
115 wait_session_cleanup(cleanup).await;
116 result
117 }
118 Either::Right((result, run)) => {
119 close_session_registrations(&cleanup);
120 let runner_result = drive_session_cleanup(run, cleanup).await;
121 // Foreground failure remains authoritative over cleanup failures.
122 result.and_then(|value| runner_result.map(|()| value))
123 }
124 };
125 // The chain may have observed an error while still Pending for cleanup.
126 // Successful foreground completion must not hide that recorded failure.
127 // An explicit foreground error remains authoritative.
128 result.and_then(|value| error_scope.error().map_or(Ok(value), Err))
129}
130
131/// Marker type indicating the session builder will block the current task.
132#[derive(Debug)]
133pub struct Blocking;
134impl block_state::Sealed for Blocking {}
135impl SessionBlockState for Blocking {}
136
137/// Marker type indicating the session builder will not block the current task.
138#[derive(Debug)]
139pub struct NonBlocking;
140impl block_state::Sealed for NonBlocking {}
141impl SessionBlockState for NonBlocking {}
142
143mod block_state {
144 pub trait Sealed {}
145}
146
147/// Trait for marker types that indicate blocking vs non-blocking API.
148/// See [`SessionBuilder::block_task`].
149///
150/// This trait is sealed: [`Blocking`] and [`NonBlocking`] are its only
151/// implementations.
152pub trait SessionBlockState: block_state::Sealed + Send + 'static + Sync + std::fmt::Debug {}
153
154impl<Counterpart: Role> ConnectionTo<Counterpart>
155where
156 Counterpart: HasPeer<Agent>,
157{
158 /// Stable protocol v1 session builder for a new session request.
159 ///
160 /// With `unstable_protocol_v2`, a `Client.v2()` callback receives a
161 /// `v2::ConnectionTo` with its own v2 `build_session` helper.
162 ///
163 /// `cwd` must be an absolute path: ACP requires one, and the SDK sends it
164 /// without checking.
165 pub fn build_session(&self, cwd: impl AsRef<Path>) -> SessionBuilder<Counterpart, NullRun> {
166 SessionBuilder::new(self, NewSessionRequest::new(cwd.as_ref()))
167 }
168
169 /// Stable protocol v1 session builder using the current working directory.
170 ///
171 /// This is a convenience wrapper around [`build_session`](Self::build_session)
172 /// that uses [`std::env::current_dir`] to get the working directory.
173 ///
174 /// # Errors
175 ///
176 /// Returns an error if the current directory cannot be determined.
177 pub fn build_session_cwd(&self) -> Result<SessionBuilder<Counterpart, NullRun>, crate::Error> {
178 let cwd = std::env::current_dir().map_err(|e| {
179 crate::Error::internal_error().data(format!("cannot get current directory: {e}"))
180 })?;
181 Ok(self.build_session(cwd))
182 }
183
184 /// Stable protocol v1 session builder starting from an existing request.
185 ///
186 /// Use this when you've intercepted a `session.new` request and want to
187 /// modify it (e.g., inject MCP servers) before forwarding.
188 pub fn build_session_from(
189 &self,
190 request: NewSessionRequest,
191 ) -> SessionBuilder<Counterpart, NullRun> {
192 SessionBuilder::new(self, request)
193 }
194
195 /// Stable protocol v1 session builder that loads an existing session.
196 ///
197 /// The returned builder installs session routing before publishing
198 /// `session/load`, so replay notifications sent before the response are
199 /// available through the restored [`ActiveSession`].
200 ///
201 /// Call this only when the initialization response advertises
202 /// `agentCapabilities.loadSession`.
203 ///
204 /// `cwd` must be an absolute path: ACP requires one, and the SDK sends it
205 /// without checking.
206 pub fn load_session(
207 &self,
208 session_id: impl Into<SessionId>,
209 cwd: impl AsRef<Path>,
210 ) -> LoadSessionBuilder<Counterpart> {
211 self.load_session_from(LoadSessionRequest::new(session_id, cwd.as_ref()))
212 }
213
214 /// Stable protocol v1 session builder from an existing `session/load`
215 /// request.
216 ///
217 /// Use this to send a typed request assembled or intercepted elsewhere
218 /// without rebuilding it.
219 pub fn load_session_from(
220 &self,
221 request: LoadSessionRequest,
222 ) -> LoadSessionBuilder<Counterpart> {
223 RestoreSessionBuilder::new(self, request)
224 }
225
226 /// Stable protocol v1 session builder that resumes an existing session.
227 ///
228 /// This is the `session/resume` counterpart of
229 /// [`load_session`](Self::load_session), but continues without replaying
230 /// conversation history. Call this only when the initialization response
231 /// advertises `agentCapabilities.sessionCapabilities.resume`.
232 ///
233 /// `cwd` must be an absolute path: ACP requires one, and the SDK sends it
234 /// without checking.
235 pub fn resume_session(
236 &self,
237 session_id: impl Into<SessionId>,
238 cwd: impl AsRef<Path>,
239 ) -> ResumeSessionBuilder<Counterpart> {
240 self.resume_session_from(ResumeSessionRequest::new(session_id, cwd.as_ref()))
241 }
242
243 /// Stable protocol v1 session builder from an existing `session/resume`
244 /// request.
245 ///
246 /// Use this to send a typed request assembled or intercepted elsewhere
247 /// without rebuilding it.
248 pub fn resume_session_from(
249 &self,
250 request: ResumeSessionRequest,
251 ) -> ResumeSessionBuilder<Counterpart> {
252 RestoreSessionBuilder::new(self, request)
253 }
254
255 /// Given a session response received from the agent,
256 /// attach a handler to process messages related to this session
257 /// and return the session together with the response.
258 ///
259 /// Normally you would not use this method directly but would
260 /// instead use [`Self::build_session`] and then [`SessionBuilder::start_session`].
261 ///
262 /// The vector `dynamic_handler_registrations` contains any dynamic
263 /// handle registrations associated with this session (e.g., from MCP servers).
264 /// You can simply pass `Default::default()` if not applicable.
265 pub(crate) fn attach_session<'runner>(
266 &self,
267 response: NewSessionResponse,
268 mcp_handler_registrations: Vec<DynamicHandlerGuard<Counterpart>>,
269 ) -> Result<SessionSetup<'runner, Counterpart, NewSessionResponse>, crate::Error> {
270 let prepared = self.prepare_session_routing(&response.session_id)?;
271 let session = prepared.into_active_session(
272 self.clone(),
273 response.session_id.clone(),
274 mcp_handler_registrations,
275 );
276 Ok(SessionSetup { session, response })
277 }
278
279 /// Install the update channel and handler for `session_id`.
280 ///
281 /// Restore requests call this before request publication. Dropping the
282 /// returned value deactivates and removes the route.
283 fn prepare_session_routing(
284 &self,
285 session_id: &SessionId,
286 ) -> Result<PreparedSession<Counterpart>, crate::Error> {
287 let (update_tx, update_rx) = mpsc::unbounded();
288 let handler = ActiveSessionHandler::new(session_id.clone(), update_tx.clone());
289 let session_handler_registration = self.add_dynamic_handler(handler)?;
290
291 Ok(PreparedSession {
292 update_rx,
293 update_tx,
294 session_handler_registration,
295 })
296 }
297}
298
299/// Session-routing state installed before a restore request is published.
300struct PreparedSession<Counterpart: Role>
301where
302 Counterpart: HasPeer<Agent>,
303{
304 update_rx: mpsc::UnboundedReceiver<SessionMessage>,
305 update_tx: mpsc::UnboundedSender<SessionMessage>,
306 session_handler_registration: DynamicHandlerGuard<Counterpart>,
307}
308
309impl<Counterpart> PreparedSession<Counterpart>
310where
311 Counterpart: HasPeer<Agent>,
312{
313 fn into_active_session<'runner>(
314 self,
315 connection: ConnectionTo<Counterpart>,
316 session_id: SessionId,
317 mcp_handler_registrations: Vec<DynamicHandlerGuard<Counterpart>>,
318 ) -> ActiveSession<'runner, Counterpart> {
319 ActiveSession {
320 session_id,
321 update_rx: self.update_rx,
322 update_tx: self.update_tx,
323 connection,
324 session_handler_registration: self.session_handler_registration,
325 mcp_handler_registrations,
326 _runner: PhantomData,
327 }
328 }
329}
330
331/// Internal behavior shared by the two stable restore operations.
332trait RestoreRequest: JsonRpcRequest {
333 fn session_id(&self) -> &SessionId;
334}
335
336impl RestoreRequest for LoadSessionRequest {
337 fn session_id(&self) -> &SessionId {
338 &self.session_id
339 }
340}
341
342impl RestoreRequest for ResumeSessionRequest {
343 fn session_id(&self) -> &SessionId {
344 &self.session_id
345 }
346}
347
348/// Stable protocol v1 builder for `session/load` or `session/resume`.
349///
350/// This type is not exported. Callers name it through the
351/// [`LoadSessionBuilder`] and [`ResumeSessionBuilder`] aliases.
352///
353/// Use [`ConnectionTo::load_session`] or [`ConnectionTo::resume_session`] to
354/// construct this builder. Use the matching `_from` method to send an existing
355/// typed request without rebuilding it.
356///
357/// The `BlockState` parameter mirrors [`SessionBuilder`]:
358/// - [`NonBlocking`] exposes `on_session_start` on each concrete operation.
359/// - [`Blocking`], selected with [`Self::block_task`], exposes
360/// `start_session`.
361///
362/// Session routing is acknowledged before the request can reach the peer.
363/// Dropping a pending blocking start removes that routing and applies the
364/// standard [`SentRequest`](crate::SentRequest) drop-time cancellation
365/// behavior. Error responses remove the route before later entries in the same
366/// transport frame are dispatched.
367#[must_use = "use `start_session` or `on_session_start` to restore the session"]
368#[derive(Debug)]
369pub struct RestoreSessionBuilder<Counterpart, Request, BlockState = NonBlocking>
370where
371 Counterpart: HasPeer<Agent>,
372 BlockState: SessionBlockState,
373{
374 connection: ConnectionTo<Counterpart>,
375 request: Request,
376 block_state: PhantomData<BlockState>,
377}
378
379/// Stable protocol v1 builder for a `session/load` request, returned by
380/// [`ConnectionTo::load_session`] and [`ConnectionTo::load_session_from`].
381///
382/// The `BlockState` parameter mirrors [`SessionBuilder`]:
383/// - [`NonBlocking`] exposes `on_session_start`.
384/// - [`Blocking`], selected with `block_task`, exposes `start_session`.
385///
386/// Session routing is installed before the request can reach the peer, so
387/// replay notifications sent before the response are kept on the restored
388/// [`ActiveSession`].
389///
390/// Unlike [`SessionBuilder`], this builder has no `with_mcp_server` and no
391/// proxy helpers (`on_proxy_session_start`, `start_session_proxy`). To add an
392/// MCP server to load requests a proxy forwards, use `with_mcp_server` on the
393/// proxy's [`v1::Builder`](crate::v1::Builder).
394pub type LoadSessionBuilder<Counterpart, BlockState = NonBlocking> =
395 RestoreSessionBuilder<Counterpart, LoadSessionRequest, BlockState>;
396
397/// Stable protocol v1 builder for a `session/resume` request, returned by
398/// [`ConnectionTo::resume_session`] and [`ConnectionTo::resume_session_from`].
399///
400/// The `BlockState` parameter mirrors [`SessionBuilder`]:
401/// - [`NonBlocking`] exposes `on_session_start`.
402/// - [`Blocking`], selected with `block_task`, exposes `start_session`.
403///
404/// Unlike [`SessionBuilder`], this builder has no `with_mcp_server` and no
405/// proxy helpers (`on_proxy_session_start`, `start_session_proxy`). To add an
406/// MCP server to resume requests a proxy forwards, use `with_mcp_server` on
407/// the proxy's [`v1::Builder`](crate::v1::Builder).
408pub type ResumeSessionBuilder<Counterpart, BlockState = NonBlocking> =
409 RestoreSessionBuilder<Counterpart, ResumeSessionRequest, BlockState>;
410
411impl<Counterpart, Request> RestoreSessionBuilder<Counterpart, Request, NonBlocking>
412where
413 Counterpart: HasPeer<Agent>,
414{
415 fn new(connection: &ConnectionTo<Counterpart>, request: Request) -> Self {
416 Self {
417 connection: connection.clone(),
418 request,
419 block_state: PhantomData,
420 }
421 }
422
423 /// Mark this restore builder as able to block the current task.
424 ///
425 /// Do not use the resulting blocking methods inside a message handler.
426 pub fn block_task(self) -> RestoreSessionBuilder<Counterpart, Request, Blocking> {
427 RestoreSessionBuilder {
428 connection: self.connection,
429 request: self.request,
430 block_state: PhantomData,
431 }
432 }
433}
434
435fn restored_session<Counterpart, Request>(
436 connection: ConnectionTo<Counterpart>,
437 session_id: SessionId,
438 prepared: PreparedSession<Counterpart>,
439 response: Request::Response,
440) -> SessionSetup<'static, Counterpart, Request::Response>
441where
442 Counterpart: HasPeer<Agent>,
443 Request: RestoreRequest,
444{
445 let session = prepared.into_active_session(connection, session_id, Vec::new());
446
447 SessionSetup { session, response }
448}
449
450fn on_restore_session_start<Counterpart, Request, F, Fut>(
451 builder: RestoreSessionBuilder<Counterpart, Request>,
452 op: F,
453) -> Result<(), crate::Error>
454where
455 Counterpart: HasPeer<Agent>,
456 Request: RestoreRequest,
457 F: FnOnce(SessionSetup<'static, Counterpart, Request::Response>) -> Fut + Send + 'static,
458 Fut: Future<Output = Result<(), crate::Error>> + Send,
459{
460 let RestoreSessionBuilder {
461 connection,
462 request,
463 block_state: _,
464 } = builder;
465 let session_id = request.session_id().clone();
466 let prepared = connection.prepare_session_routing(&session_id)?;
467 let routing_ready = connection.raw_connection().dynamic_handler_barrier();
468
469 connection
470 .raw_connection()
471 .send_ordered_request_to_after::<Raw, _, _, _>(Agent, request, routing_ready)
472 .on_receiving_result({
473 let connection = connection.clone();
474 async move |result| {
475 let response = result?;
476 let restored = restored_session::<_, Request>(
477 connection.clone(),
478 session_id,
479 prepared,
480 response,
481 );
482 connection.spawn(async move { op(restored).await })
483 }
484 })
485}
486
487async fn start_restored_session<Counterpart, Request>(
488 builder: RestoreSessionBuilder<Counterpart, Request, Blocking>,
489) -> Result<SessionSetup<'static, Counterpart, Request::Response>, crate::Error>
490where
491 Counterpart: HasPeer<Agent>,
492 Request: RestoreRequest,
493{
494 let RestoreSessionBuilder {
495 connection,
496 request,
497 block_state: _,
498 } = builder;
499 let session_id = request.session_id().clone();
500 let prepared = connection.prepare_session_routing(&session_id)?;
501 let routing_ready = connection.raw_connection().dynamic_handler_barrier();
502 let session_connection = connection.clone();
503
504 connection
505 .raw_connection()
506 .send_ordered_request_to_after::<Raw, _, _, _>(Agent, request, routing_ready)
507 .block_task_with_ordered_result(move |result| {
508 let response = result?;
509 Ok(restored_session::<_, Request>(
510 session_connection,
511 session_id,
512 prepared,
513 response,
514 ))
515 })
516 .await
517}
518
519impl<Counterpart> RestoreSessionBuilder<Counterpart, LoadSessionRequest>
520where
521 Counterpart: HasPeer<Agent>,
522{
523 /// Restore with `session/load` in the background and run `op` once its
524 /// exact response and active session are available.
525 ///
526 /// This returns immediately and is safe to call from a message handler.
527 /// Replay notifications can arrive before the response and are retained by
528 /// the returned session.
529 pub fn on_session_start<F, Fut>(self, op: F) -> Result<(), crate::Error>
530 where
531 F: FnOnce(SessionSetup<'static, Counterpart, LoadSessionResponse>) -> Fut + Send + 'static,
532 Fut: Future<Output = Result<(), crate::Error>> + Send,
533 {
534 on_restore_session_start(self, op)
535 }
536}
537
538impl<Counterpart> RestoreSessionBuilder<Counterpart, ResumeSessionRequest>
539where
540 Counterpart: HasPeer<Agent>,
541{
542 /// Restore with `session/resume` in the background and run `op` once its
543 /// exact response and active session are available.
544 ///
545 /// This returns immediately and is safe to call from a message handler.
546 /// The returned session receives subsequent session traffic.
547 pub fn on_session_start<F, Fut>(self, op: F) -> Result<(), crate::Error>
548 where
549 F: FnOnce(SessionSetup<'static, Counterpart, ResumeSessionResponse>) -> Fut
550 + Send
551 + 'static,
552 Fut: Future<Output = Result<(), crate::Error>> + Send,
553 {
554 on_restore_session_start(self, op)
555 }
556}
557
558impl<Counterpart> RestoreSessionBuilder<Counterpart, LoadSessionRequest, Blocking>
559where
560 Counterpart: HasPeer<Agent>,
561{
562 /// Publish `session/load`, wait on the current task, and return an
563 /// [`ActiveSession`] together with the exact [`LoadSessionResponse`].
564 ///
565 /// Requires [`block_task`](LoadSessionBuilder::block_task). Dropping
566 /// this future while it is pending cancels the request and removes the
567 /// provisional session route.
568 pub async fn start_session(
569 self,
570 ) -> Result<SessionSetup<'static, Counterpart, LoadSessionResponse>, crate::Error> {
571 start_restored_session(self).await
572 }
573}
574
575impl<Counterpart> RestoreSessionBuilder<Counterpart, ResumeSessionRequest, Blocking>
576where
577 Counterpart: HasPeer<Agent>,
578{
579 /// Publish `session/resume`, wait on the current task, and return an
580 /// [`ActiveSession`] together with the exact [`ResumeSessionResponse`].
581 ///
582 /// Requires [`block_task`](ResumeSessionBuilder::block_task). Dropping
583 /// this future while it is pending cancels the request and removes the
584 /// provisional session route.
585 pub async fn start_session(
586 self,
587 ) -> Result<SessionSetup<'static, Counterpart, ResumeSessionResponse>, crate::Error> {
588 start_restored_session(self).await
589 }
590}
591
592/// A stable protocol v1 session and the response of the request that set it
593/// up.
594///
595/// Every setup method returns one: [`SessionBuilder::start_session`]
596/// (`session/new`), and `start_session` on [`LoadSessionBuilder`]
597/// (`session/load`) and [`ResumeSessionBuilder`] (`session/resume`). The `on_session_start` and
598/// [`run_until`](SessionBuilder::run_until) callbacks receive one too. The
599/// response is the complete, operation-specific setup response; it is kept
600/// next to the session rather than inside [`ActiveSession`], so the setup
601/// response lives in the same place for every setup method. For load and
602/// resume, the session ID comes from the request, because stable v1 restore
603/// responses do not repeat it.
604///
605/// New fields may be added, so destructure with `..`:
606///
607/// ```ignore
608/// let SessionSetup { mut session, response, .. } = builder.start_session().await?;
609/// ```
610#[non_exhaustive]
611pub struct SessionSetup<'runner, Link, Response>
612where
613 Link: HasPeer<Agent>,
614{
615 /// The session, with its update stream.
616 pub session: ActiveSession<'runner, Link>,
617 /// The complete response of the request that set the session up.
618 pub response: Response,
619}
620
621impl<Link, Response> std::fmt::Debug for SessionSetup<'_, Link, Response>
622where
623 Link: HasPeer<Agent>,
624 Response: std::fmt::Debug,
625{
626 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
627 formatter
628 .debug_struct("SessionSetup")
629 .field("session_id", self.session.session_id())
630 .field("response", &self.response)
631 .finish()
632 }
633}
634
635/// Stable protocol v1 session builder for a new session request.
636/// Allows you to add MCP servers or set other details for this session.
637///
638/// The `BlockState` type parameter tracks whether blocking methods are available:
639/// - `NonBlocking` (default): Only [`on_session_start`](Self::on_session_start) is available
640/// - `Blocking` (after calling [`block_task`](Self::block_task)):
641/// [`run_until`](Self::run_until) and [`start_session`](Self::start_session) become available
642#[must_use = "use `start_session`, `run_until`, or `on_session_start` to start the session"]
643#[derive(Debug)]
644pub struct SessionBuilder<
645 Counterpart,
646 Run: RunWithConnectionTo<Counterpart> = NullRun,
647 BlockState: SessionBlockState = NonBlocking,
648> where
649 Counterpart: HasPeer<Agent>,
650{
651 connection: ConnectionTo<Counterpart>,
652 request: NewSessionRequest,
653 dynamic_handler_registrations: Vec<DynamicHandlerGuard<Counterpart>>,
654 run: Run,
655 block_state: PhantomData<BlockState>,
656}
657
658impl<Counterpart> SessionBuilder<Counterpart, NullRun, NonBlocking>
659where
660 Counterpart: HasPeer<Agent>,
661{
662 fn new(connection: &ConnectionTo<Counterpart>, request: NewSessionRequest) -> Self {
663 SessionBuilder {
664 connection: connection.clone(),
665 request,
666 dynamic_handler_registrations: Vec::default(),
667 run: NullRun,
668 block_state: PhantomData,
669 }
670 }
671}
672
673impl<Counterpart, R, BlockState> SessionBuilder<Counterpart, R, BlockState>
674where
675 Counterpart: HasPeer<Agent>,
676 R: RunWithConnectionTo<Counterpart>,
677 BlockState: SessionBlockState,
678{
679 /// Attach an MCP server to this new session.
680 ///
681 /// The declaration is an `acp` transport (`McpServer::Acp`). The agent must
682 /// advertise `agentCapabilities.mcpCapabilities.acp`, or a compatibility
683 /// proxy such as `McpOverAcpPolyfill` must sit in front of it; otherwise a
684 /// conforming agent rejects the setup request with `-32602`. This method
685 /// does not check the agent's capabilities.
686 ///
687 /// # Errors
688 ///
689 /// Returns an error if the connection cannot register the MCP message handler.
690 #[cfg(feature = "unstable_mcp_over_acp")]
691 pub fn with_mcp_server<McpRun>(
692 mut self,
693 mcp_server: McpServer<Counterpart, McpRun>,
694 ) -> Result<SessionBuilder<Counterpart, ChainRun<R, McpRun>, BlockState>, crate::Error>
695 where
696 McpRun: RunWithConnectionTo<Counterpart>,
697 {
698 let (handler, mcp_run) = mcp_server.into_handler_and_runner();
699 self.dynamic_handler_registrations.push(
700 handler.into_dynamic_handler(&mut self.request, self.connection.raw_connection())?,
701 );
702 Ok(SessionBuilder {
703 connection: self.connection,
704 request: self.request,
705 dynamic_handler_registrations: self.dynamic_handler_registrations,
706 run: ChainRun::new(self.run, mcp_run),
707 block_state: self.block_state,
708 })
709 }
710
711 /// Spawn a task that runs the provided closure once the session starts.
712 ///
713 /// Unlike [`start_session`](Self::start_session), this method returns immediately
714 /// without blocking the current task. The session handshake and closure execution
715 /// happen in a spawned background task.
716 ///
717 /// The closure receives a [`SessionSetup`] with an
718 /// `ActiveSession<'static, _>` and the [`NewSessionResponse`], and runs in
719 /// a spawned task. If it returns an error, the error propagates to the
720 /// connection's task handling.
721 ///
722 /// # Example
723 ///
724 /// ```ignore
725 /// # use agent_client_protocol::{Client, Agent, ConnectTo};
726 /// # use agent_client_protocol::mcp_server::McpServer;
727 /// # use agent_client_protocol_rmcp::rmcp_3::McpServerExt;
728 /// # async fn example(transport: impl ConnectTo<Client>) -> Result<(), agent_client_protocol::Error> {
729 /// # Client.v1().connect_with(transport, async |cx| {
730 /// # let mcp = McpServer::<Agent, _>::builder("tools").build();
731 /// cx.build_session_cwd()?
732 /// .with_mcp_server(mcp)?
733 /// .on_session_start(async |SessionSetup { mut session, .. }| {
734 /// // Do something with the session
735 /// session.send_prompt("Hello")?;
736 /// let response = session.read_to_string().await?;
737 /// Ok(())
738 /// })?;
739 /// // Returns immediately, session runs in background
740 /// # Ok(())
741 /// # }).await?;
742 /// # Ok(())
743 /// # }
744 /// ```
745 ///
746 /// # Ordering
747 ///
748 /// Session runners are scheduled and routing setup is installed before the
749 /// dispatch loop processes the next message when the session response is
750 /// routed during its original dispatch. No user callback code runs under
751 /// that ordering guarantee: the callback is invoked in a spawned task, so
752 /// it may wait for later session traffic without deadlocking the connection.
753 /// A response interceptor that retains the response and routes it later
754 /// cannot retroactively order session setup before messages the dispatch
755 /// loop has already processed.
756 ///
757 /// # Errors
758 ///
759 /// Returns an error if the session runner or response callback cannot
760 /// be scheduled. Session setup and callback errors occur in the spawned tasks.
761 pub fn on_session_start<F, Fut>(self, op: F) -> Result<(), crate::Error>
762 where
763 R: 'static,
764 F: FnOnce(SessionSetup<'static, Counterpart, NewSessionResponse>) -> Fut + Send + 'static,
765 Fut: Future<Output = Result<(), crate::Error>> + Send,
766 {
767 let Self {
768 connection,
769 request,
770 dynamic_handler_registrations,
771 run,
772 block_state: _,
773 } = self;
774
775 let cleanup = session_cleanup(&dynamic_handler_registrations);
776 let (runner_connection, error_scope) =
777 session_runner_connection(connection.raw_connection().clone(), &cleanup);
778 connection.spawn(run_attached_session_runner(
779 run.run_with_connection_to(runner_connection),
780 cleanup,
781 error_scope,
782 ))?;
783
784 connection
785 .raw_connection()
786 .send_ordered_request_to::<Raw, _, _>(Agent, request)
787 .on_receiving_result({
788 let connection = connection.clone();
789 async move |result| {
790 let response = result?;
791
792 let setup =
793 connection.attach_session(response, dynamic_handler_registrations)?;
794
795 connection.spawn(async move { op(setup).await })
796 }
797 })
798 }
799
800 /// Spawn a proxy session and run a closure with the `session/new` response.
801 ///
802 /// A **proxy session** starts the session with the agent and then automatically
803 /// proxies all session updates (prompts, tool calls, etc.) from the agent back
804 /// to the client. You don't need to handle any messages yourself - the proxy
805 /// takes care of forwarding everything. This is useful when you want to inject
806 /// and/or filter prompts coming from the client but otherwise not be involved
807 /// in the session.
808 ///
809 /// Unlike [`start_session_proxy`](Self::start_session_proxy), this method returns
810 /// immediately without blocking the current task. The session handshake, client
811 /// response, and proxy setup all happen in a spawned background task.
812 ///
813 /// The closure receives a clone of the complete [`NewSessionResponse`], which was also
814 /// forwarded to the client, once the session is established. Read the session ID from its
815 /// `session_id` field. Use it for logging
816 /// or eventual tracking; it runs concurrently with later connection traffic. Register
817 /// ID-independent state that later handlers must observe before calling this helper. For
818 /// ID-keyed bookkeeping, install a gate or placeholder first, make later handlers await it,
819 /// and populate it from the closure.
820 ///
821 /// # Example
822 ///
823 /// ```ignore
824 /// # use agent_client_protocol::{Proxy, Client, Conductor, ConnectTo};
825 /// # use agent_client_protocol::v1::schema::NewSessionRequest;
826 /// # use agent_client_protocol::mcp_server::McpServer;
827 /// # use agent_client_protocol_rmcp::rmcp_3::McpServerExt;
828 /// # async fn example(transport: impl ConnectTo<Proxy>) -> Result<(), agent_client_protocol::Error> {
829 /// Proxy.v1()
830 /// .on_receive_request_from(Client, async |request: NewSessionRequest, responder, cx| {
831 /// let mcp = McpServer::<Conductor, _>::builder("tools").build();
832 /// cx.build_session_from(request)
833 /// .with_mcp_server(mcp)?
834 /// .on_proxy_session_start(responder, async |response| {
835 /// // Session started
836 /// Ok(())
837 /// })
838 /// }, agent_client_protocol::on_receive_request!())
839 /// .connect_to(transport)
840 /// .await?;
841 /// # Ok(())
842 /// # }
843 /// ```
844 ///
845 /// # Ordering
846 ///
847 /// The client response is queued, proxy routing is installed, and session runners are
848 /// scheduled before the dispatch loop processes the next message when the session response
849 /// is routed during its original dispatch. This is a local ordering guarantee, not a
850 /// guarantee that the response reaches the client before later wire traffic. No user callback
851 /// code runs under the barrier: the callback is invoked in a spawned task, so it may wait for
852 /// later connection traffic. A response interceptor that retains the response and routes it
853 /// later cannot retroactively order this setup before messages the loop already processed.
854 ///
855 /// # Errors
856 ///
857 /// Returns an error if the session runner or response callback cannot be
858 /// scheduled. An error from the downstream request goes to `responder`.
859 pub fn on_proxy_session_start<F, Fut>(
860 self,
861 responder: Responder<NewSessionResponse, crate::V1>,
862 op: F,
863 ) -> Result<(), crate::Error>
864 where
865 F: FnOnce(NewSessionResponse) -> Fut + Send + 'static,
866 Fut: Future<Output = Result<(), crate::Error>> + Send,
867 Counterpart: HasPeer<Client>,
868 R: 'static,
869 {
870 let Self {
871 connection,
872 request,
873 dynamic_handler_registrations,
874 run,
875 block_state: _,
876 } = self;
877
878 let cleanup = session_cleanup(&dynamic_handler_registrations);
879 let (runner_connection, error_scope) =
880 session_runner_connection(connection.raw_connection().clone(), &cleanup);
881 connection.spawn(run_attached_session_runner(
882 run.run_with_connection_to(runner_connection),
883 cleanup,
884 error_scope,
885 ))?;
886
887 // Send the "new session" request to the agent.
888 let sent = connection
889 .prepare_request_to(Agent, request)
890 .forwarded_from(&responder);
891
892 sent.on_receiving_ok_result(responder, {
893 let connection = connection.clone();
894 async move |response, responder| {
895 // Extract the session-id from the response and forward
896 // the response back to the client
897 let session_id = response.session_id.clone();
898 responder.respond(response.clone())?;
899
900 // Install a dynamic handler to proxy messages from this session
901 connection
902 .add_dynamic_handler(ProxySessionMessages::new(session_id))?
903 .detach();
904
905 // Keep dynamic handlers live for the connection.
906 dynamic_handler_registrations
907 .into_iter()
908 .for_each(DynamicHandlerGuard::detach);
909
910 connection.spawn(async move { op(response).await })
911 }
912 })
913 }
914}
915
916impl<Counterpart, R> SessionBuilder<Counterpart, R, NonBlocking>
917where
918 Counterpart: HasPeer<Agent>,
919 R: RunWithConnectionTo<Counterpart>,
920{
921 /// Mark this session builder as being able to block the current task.
922 ///
923 /// After calling this, you can use [`run_until`](Self::run_until) or
924 /// [`start_session`](Self::start_session) which block the current task.
925 ///
926 /// This should not be used from inside a message handler like
927 /// [`Builder::on_receive_request`](`crate::Builder::on_receive_request`) or [`HandleDispatchFrom`]
928 /// implementations.
929 pub fn block_task(self) -> SessionBuilder<Counterpart, R, Blocking> {
930 SessionBuilder {
931 connection: self.connection,
932 request: self.request,
933 dynamic_handler_registrations: self.dynamic_handler_registrations,
934 run: self.run,
935 block_state: PhantomData,
936 }
937 }
938}
939
940impl<Counterpart, R> SessionBuilder<Counterpart, R, Blocking>
941where
942 Counterpart: HasPeer<Agent>,
943 R: RunWithConnectionTo<Counterpart>,
944{
945 /// Run this session synchronously. The current task will be blocked
946 /// and `op` will be executed with the active session information.
947 /// This is useful when you have MCP servers that are borrowed from your local
948 /// stack frame.
949 ///
950 /// The [`SessionSetup`] passed to `op` holds an `ActiveSession` with a
951 /// non-`'static` lifetime, which
952 /// prevents calling [`ActiveSession::proxy_remaining_messages`] (since the
953 /// session's background runners would terminate when `op` returns).
954 ///
955 /// Requires calling [`block_task`](Self::block_task) first.
956 ///
957 /// # Errors
958 ///
959 /// Propagates failures from `session/new`, session handler registration,
960 /// the session runner, or `op`.
961 pub async fn run_until<T>(
962 self,
963 op: impl for<'runner> AsyncFnOnce(
964 SessionSetup<'runner, Counterpart, NewSessionResponse>,
965 ) -> Result<T, crate::Error>,
966 ) -> Result<T, crate::Error> {
967 let Self {
968 connection,
969 request,
970 dynamic_handler_registrations,
971 run,
972 block_state: _,
973 } = self;
974
975 let cleanup = session_cleanup(&dynamic_handler_registrations);
976 let (runner_connection, error_scope) =
977 session_runner_connection(connection.raw_connection().clone(), &cleanup);
978 run_session_scope(
979 run.run_with_connection_to(runner_connection),
980 async move {
981 let response = connection
982 .send_request_to(Agent, request)
983 .block_task()
984 .await?;
985 let setup = connection.attach_session(response, dynamic_handler_registrations)?;
986 op(setup).await
987 },
988 cleanup,
989 error_scope,
990 )
991 .await
992 }
993
994 /// Send the request to create the session and return a handle.
995 /// This is an alternative to [`Self::run_until`] that avoids rightward
996 /// drift but at the cost of requiring MCP servers that are `Send` and
997 /// don't access data from the surrounding scope.
998 ///
999 /// Returns a [`SessionSetup`] with the `ActiveSession<'static, _>` and the
1000 /// complete [`NewSessionResponse`]. The session is `'static` because its
1001 /// runners are spawned into background tasks that live for the connection
1002 /// lifetime.
1003 ///
1004 /// Session routing is installed before later inbound messages are dispatched.
1005 ///
1006 /// Requires calling [`block_task`](Self::block_task) first.
1007 ///
1008 /// # Errors
1009 ///
1010 /// Returns an error if the runner cannot be scheduled, `session/new`
1011 /// fails, or session routing cannot be installed. A peer error leaves the
1012 /// connection running and removes the session's dynamic handlers.
1013 pub async fn start_session(
1014 self,
1015 ) -> Result<SessionSetup<'static, Counterpart, NewSessionResponse>, crate::Error>
1016 where
1017 R: 'static,
1018 {
1019 self.send_session_start(None)?.await
1020 }
1021
1022 fn send_session_start(
1023 self,
1024 origin: Option<&Responder<NewSessionResponse, crate::V1>>,
1025 ) -> Result<
1026 impl Future<
1027 Output = Result<SessionSetup<'static, Counterpart, NewSessionResponse>, crate::Error>,
1028 > + use<Counterpart, R>,
1029 crate::Error,
1030 >
1031 where
1032 R: 'static,
1033 {
1034 let Self {
1035 connection,
1036 request,
1037 dynamic_handler_registrations,
1038 run,
1039 block_state: _,
1040 } = self;
1041
1042 let cleanup = session_cleanup(&dynamic_handler_registrations);
1043 let (runner_connection, error_scope) =
1044 session_runner_connection(connection.raw_connection().clone(), &cleanup);
1045 connection.spawn(run_attached_session_runner(
1046 run.run_with_connection_to(runner_connection),
1047 cleanup,
1048 error_scope,
1049 ))?;
1050
1051 let session_connection = connection.clone();
1052 let prepared = connection.prepare_request_to(Agent, request);
1053 let prepared = match origin {
1054 Some(responder) => prepared.forwarded_from(responder),
1055 None => prepared,
1056 };
1057 Ok(prepared
1058 .into_sent_request(true)
1059 .block_task_with_ordered_result(move |result| {
1060 let response = result?;
1061 session_connection.attach_session(response, dynamic_handler_registrations)
1062 }))
1063 }
1064
1065 /// Start a proxy session that forwards all messages between client and agent.
1066 ///
1067 /// A **proxy session** starts the session with the agent and then automatically
1068 /// proxies all session updates (prompts, tool calls, etc.) from the agent back
1069 /// to the client. You don't need to handle any messages yourself - the proxy
1070 /// takes care of forwarding everything. This is useful when you want to inject
1071 /// and/or filter prompts coming from the client but otherwise not be involved
1072 /// in the session.
1073 ///
1074 /// This is a convenience method that combines [`start_session`](Self::start_session),
1075 /// responding to the client, and [`ActiveSession::proxy_remaining_messages`].
1076 ///
1077 /// For more control (e.g., to send some messages before proxying), use
1078 /// [`start_session`](Self::start_session) instead and call
1079 /// [`proxy_remaining_messages`](ActiveSession::proxy_remaining_messages) manually.
1080 ///
1081 /// Returns a clone of the complete [`NewSessionResponse`] forwarded to the
1082 /// client.
1083 ///
1084 /// Requires calling [`block_task`](Self::block_task) first.
1085 ///
1086 /// # Errors
1087 ///
1088 /// Returns an error if session setup fails, the reply cannot be queued for
1089 /// the client, or [`ActiveSession::proxy_remaining_messages`] fails.
1090 pub async fn start_session_proxy(
1091 self,
1092 responder: Responder<NewSessionResponse, crate::V1>,
1093 ) -> Result<NewSessionResponse, crate::Error>
1094 where
1095 Counterpart: HasPeer<Client>,
1096 R: 'static,
1097 {
1098 let SessionSetup {
1099 session, response, ..
1100 } = self.send_session_start(Some(&responder))?.await?;
1101 responder.respond(response.clone())?;
1102 session.proxy_remaining_messages()?;
1103 Ok(response)
1104 }
1105}
1106
1107/// Stable protocol v1 active session that lets you send prompts and receive updates.
1108///
1109/// The session owns a stream of [`SessionMessage`]s: the requests and
1110/// notifications the agent sends for this session, and the responses to
1111/// prompts sent with [`send_prompt`](Self::send_prompt) or
1112/// [`send_prompt_blocks`](Self::send_prompt_blocks).
1113///
1114/// This handle covers prompting and reading the stream only. It has no
1115/// helpers for `session/cancel`, `session/set_mode`,
1116/// `session/set_config_option`, `session/close` or `session/fork`. Send those
1117/// messages through [`connection`](Self::connection) with
1118/// [`session_id`](Self::session_id), for example
1119/// `session.connection().send_notification_to(Agent, CancelNotification::new(session.session_id().clone()))`.
1120///
1121/// The `'runner` lifetime represents the span during which session support runners
1122/// (such as MCP servers) are active. When created via [`SessionBuilder::start_session`],
1123/// this is `'static` because the runners are spawned into background tasks.
1124/// When created via [`SessionBuilder::run_until`], this is tied to the
1125/// closure scope, preventing [`Self::proxy_remaining_messages`] from being called
1126/// (since the runners would stop when the closure returns).
1127#[derive(Debug)]
1128pub struct ActiveSession<'runner, Link>
1129where
1130 Link: HasPeer<Agent>,
1131{
1132 session_id: SessionId,
1133 update_rx: mpsc::UnboundedReceiver<SessionMessage>,
1134 update_tx: mpsc::UnboundedSender<SessionMessage>,
1135 connection: ConnectionTo<Link>,
1136
1137 /// Registration for the handler that routes session messages to `update_rx`.
1138 /// This is separate from MCP handlers so it can be dropped independently
1139 /// when switching to proxy mode.
1140 session_handler_registration: DynamicHandlerGuard<Link>,
1141
1142 /// Registrations for MCP server handlers.
1143 /// These will be dropped once the active-session struct is dropped
1144 /// which will cause them to be deregistered.
1145 mcp_handler_registrations: Vec<DynamicHandlerGuard<Link>>,
1146
1147 /// Phantom lifetime representing the session-runner lifetime.
1148 _runner: PhantomData<&'runner ()>,
1149}
1150
1151/// An item on a stable protocol v1 session's update stream, returned by
1152/// [`ActiveSession::read_update`].
1153#[non_exhaustive]
1154#[derive(Debug)]
1155// TODO(next major): revisit boxing the public Message payload. It is the common case.
1156#[allow(
1157 clippy::large_enum_variant,
1158 reason = "the size difference depends on target and unified schema features"
1159)]
1160pub enum SessionMessage {
1161 /// A request or notification the agent sent for this session, such as a
1162 /// `session/update` notification or a `session/request_permission`
1163 /// request.
1164 ///
1165 /// Request handles are typed for protocol v1. To match on the message
1166 /// type with [`MatchDispatch`], convert it with
1167 /// [`Dispatch::into_raw`](crate::Dispatch::into_raw) first.
1168 Message(crate::v1::Dispatch),
1169
1170 /// The response to a `session/prompt` request sent with
1171 /// [`ActiveSession::send_prompt`] or
1172 /// [`ActiveSession::send_prompt_blocks`], which ends that prompt turn.
1173 ///
1174 /// An error response from the agent arrives here as `Err`. It does not
1175 /// close the connection or affect other sessions.
1176 PromptResponse(Result<PromptResponse, crate::Error>),
1177}
1178
1179impl<Link> ActiveSession<'_, Link>
1180where
1181 Link: HasPeer<Agent>,
1182{
1183 /// Access the session ID.
1184 pub fn session_id(&self) -> &SessionId {
1185 &self.session_id
1186 }
1187
1188 /// Access the underlying connection context used to communicate with the agent.
1189 pub fn connection(&self) -> &ConnectionTo<Link> {
1190 &self.connection
1191 }
1192
1193 /// Send a text prompt to the agent.
1194 ///
1195 /// Read the agent's output with [`read_update`](Self::read_update) or
1196 /// [`read_to_string`](Self::read_to_string). The `session/prompt`
1197 /// response, or the error the agent answered with, arrives on the same
1198 /// stream as [`SessionMessage::PromptResponse`].
1199 ///
1200 /// # Errors
1201 ///
1202 /// Returns an error if the prompt response handler cannot be scheduled.
1203 /// Request and peer errors arrive on the update stream.
1204 pub fn send_prompt(&mut self, prompt: impl ToString) -> Result<(), crate::Error> {
1205 self.send_prompt_blocks(vec![prompt.to_string().into()])
1206 }
1207
1208 /// Send a prompt made of arbitrary content blocks to the agent.
1209 ///
1210 /// Content other than text and resource links needs the matching
1211 /// `promptCapabilities` entry from the agent's initialize response. Like
1212 /// [`send_prompt`](Self::send_prompt), the
1213 /// response arrives on the update stream as
1214 /// [`SessionMessage::PromptResponse`].
1215 ///
1216 /// # Errors
1217 ///
1218 /// Returns an error if the prompt response handler cannot be scheduled.
1219 /// Request and peer errors arrive on the update stream.
1220 pub fn send_prompt_blocks(&mut self, prompt: Vec<ContentBlock>) -> Result<(), crate::Error> {
1221 let update_tx = self.update_tx.clone();
1222 self.connection
1223 .raw_connection()
1224 .send_ordered_request_to::<Raw, _, _>(
1225 Agent,
1226 PromptRequest::new(self.session_id.clone(), prompt),
1227 )
1228 .on_receiving_result(async move |result| {
1229 // A closed channel means the session was dropped or handed to
1230 // `proxy_remaining_messages`, so nobody reads the response.
1231 drop(update_tx.unbounded_send(SessionMessage::PromptResponse(result)));
1232 Ok(())
1233 })
1234 }
1235
1236 /// Read the next item on the session's update stream: a message the agent
1237 /// sent for this session, or the response to a prompt.
1238 ///
1239 /// # Errors
1240 ///
1241 /// Returns an error if the update stream closes. A prompt failure is a
1242 /// [`SessionMessage::PromptResponse`] item, not a failure to read the stream.
1243 pub async fn read_update(&mut self) -> Result<SessionMessage, crate::Error> {
1244 use futures::StreamExt;
1245 let message =
1246 self.update_rx.next().await.ok_or_else(|| {
1247 crate::util::internal_error("session channel closed unexpectedly")
1248 })?;
1249
1250 Ok(message)
1251 }
1252
1253 /// Read updates until the next prompt response and return the text of the
1254 /// agent's message chunks.
1255 ///
1256 /// Ignores non-text updates. Requests from the agent that reach the
1257 /// session, such as `session/request_permission`, are answered with a
1258 /// method not found error (`-32601`). Use
1259 /// [`read_update`](Self::read_update) instead to answer them yourself.
1260 ///
1261 /// # Errors
1262 ///
1263 /// Propagates a prompt error, a closed update stream, or a failure to
1264 /// decode an update or answer an unmatched request.
1265 pub async fn read_to_string(&mut self) -> Result<String, crate::Error> {
1266 let mut output = String::new();
1267 loop {
1268 let update = self.read_update().await?;
1269 tracing::trace!("read_to_string update");
1270 match update {
1271 SessionMessage::Message(dispatch) => MatchDispatch::new(dispatch.into_raw())
1272 .if_notification(async |notif: SessionNotification| match notif.update {
1273 SessionUpdate::AgentMessageChunk(ContentChunk {
1274 content: ContentBlock::Text(text),
1275 ..
1276 }) => {
1277 output.push_str(&text.text);
1278 Ok(())
1279 }
1280 _ => Ok(()),
1281 })
1282 .await
1283 .otherwise_ignore()?,
1284 SessionMessage::PromptResponse(response) => {
1285 response?;
1286 break;
1287 }
1288 }
1289 }
1290 Ok(output)
1291 }
1292}
1293
1294impl<Link> ActiveSession<'static, Link>
1295where
1296 Link: HasPeer<Agent>,
1297{
1298 /// Proxy all remaining messages for this session between client and agent.
1299 ///
1300 /// Use this when you want to inject MCP servers into a session but don't need
1301 /// to actively interact with it after setup. The session messages will be proxied
1302 /// between client and agent automatically.
1303 ///
1304 /// This consumes the `ActiveSession` since you're giving up active control.
1305 ///
1306 /// This method is only available on `ActiveSession<'static, _>` (from
1307 /// [`SessionBuilder::start_session`]) because it requires the session's runners to outlive
1308 /// the method call.
1309 ///
1310 /// # Message Ordering Guarantees
1311 ///
1312 /// This method ensures proper handoff from active session mode to proxy mode
1313 /// without losing or reordering messages:
1314 ///
1315 /// 1. **Stop the session handler** - Deactivate the handler that routes messages
1316 /// to `update_rx`. After this, no new messages will be queued.
1317 /// 2. **Close the channel** - Drop `update_tx` so we can detect when the channel
1318 /// is fully drained.
1319 /// 3. **Drain queued messages** - Forward any messages that were already queued
1320 /// in `update_rx` to the client, preserving order.
1321 /// 4. **Install proxy handler** - Now that all queued messages are forwarded,
1322 /// install the proxy handler to handle future messages.
1323 /// 5. **Remove the session handler** - Drop its registration.
1324 ///
1325 /// This sequence prevents the race condition where messages could be delivered
1326 /// out of order or lost during the transition. Messages that arrive between
1327 /// steps 1 and 4 wait for the proxy handler. The deactivated handler stays
1328 /// registered until the proxy handler is installed, so a request in that
1329 /// window waits too instead of being rejected.
1330 ///
1331 /// # Errors
1332 ///
1333 /// Returns an error if a queued message cannot be forwarded or the
1334 /// connection cannot register the replacement proxy handler.
1335 pub fn proxy_remaining_messages(self) -> Result<(), crate::Error>
1336 where
1337 Link: HasPeer<Client>,
1338 {
1339 // Destructure self to get ownership of all fields
1340 let ActiveSession {
1341 session_id,
1342 mut update_rx,
1343 update_tx,
1344 connection,
1345 session_handler_registration,
1346 mcp_handler_registrations,
1347 _runner,
1348 } = self;
1349
1350 // Step 1: Deactivate the session handler.
1351 // After this point, no new messages will be added to the channel.
1352 // Its removal is queued only after the proxy handler (step 5): while a
1353 // deactivated handler is registered, the incoming actor parks session
1354 // requests for the replacement instead of rejecting them.
1355 session_handler_registration.deactivate();
1356
1357 // Step 2: Drop the sender side of the channel.
1358 // This allows us to detect when the channel is fully drained
1359 // (recv will return None when empty and sender is dropped).
1360 drop(update_tx);
1361
1362 // Step 3: Drain any messages that were already queued and forward to client.
1363 // These messages arrived before we dropped the handler but haven't been
1364 // consumed yet. We must forward them to maintain message ordering.
1365 while let Ok(message) = update_rx.try_recv() {
1366 match message {
1367 SessionMessage::Message(dispatch) => {
1368 // Forward the message to the client
1369 connection.send_proxied_message_to(Client, dispatch)?;
1370 }
1371 SessionMessage::PromptResponse(_) => {
1372 // Responses to the proxy's own prompts are not forwarded
1373 }
1374 }
1375 }
1376
1377 // Step 4: Install the proxy handler for future messages.
1378 // Now that all queued messages have been forwarded, the proxy handler
1379 // can take over. Any new messages will go directly through the proxy.
1380 connection
1381 .add_dynamic_handler(ProxySessionMessages::new(session_id))?
1382 .detach();
1383
1384 // Step 5: Remove the deactivated session handler.
1385 drop(session_handler_registration);
1386
1387 // Keep MCP server handlers alive for the lifetime of the proxy
1388 for registration in mcp_handler_registrations {
1389 registration.detach();
1390 }
1391
1392 Ok(())
1393 }
1394}
1395
1396struct ActiveSessionHandler {
1397 session_id: SessionId,
1398 update_tx: mpsc::UnboundedSender<SessionMessage>,
1399}
1400
1401impl ActiveSessionHandler {
1402 pub fn new(session_id: SessionId, update_tx: mpsc::UnboundedSender<SessionMessage>) -> Self {
1403 Self {
1404 session_id,
1405 update_tx,
1406 }
1407 }
1408}
1409
1410impl<Counterpart: Role> HandleDispatchFrom<Counterpart> for ActiveSessionHandler
1411where
1412 Counterpart: HasPeer<Agent>,
1413{
1414 async fn handle_dispatch_from(
1415 &mut self,
1416 message: Dispatch,
1417 cx: RawConnectionTo<Counterpart>,
1418 ) -> Result<Handled<Dispatch>, crate::Error> {
1419 // If this is a message for our session, grab it.
1420 tracing::trace!(
1421 method = message.method(),
1422 handler_session_id = ?self.session_id,
1423 "ActiveSessionHandler::handle_dispatch"
1424 );
1425 MatchDispatchFrom::new(message, &cx)
1426 .if_dispatch_from(Agent, async |message| {
1427 if let Some(session_id) = message.get_session_id()? {
1428 tracing::trace!(
1429 message_session_id = ?session_id,
1430 handler_session_id = ?self.session_id,
1431 "ActiveSessionHandler::handle_dispatch"
1432 );
1433 if session_id == self.session_id {
1434 self.update_tx
1435 .unbounded_send(SessionMessage::Message(message.into_protocol()?))
1436 .map_err(crate::util::internal_error)?;
1437 return Ok(Handled::Yes);
1438 }
1439 }
1440
1441 // Otherwise, pass it through.
1442 Ok(Handled::No {
1443 message,
1444 retry: false,
1445 })
1446 })
1447 .await
1448 .done()
1449 }
1450
1451 fn describe_chain(&self) -> impl std::fmt::Debug {
1452 format!("ActiveSessionHandler({})", self.session_id)
1453 }
1454}