agent_client_protocol/session/v2.rs
1use std::{future::Future, path::Path};
2
3use futures::{
4 channel::oneshot,
5 future::{self, Either},
6};
7
8use crate::{
9 Agent, Client, ConnectionTo as RawConnectionTo, DynamicHandlerGuard, JsonRpcRequest,
10 PreparedRequest, Responder, SentRequest, V2,
11 jsonrpc::run::{NullRun, RunWithConnectionTo},
12 role::{HasPeer, acp::ProxySessionMessages},
13 v2::ConnectionTo,
14 v2::schema as v2,
15};
16
17#[cfg(feature = "unstable_mcp_over_acp")]
18use crate::{jsonrpc::run::ChainRun, mcp_server::McpServer};
19
20use super::{
21 SessionCleanup, close_session_registrations, drive_session_cleanup,
22 run_attached_session_runner, session_cleanup, session_runner_connection, wait_session_cleanup,
23};
24
25async fn run_pending_session_setup<Counterpart, Run>(
26 connection: RawConnectionTo<Counterpart>,
27 run: Run,
28 started_tx: oneshot::Sender<Result<(), crate::Error>>,
29 promotion_rx: oneshot::Receiver<()>,
30 cleanup: SessionCleanup,
31) -> Result<(), crate::Error>
32where
33 Counterpart: HasPeer<Agent>,
34 Run: RunWithConnectionTo<Counterpart>,
35{
36 let (connection, error_scope) = session_runner_connection(connection, &cleanup);
37 let mut run = Box::pin(run.run_with_connection_to(connection));
38 let first_poll =
39 future::poll_fn(|cx| std::task::Poll::Ready(std::future::Future::poll(run.as_mut(), cx)))
40 .await;
41 // A composed runner may have observed an immediate error but remain Pending
42 // while its sibling drives owned cleanup. It still failed before publication.
43 if let Some(error) = error_scope.error() {
44 close_session_registrations(&cleanup);
45 if first_poll.is_pending() {
46 drop(drive_session_cleanup(run, cleanup).await);
47 } else {
48 wait_session_cleanup(cleanup).await;
49 }
50 drop(started_tx.send(Err(error)));
51 return Ok(());
52 }
53 let readiness = match &first_poll {
54 std::task::Poll::Ready(result) => result.clone(),
55 std::task::Poll::Pending => Ok(()),
56 };
57 drop(started_tx.send(readiness));
58
59 match first_poll {
60 std::task::Poll::Ready(Ok(())) => {
61 if promotion_rx.await.is_err() {
62 close_session_registrations(&cleanup);
63 wait_session_cleanup(cleanup).await;
64 }
65 Ok(())
66 }
67 // The request has not been published yet, so report an immediate
68 // startup failure through its readiness result without failing the
69 // whole connection.
70 std::task::Poll::Ready(Err(_)) => {
71 close_session_registrations(&cleanup);
72 wait_session_cleanup(cleanup).await;
73 Ok(())
74 }
75 std::task::Poll::Pending => match future::select(run, promotion_rx).await {
76 Either::Left((result, promotion_rx)) => {
77 // A Pending first poll releases session setup for publication.
78 // From that point onward the agent may already be using an
79 // attachment, so runner failures are connection-fatal just as
80 // they are for other connection runners.
81 if result.is_err() || promotion_rx.await.is_err() {
82 close_session_registrations(&cleanup);
83 wait_session_cleanup(cleanup).await;
84 }
85 result
86 }
87 Either::Right((Ok(()), run)) => {
88 run_attached_session_runner(run, cleanup, error_scope).await
89 }
90 Either::Right((Err(_), run)) => {
91 close_session_registrations(&cleanup);
92 run_attached_session_runner(run, cleanup, error_scope).await
93 }
94 },
95 }
96}
97
98fn prepare_session_setup<Counterpart, Request, Run>(
99 connection: ConnectionTo<Counterpart>,
100 request: Request,
101 dynamic_handler_registrations: Vec<DynamicHandlerGuard<Counterpart>>,
102 run: Run,
103) -> PreparedRequest<Request::Response, V2>
104where
105 Counterpart: HasPeer<Agent>,
106 Request: JsonRpcRequest + 'static,
107 Request::Response: 'static,
108 Run: RunWithConnectionTo<Counterpart> + 'static,
109{
110 let raw_connection = connection.raw_connection().clone();
111 if dynamic_handler_registrations.is_empty() {
112 drop(run);
113 connection.prepare_request_to(Agent, request)
114 } else {
115 let handlers_ready = raw_connection.dynamic_handler_barrier();
116 let (runner_started_tx, runner_started_rx) = oneshot::channel();
117 let (promotion_tx, promotion_rx) = oneshot::channel();
118 let cleanup = session_cleanup(&dynamic_handler_registrations);
119 let runner_started = match raw_connection.spawn(run_pending_session_setup(
120 raw_connection.clone(),
121 run,
122 runner_started_tx,
123 promotion_rx,
124 cleanup,
125 )) {
126 Ok(()) => Either::Left(async move {
127 runner_started_rx.await.map_err(|error| {
128 crate::util::internal_error(format!(
129 "session setup runner stopped before its initial poll: {error}"
130 ))
131 })?
132 }),
133 Err(error) => Either::Right(future::ready(Err(error))),
134 };
135 let readiness = async move {
136 future::try_join(handlers_ready, runner_started).await?;
137 Ok(())
138 };
139 let response_hook = move |_response: &Request::Response| {
140 promotion_tx.send(()).map_err(|()| {
141 crate::util::internal_error("session setup runner stopped before setup completed")
142 })?;
143 dynamic_handler_registrations
144 .into_iter()
145 .for_each(DynamicHandlerGuard::detach);
146 Ok(())
147 };
148
149 raw_connection.prepare_request_to_with_response_hook_after(
150 Agent,
151 request,
152 readiness,
153 response_hook,
154 )
155 }
156}
157
158impl<Counterpart> ConnectionTo<Counterpart>
159where
160 Counterpart: HasPeer<Agent>,
161{
162 /// Build a draft protocol v2 `session/new` request.
163 ///
164 /// `cwd` must be an absolute path: ACP requires one, and the SDK sends it
165 /// without checking.
166 pub fn build_session(&self, cwd: impl AsRef<Path>) -> SessionBuilder<Counterpart> {
167 SessionBuilder::new(self, v2::NewSessionRequest::new(cwd.as_ref()))
168 }
169
170 /// Build a draft protocol v2 session using the current working directory.
171 ///
172 /// # Errors
173 ///
174 /// Returns an error if the current directory cannot be determined.
175 pub fn build_session_cwd(&self) -> Result<SessionBuilder<Counterpart>, crate::Error> {
176 let cwd = std::env::current_dir().map_err(|error| {
177 crate::Error::internal_error().data(format!("cannot get current directory: {error}"))
178 })?;
179 Ok(self.build_session(cwd))
180 }
181
182 /// Build a draft protocol v2 session from an existing `session/new` request.
183 pub fn build_session_from(
184 &self,
185 request: v2::NewSessionRequest,
186 ) -> SessionBuilder<Counterpart> {
187 SessionBuilder::new(self, request)
188 }
189
190 /// Build an unstable draft protocol v2 `session/fork` request.
191 ///
192 /// This helper is available with the `unstable_session_fork` feature. Call
193 /// [`ForkSessionBuilder::start_session`] to publish the request and
194 /// obtain a command handle for the newly created fork.
195 ///
196 /// `cwd` must be an absolute path: ACP requires one, and the SDK sends it
197 /// without checking.
198 #[cfg(feature = "unstable_session_fork")]
199 pub fn fork_session(
200 &self,
201 session_id: impl Into<v2::SessionId>,
202 cwd: impl AsRef<Path>,
203 ) -> ForkSessionBuilder<Counterpart> {
204 self.fork_session_from(v2::ForkSessionRequest::new(session_id, cwd.as_ref()))
205 }
206
207 /// Build an unstable draft protocol v2 `session/fork` request from an
208 /// existing request.
209 ///
210 /// This helper is available with the `unstable_session_fork` feature. Call
211 /// [`ForkSessionBuilder::start_session`] to publish the request.
212 #[cfg(feature = "unstable_session_fork")]
213 pub fn fork_session_from(
214 &self,
215 request: v2::ForkSessionRequest,
216 ) -> ForkSessionBuilder<Counterpart> {
217 ForkSessionBuilder::new(self, request)
218 }
219
220 /// Build a draft protocol v2 `session/resume` request.
221 ///
222 /// Use [`Self::resume_session_from`] to request history replay or set
223 /// other optional resume parameters. Call
224 /// [`ResumeSessionBuilder::start_session`] to publish the request.
225 ///
226 /// `cwd` must be an absolute path: ACP requires one, and the SDK sends it
227 /// without checking.
228 pub fn resume_session(
229 &self,
230 session_id: impl Into<v2::SessionId>,
231 cwd: impl AsRef<Path>,
232 ) -> ResumeSessionBuilder<Counterpart> {
233 self.resume_session_from(v2::ResumeSessionRequest::new(session_id, cwd.as_ref()))
234 }
235
236 /// Build a draft protocol v2 `session/resume` request from an existing request.
237 ///
238 /// Register typed session update handlers before connecting. When the
239 /// request asks for replay, the agent sends those updates before the
240 /// [`v2::schema::ResumeSessionResponse`](v2::ResumeSessionResponse), and
241 /// ends the replayed history with a
242 /// [`v2::schema::ReplayComplete`](v2::ReplayComplete) update. Call
243 /// [`ResumeSessionBuilder::start_session`] to publish the request.
244 pub fn resume_session_from(
245 &self,
246 request: v2::ResumeSessionRequest,
247 ) -> ResumeSessionBuilder<Counterpart> {
248 ResumeSessionBuilder::new(self, request)
249 }
250}
251
252/// Builder for a draft protocol v2 `session/new` request.
253///
254/// Protocol v2 acknowledges `session/prompt` independently from inbound
255/// session updates. Register typed [`v2::schema::UpdateSessionNotification`](v2::UpdateSessionNotification) and
256/// session request handlers on [`v2::Builder`](crate::v2::Builder) before connecting, then use
257/// [`Self::start_session`] to create the command-only [`ActiveSession`] handle or
258/// `on_proxy_session_start` to forward setup through a proxy.
259///
260/// With both the `unstable_protocol_v2` and `unstable_mcp_over_acp` features,
261/// `with_mcp_server` attaches an MCP server to the new session.
262#[must_use = "call `start_session` or `on_proxy_session_start` to send the `session/new` request"]
263#[derive(Debug)]
264pub struct SessionBuilder<Counterpart, Run = NullRun>
265where
266 Counterpart: HasPeer<Agent>,
267 Run: RunWithConnectionTo<Counterpart>,
268{
269 connection: ConnectionTo<Counterpart>,
270 request: v2::NewSessionRequest,
271 dynamic_handler_registrations: Vec<DynamicHandlerGuard<Counterpart>>,
272 run: Run,
273}
274
275impl<Counterpart> SessionBuilder<Counterpart, NullRun>
276where
277 Counterpart: HasPeer<Agent>,
278{
279 fn new(connection: &ConnectionTo<Counterpart>, request: v2::NewSessionRequest) -> Self {
280 Self {
281 connection: connection.clone(),
282 request,
283 dynamic_handler_registrations: Vec::new(),
284 run: NullRun,
285 }
286 }
287}
288
289impl<Counterpart, Run> SessionBuilder<Counterpart, Run>
290where
291 Counterpart: HasPeer<Agent>,
292 Run: RunWithConnectionTo<Counterpart>,
293{
294 /// Attach an MCP server to this new protocol v2 session.
295 ///
296 /// This method is available when both `unstable_protocol_v2` and
297 /// `unstable_mcp_over_acp` are enabled. MCP routes are installed and their
298 /// runner tasks receive an initial poll before `session/new` is published,
299 /// allowing the agent to connect while handling session setup. A
300 /// successful attachment remains active for the lifetime of the connection.
301 ///
302 /// The declaration is an `acp` transport (`McpServer::Acp`). The agent must
303 /// advertise `session.mcp.acp`, or a compatibility proxy such as
304 /// `McpOverAcpPolyfill` must sit in front of it; otherwise a conforming
305 /// agent rejects the setup request with `-32602`. This method does not
306 /// check the agent's capabilities.
307 ///
308 /// # Errors
309 ///
310 /// Returns Invalid params (`-32602`) if the request already declares that
311 /// server name, or a registration error if the connection no longer accepts handlers.
312 #[cfg(feature = "unstable_mcp_over_acp")]
313 pub fn with_mcp_server<McpRun>(
314 mut self,
315 mcp_server: McpServer<Counterpart, McpRun>,
316 ) -> Result<SessionBuilder<Counterpart, ChainRun<Run, McpRun>>, crate::Error>
317 where
318 McpRun: RunWithConnectionTo<Counterpart>,
319 {
320 let (handler, mcp_run) = mcp_server.into_v2_handler_and_runner();
321 self.dynamic_handler_registrations
322 .push(handler.into_dynamic_handler(&mut self.request.mcp_servers, &self.connection)?);
323 Ok(SessionBuilder {
324 connection: self.connection,
325 request: self.request,
326 dynamic_handler_registrations: self.dynamic_handler_registrations,
327 run: ChainRun::new(self.run, mcp_run),
328 })
329 }
330
331 fn prepare_new_session(self) -> PreparedRequest<v2::NewSessionResponse, V2>
332 where
333 Run: 'static,
334 {
335 let Self {
336 connection,
337 request,
338 dynamic_handler_registrations,
339 run,
340 } = self;
341 prepare_session_setup(connection, request, dynamic_handler_registrations, run)
342 }
343
344 /// Send `session/new` and return its independently consumable request.
345 ///
346 /// The successful result contains both a cloneable command handle and the
347 /// complete [`v2::schema::NewSessionResponse`](v2::NewSessionResponse). Consume the returned request with
348 /// [`SentRequest::block_task`], [`SentRequest::on_receiving_result`], or
349 /// another explicit [`SentRequest`] completion mode.
350 ///
351 /// Attached MCP routes are installed and their runner tasks begin
352 /// executing before the request is published. A valid success response
353 /// promotes them to the connection lifetime, independently from how this
354 /// request handle is consumed. Setup errors clean up the pending
355 /// attachment.
356 pub fn start_session(self) -> SentRequest<SessionSetup<Counterpart, v2::NewSessionResponse>, V2>
357 where
358 Run: 'static,
359 {
360 let session_connection = self.connection.clone();
361 self.prepare_new_session()
362 .into_sent_request(false)
363 .map(move |response| {
364 let session = ActiveSession {
365 session_id: response.session_id.clone(),
366 connection: session_connection,
367 };
368 Ok(SessionSetup { session, response })
369 })
370 }
371
372 /// Start a protocol v2 session through a proxy and forward its response.
373 ///
374 /// The downstream request is ordered and inherits cancellation from the
375 /// upstream request. On success, this helper installs session routing before
376 /// later inbound traffic is processed, forwards the complete response, and
377 /// spawns `op` with an [`SessionSetup`] containing the command-only
378 /// session handle plus the complete setup response. Inbound updates and
379 /// interactive requests remain independent connection traffic.
380 ///
381 /// The callback runs outside the ordered response barrier, so it may wait
382 /// for later connection traffic without deadlocking the dispatch loop.
383 ///
384 /// # Errors
385 ///
386 /// Returns an error if the response handler cannot be scheduled.
387 /// A downstream setup error is forwarded to `responder`.
388 pub fn on_proxy_session_start<F, Fut>(
389 self,
390 responder: Responder<v2::NewSessionResponse, V2>,
391 op: F,
392 ) -> Result<(), crate::Error>
393 where
394 Counterpart: HasPeer<Client>,
395 Run: 'static,
396 F: FnOnce(SessionSetup<Counterpart, v2::NewSessionResponse>) -> Fut + Send + 'static,
397 Fut: Future<Output = Result<(), crate::Error>> + Send,
398 {
399 let session_connection = self.connection.clone();
400 self.prepare_new_session()
401 .forwarded_from(&responder)
402 .on_receiving_ok_result(responder, async move |response, responder| {
403 let session_id = response.session_id.clone();
404 let raw_connection = session_connection.raw_connection();
405 let route = match raw_connection.add_dynamic_handler(ProxySessionMessages::new(
406 crate::v1::schema::SessionId::from(session_id.0.clone()),
407 )) {
408 Ok(route) => route,
409 Err(error) => return responder.respond_with_error(error),
410 };
411
412 let setup = SessionSetup {
413 session: ActiveSession {
414 session_id,
415 connection: session_connection.clone(),
416 },
417 response: response.clone(),
418 };
419 responder.respond(response)?;
420 route.detach();
421 raw_connection.spawn(async move { op(setup).await })
422 })
423 }
424}
425
426/// Builder for an unstable draft protocol v2 `session/fork` request.
427///
428/// A successful fork creates a new independent session whose ID comes from the
429/// [`v2::schema::ForkSessionResponse`](v2::ForkSessionResponse). Register typed
430/// [`v2::schema::UpdateSessionNotification`](v2::UpdateSessionNotification) and interactive request handlers on
431/// [`v2::Builder`](crate::v2::Builder) before connecting, then use [`Self::start_session`] to
432/// obtain a command handle for the fork or `on_proxy_session_start` to forward
433/// setup through a proxy.
434///
435/// This type is available with the `unstable_session_fork` feature. With
436/// `unstable_mcp_over_acp` as well, `with_mcp_server` attaches an MCP server to
437/// the forked session.
438#[cfg(feature = "unstable_session_fork")]
439#[must_use = "call `start_session` or `on_proxy_session_start` to send the `session/fork` request"]
440#[derive(Debug)]
441pub struct ForkSessionBuilder<Counterpart, Run = NullRun>
442where
443 Counterpart: HasPeer<Agent>,
444 Run: RunWithConnectionTo<Counterpart>,
445{
446 connection: ConnectionTo<Counterpart>,
447 request: v2::ForkSessionRequest,
448 dynamic_handler_registrations: Vec<DynamicHandlerGuard<Counterpart>>,
449 run: Run,
450}
451
452#[cfg(feature = "unstable_session_fork")]
453impl<Counterpart> ForkSessionBuilder<Counterpart, NullRun>
454where
455 Counterpart: HasPeer<Agent>,
456{
457 fn new(connection: &ConnectionTo<Counterpart>, request: v2::ForkSessionRequest) -> Self {
458 Self {
459 connection: connection.clone(),
460 request,
461 dynamic_handler_registrations: Vec::new(),
462 run: NullRun,
463 }
464 }
465}
466
467#[cfg(feature = "unstable_session_fork")]
468impl<Counterpart, Run> ForkSessionBuilder<Counterpart, Run>
469where
470 Counterpart: HasPeer<Agent>,
471 Run: RunWithConnectionTo<Counterpart>,
472{
473 /// Attach an MCP server to this forked protocol v2 session.
474 ///
475 /// This method is available when `unstable_mcp_over_acp` is enabled in
476 /// addition to `unstable_protocol_v2` and `unstable_session_fork`. MCP
477 /// routes are installed and their runner tasks receive an initial poll
478 /// before `session/fork` is published, allowing the agent to connect while
479 /// handling session setup. A successful attachment remains active for the
480 /// lifetime of the connection.
481 ///
482 /// The declaration is an `acp` transport (`McpServer::Acp`). The agent must
483 /// advertise `session.mcp.acp`, or a compatibility proxy such as
484 /// `McpOverAcpPolyfill` must sit in front of it; otherwise a conforming
485 /// agent rejects the setup request with `-32602`. This method does not
486 /// check the agent's capabilities.
487 ///
488 /// # Errors
489 ///
490 /// Returns Invalid params (`-32602`) for a duplicate server name, or an
491 /// error if the connection cannot register the MCP handler.
492 #[cfg(feature = "unstable_mcp_over_acp")]
493 pub fn with_mcp_server<McpRun>(
494 mut self,
495 mcp_server: McpServer<Counterpart, McpRun>,
496 ) -> Result<ForkSessionBuilder<Counterpart, ChainRun<Run, McpRun>>, crate::Error>
497 where
498 McpRun: RunWithConnectionTo<Counterpart>,
499 {
500 let (handler, mcp_run) = mcp_server.into_v2_handler_and_runner();
501 self.dynamic_handler_registrations
502 .push(handler.into_dynamic_handler(&mut self.request.mcp_servers, &self.connection)?);
503 Ok(ForkSessionBuilder {
504 connection: self.connection,
505 request: self.request,
506 dynamic_handler_registrations: self.dynamic_handler_registrations,
507 run: ChainRun::new(self.run, mcp_run),
508 })
509 }
510
511 fn prepare_fork_session(self) -> PreparedRequest<v2::ForkSessionResponse, V2>
512 where
513 Run: 'static,
514 {
515 let Self {
516 connection,
517 request,
518 dynamic_handler_registrations,
519 run,
520 } = self;
521 prepare_session_setup(connection, request, dynamic_handler_registrations, run)
522 }
523
524 /// Send `session/fork` and return its independently consumable request.
525 ///
526 /// The successful result contains both a cloneable command handle for the
527 /// newly created fork and the complete [`v2::schema::ForkSessionResponse`](v2::ForkSessionResponse). Consume
528 /// the returned request with [`SentRequest::block_task`],
529 /// [`SentRequest::on_receiving_result`], or another explicit [`SentRequest`]
530 /// completion mode.
531 ///
532 /// Attached MCP routes are installed and their runner tasks begin
533 /// executing before the request is published. A valid success response
534 /// promotes them to the connection lifetime independently from how this
535 /// request handle is consumed; setup errors clean up the pending
536 /// attachment.
537 pub fn start_session(
538 self,
539 ) -> SentRequest<SessionSetup<Counterpart, v2::ForkSessionResponse>, V2>
540 where
541 Run: 'static,
542 {
543 let session_connection = self.connection.clone();
544 self.prepare_fork_session()
545 .into_sent_request(false)
546 .map(move |response| {
547 let session = ActiveSession {
548 session_id: response.session_id.clone(),
549 connection: session_connection,
550 };
551 Ok(SessionSetup { session, response })
552 })
553 }
554
555 /// Fork a protocol v2 session through a proxy and forward its response.
556 ///
557 /// The downstream request is ordered and inherits cancellation from the
558 /// upstream request. On success, this helper obtains the new session ID
559 /// from the response, installs session routing before later inbound traffic
560 /// is processed, forwards the complete response, and spawns `op` with an
561 /// [`SessionSetup`] containing the fork's command handle and response.
562 /// Inbound updates and interactive requests remain independent connection
563 /// traffic.
564 ///
565 /// The callback runs outside the ordered response barrier, so it may wait
566 /// for later connection traffic without deadlocking the dispatch loop.
567 ///
568 /// # Errors
569 ///
570 /// Returns an error if the response handler cannot be scheduled.
571 /// A downstream fork error is forwarded to `responder`.
572 pub fn on_proxy_session_start<F, Fut>(
573 self,
574 responder: Responder<v2::ForkSessionResponse, V2>,
575 op: F,
576 ) -> Result<(), crate::Error>
577 where
578 Counterpart: HasPeer<Client>,
579 Run: 'static,
580 F: FnOnce(SessionSetup<Counterpart, v2::ForkSessionResponse>) -> Fut + Send + 'static,
581 Fut: Future<Output = Result<(), crate::Error>> + Send,
582 {
583 let session_connection = self.connection.clone();
584 self.prepare_fork_session()
585 .forwarded_from(&responder)
586 .on_receiving_ok_result(responder, async move |response, responder| {
587 let session_id = response.session_id.clone();
588 let raw_connection = session_connection.raw_connection();
589 let route = match raw_connection.add_dynamic_handler(ProxySessionMessages::new(
590 crate::v1::schema::SessionId::from(session_id.0.clone()),
591 )) {
592 Ok(route) => route,
593 Err(error) => return responder.respond_with_error(error),
594 };
595
596 let setup = SessionSetup {
597 session: ActiveSession {
598 session_id,
599 connection: session_connection.clone(),
600 },
601 response: response.clone(),
602 };
603 responder.respond(response)?;
604 route.detach();
605 raw_connection.spawn(async move { op(setup).await })
606 })
607 }
608}
609
610/// Builder for a draft protocol v2 `session/resume` request.
611///
612/// Replay updates arrive before the resume response. Direct clients must
613/// register typed [`v2::schema::UpdateSessionNotification`](v2::UpdateSessionNotification) and interactive request
614/// handlers on [`v2::Builder`](crate::v2::Builder) before connecting. Proxies should use
615/// [`Self::on_proxy_session_start`], which makes downstream session routing
616/// ready before publishing the resume request.
617///
618/// With both the `unstable_protocol_v2` and `unstable_mcp_over_acp` features,
619/// `with_mcp_server` attaches an MCP server to the resumed session and makes it
620/// ready before the agent can send replay or its response.
621#[must_use = "call `start_session` or `on_proxy_session_start` to send the `session/resume` request"]
622#[derive(Debug)]
623pub struct ResumeSessionBuilder<Counterpart, Run = NullRun>
624where
625 Counterpart: HasPeer<Agent>,
626 Run: RunWithConnectionTo<Counterpart>,
627{
628 connection: ConnectionTo<Counterpart>,
629 request: v2::ResumeSessionRequest,
630 dynamic_handler_registrations: Vec<DynamicHandlerGuard<Counterpart>>,
631 run: Run,
632}
633
634impl<Counterpart> ResumeSessionBuilder<Counterpart, NullRun>
635where
636 Counterpart: HasPeer<Agent>,
637{
638 fn new(connection: &ConnectionTo<Counterpart>, request: v2::ResumeSessionRequest) -> Self {
639 Self {
640 connection: connection.clone(),
641 request,
642 dynamic_handler_registrations: Vec::new(),
643 run: NullRun,
644 }
645 }
646}
647
648impl<Counterpart, Run> ResumeSessionBuilder<Counterpart, Run>
649where
650 Counterpart: HasPeer<Agent>,
651 Run: RunWithConnectionTo<Counterpart>,
652{
653 /// Attach an MCP server to this resumed protocol v2 session.
654 ///
655 /// This method is available when both `unstable_protocol_v2` and
656 /// `unstable_mcp_over_acp` are enabled. MCP routes are installed and their
657 /// runner tasks receive an initial poll before `session/resume` is
658 /// published, allowing the agent to use the server during replay and
659 /// session setup. A successful attachment remains active for the lifetime
660 /// of the connection.
661 ///
662 /// The declaration is an `acp` transport (`McpServer::Acp`). The agent must
663 /// advertise `session.mcp.acp`, or a compatibility proxy such as
664 /// `McpOverAcpPolyfill` must sit in front of it; otherwise a conforming
665 /// agent rejects the setup request with `-32602`. This method does not
666 /// check the agent's capabilities.
667 ///
668 /// # Errors
669 ///
670 /// Returns Invalid params (`-32602`) for a duplicate server name, or an
671 /// error if the connection cannot register the MCP handler.
672 #[cfg(feature = "unstable_mcp_over_acp")]
673 pub fn with_mcp_server<McpRun>(
674 mut self,
675 mcp_server: McpServer<Counterpart, McpRun>,
676 ) -> Result<ResumeSessionBuilder<Counterpart, ChainRun<Run, McpRun>>, crate::Error>
677 where
678 McpRun: RunWithConnectionTo<Counterpart>,
679 {
680 let (handler, mcp_run) = mcp_server.into_v2_handler_and_runner();
681 self.dynamic_handler_registrations
682 .push(handler.into_dynamic_handler(&mut self.request.mcp_servers, &self.connection)?);
683 Ok(ResumeSessionBuilder {
684 connection: self.connection,
685 request: self.request,
686 dynamic_handler_registrations: self.dynamic_handler_registrations,
687 run: ChainRun::new(self.run, mcp_run),
688 })
689 }
690
691 fn prepare_resume_session(self) -> PreparedRequest<v2::ResumeSessionResponse, V2>
692 where
693 Run: 'static,
694 {
695 let Self {
696 connection,
697 request,
698 dynamic_handler_registrations,
699 run,
700 } = self;
701 prepare_session_setup(connection, request, dynamic_handler_registrations, run)
702 }
703
704 /// Send `session/resume` and return its independently consumable request.
705 ///
706 /// The successful result contains both a cloneable command handle and the
707 /// complete [`v2::schema::ResumeSessionResponse`](v2::ResumeSessionResponse). Consume the returned request
708 /// with [`SentRequest::block_task`], [`SentRequest::on_receiving_result`],
709 /// or another explicit [`SentRequest`] completion mode.
710 ///
711 /// Replay is delivered through the typed connection handlers before the
712 /// response. Attached MCP routes and runner tasks are ready before the
713 /// request is published. A valid success response promotes them to the
714 /// connection lifetime independently from how this request handle is
715 /// consumed; setup errors clean up the pending attachment.
716 pub fn start_session(
717 self,
718 ) -> SentRequest<SessionSetup<Counterpart, v2::ResumeSessionResponse>, V2>
719 where
720 Run: 'static,
721 {
722 let session_id = self.request.session_id.clone();
723 let session_connection = self.connection.clone();
724 self.prepare_resume_session()
725 .into_sent_request(false)
726 .map(move |response| {
727 let session = ActiveSession {
728 session_id,
729 connection: session_connection,
730 };
731 Ok(SessionSetup { session, response })
732 })
733 }
734
735 /// Resume a protocol v2 session through a proxy and forward its response.
736 ///
737 /// The session ID is known before the request, so this helper installs and
738 /// acknowledges downstream session routing before publishing the ordered
739 /// `session/resume` request. Replay can therefore be forwarded before the
740 /// response as required by the protocol. The downstream request inherits
741 /// cancellation from the upstream request.
742 ///
743 /// On success, the helper forwards the complete response and spawns `op`
744 /// with an [`SessionSetup`] containing the command-only session handle
745 /// plus that response. The callback runs outside the ordered response
746 /// barrier, so it may wait for later connection traffic without
747 /// deadlocking the dispatch loop.
748 ///
749 /// # Errors
750 ///
751 /// Returns an error if replay routing cannot be registered or the response
752 /// handler cannot be scheduled. A downstream resume error goes to `responder`.
753 pub fn on_proxy_session_start<F, Fut>(
754 mut self,
755 responder: Responder<v2::ResumeSessionResponse, V2>,
756 op: F,
757 ) -> Result<(), crate::Error>
758 where
759 Counterpart: HasPeer<Client>,
760 Run: 'static,
761 F: FnOnce(SessionSetup<Counterpart, v2::ResumeSessionResponse>) -> Fut + Send + 'static,
762 Fut: Future<Output = Result<(), crate::Error>> + Send,
763 {
764 let session_id = self.request.session_id.clone();
765 let session_connection = self.connection.clone();
766 self.dynamic_handler_registrations.push(
767 session_connection
768 .raw_connection()
769 .add_dynamic_handler(ProxySessionMessages::new(
770 crate::v1::schema::SessionId::from(session_id.0.clone()),
771 ))?,
772 );
773
774 self.prepare_resume_session()
775 .forwarded_from(&responder)
776 .on_receiving_ok_result(responder, async move |response, responder| {
777 let setup = SessionSetup {
778 session: ActiveSession {
779 session_id,
780 connection: session_connection.clone(),
781 },
782 response: response.clone(),
783 };
784 responder.respond(response)?;
785 session_connection
786 .raw_connection()
787 .spawn(async move { op(setup).await })
788 })
789 }
790}
791
792/// A protocol v2 session and the response of the request that set it up.
793///
794/// Every setup method returns one: [`SessionBuilder::start_session`]
795/// (`session/new`), [`ResumeSessionBuilder::start_session`]
796/// (`session/resume`) and, with `unstable_session_fork`,
797/// `ForkSessionBuilder::start_session` (`session/fork`), and their
798/// `on_proxy_session_start` callbacks receive one too. The response is the
799/// complete, operation-specific setup response; it is kept next to the
800/// session rather than inside [`ActiveSession`], so the setup response lives
801/// in the same place for every setup method.
802///
803/// New fields may be added, so destructure with `..`:
804///
805/// ```ignore
806/// let SessionSetup { session, response, .. } = setup;
807/// ```
808#[non_exhaustive]
809#[derive(Debug)]
810pub struct SessionSetup<Link, Response>
811where
812 Link: HasPeer<Agent>,
813{
814 /// The command handle for the session.
815 pub session: ActiveSession<Link>,
816 /// The complete response of the request that set the session up.
817 pub response: Response,
818}
819
820/// Cloneable command handle for a draft protocol v2 session.
821///
822/// Inbound protocol traffic is intentionally not owned by this value. Receive
823/// authoritative [`v2::schema::UpdateSessionNotification`](v2::UpdateSessionNotification) values and interactive
824/// requests such as [`v2::schema::RequestPermissionRequest`](v2::RequestPermissionRequest) through typed handlers
825/// installed on [`v2::Builder`](crate::v2::Builder).
826#[derive(Debug, Clone)]
827pub struct ActiveSession<Link>
828where
829 Link: HasPeer<Agent>,
830{
831 session_id: v2::SessionId,
832 connection: ConnectionTo<Link>,
833}
834
835impl<Link> ActiveSession<Link>
836where
837 Link: HasPeer<Agent>,
838{
839 /// Access the session ID.
840 pub fn session_id(&self) -> &v2::SessionId {
841 &self.session_id
842 }
843
844 /// Access the underlying connection.
845 pub fn connection(&self) -> &ConnectionTo<Link> {
846 &self.connection
847 }
848
849 /// Submit a text prompt and return its independent acceptance request.
850 ///
851 /// A successful response only acknowledges that the agent accepted the
852 /// prompt. The accepted user message, output, state changes, and completion
853 /// arrive independently through [`v2::schema::UpdateSessionNotification`](v2::UpdateSessionNotification).
854 ///
855 /// The agent owns the inserted user message. Match it to this submission
856 /// by the response's `message_id`, never by content or arrival order: the
857 /// `content` the agent reports for it can differ from `prompt`.
858 pub fn send_prompt(&self, prompt: impl ToString) -> SentRequest<v2::PromptResponse, V2> {
859 self.send_prompt_blocks(vec![prompt.to_string().into()])
860 }
861
862 /// Submit arbitrary prompt content and return its acceptance request.
863 ///
864 /// `prompt` must not be empty; an agent may reject `[]` with `-32602`.
865 ///
866 /// The SDK does not track foreground state or gate prompt submission
867 /// locally. A prompt may be sent in any state, including while foreground
868 /// work is active: the agent either inserts it right away or holds it and
869 /// inserts held prompts in received order, and it must not reject a prompt
870 /// only because work is active. A held prompt's response stays pending
871 /// until it is inserted.
872 ///
873 /// [`Self::cancel_active_work`] and [`Self::close`] drop the prompts the
874 /// agent has received and not inserted, and the agent answers each with
875 /// `-32800`.
876 /// Cancelling the returned [`SentRequest`] sends `$/cancel_request`, which
877 /// is best effort: an agent that honors it answers `-32800` and does not
878 /// insert the message, and otherwise the prompt is inserted as usual and
879 /// the response carries its `messageId`. An inserted prompt cannot be
880 /// withdrawn. Stop the work it started with [`Self::cancel_active_work`].
881 ///
882 /// A prompt sent this way has no idempotency key, so sending it again
883 /// after a lost response can insert a second user message. Use
884 /// [`Self::send_prompt_blocks_with_key`] for a prompt you may need to
885 /// retry.
886 pub fn send_prompt_blocks(
887 &self,
888 prompt: Vec<v2::ContentBlock>,
889 ) -> SentRequest<v2::PromptResponse, V2> {
890 self.connection.send_request_to(
891 Agent,
892 v2::PromptRequest::new(self.session_id.clone(), prompt),
893 )
894 }
895
896 /// Submit prompt content with an idempotency key and return its
897 /// acceptance request.
898 ///
899 /// The key identifies one submission. While the agent recognizes the key,
900 /// it inserts at most one user message for it in a session and answers a
901 /// retry with the `messageId` of the message it already inserted, without
902 /// starting the work again. To retry, call this again with the same key
903 /// and the same `prompt`. Each attempt is its own request.
904 ///
905 /// A retry is not always safe. On a new connection, resume the session
906 /// before you retry. A successful `session/resume` does not tell you
907 /// whether the prompt was inserted or whether the agent kept the key, and
908 /// a retry with a forgotten key is a new submission. If a duplicate would
909 /// matter and you cannot rule one out, do not resend the prompt
910 /// automatically. Tell the user that it might already have run and let
911 /// them decide.
912 ///
913 /// Create the key when the user submits the input, with
914 /// [`v2::schema::IdempotencyKey::generate`](v2::IdempotencyKey::generate)
915 /// or another random value, and store it with the pending input. Use a
916 /// new key for a new submission, including when the user sends the same
917 /// text again on purpose. Do not derive the key from the content, and do
918 /// not send the same key with a different prompt.
919 ///
920 /// An error response means the message was not inserted and leaves the
921 /// key unused, so the same prompt can be sent again with the same key.
922 /// The agent recognizes a key for as long as it retains the message. For
923 /// a message it does not retain, it recognizes the key while the session
924 /// stays active on a connection.
925 ///
926 /// See <https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#retrying-a-prompt>.
927 pub fn send_prompt_blocks_with_key(
928 &self,
929 prompt: Vec<v2::ContentBlock>,
930 idempotency_key: v2::IdempotencyKey,
931 ) -> SentRequest<v2::PromptResponse, V2> {
932 self.connection.send_request_to(
933 Agent,
934 v2::PromptRequest::new(self.session_id.clone(), prompt)
935 .idempotency_key(idempotency_key),
936 )
937 }
938
939 /// Ask the agent to cancel the session's current foreground work.
940 ///
941 /// This is independent from cancelling a prompt's [`SentRequest`].
942 /// `session/cancel` covers the session's foreground work and prompts
943 /// received before it that the agent has not yet inserted; those prompt
944 /// requests fail with `-32800` (request cancelled). A prompt sent after
945 /// this notification is not cancelled by it. A prompt whose user message was already
946 /// inserted still succeeds with its `messageId`. Work in the latest
947 /// `background` list is not covered and keeps running.
948 ///
949 /// If foreground work was active, cancellation completes when the agent
950 /// reports an `idle` state update with [`v2::schema::StopReason::Cancelled`](v2::StopReason::Cancelled); no
951 /// idle update is required when nothing was running. The agent sends that
952 /// update before it starts new foreground work in the session, and it does
953 /// not reject a prompt because cancellation is in progress. `cancelled` is
954 /// only reported for work the client cancelled, through this notification
955 /// or by closing the session, and for a child session whose parent
956 /// cancelled its work. The client should immediately mark unfinished tool
957 /// calls for the active work as cancelled.
958 ///
959 /// Keep accepting updates after sending this notification. Updates for
960 /// listed background work can arrive after the `idle` update. To stop a
961 /// listed tool call or terminal, send `tool_call/cancel` or
962 /// `terminal/cancel` while the item advertises `capabilities.cancel`.
963 ///
964 /// The agent stops waiting for pending
965 /// [`v2::schema::RequestPermissionRequest`](v2::RequestPermissionRequest)s
966 /// of the cancelled work and must cancel each of them with
967 /// `$/cancel_request`. The agent decides which requests belong to that
968 /// work, so do not answer every pending permission request when you send
969 /// this notification. When `$/cancel_request` arrives for a permission
970 /// request you have not answered, dismiss the prompt and answer with the
971 /// `cancelled` outcome. A client may also answer a request it knows belongs
972 /// to the cancelled work that way without waiting for `$/cancel_request`.
973 ///
974 /// See <https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#cancellation>.
975 ///
976 /// # Errors
977 ///
978 /// Returns an error if the cancellation notification cannot be encoded or
979 /// queued. Success does not mean the agent has finished cancelling.
980 pub fn cancel_active_work(&self) -> Result<(), crate::Error> {
981 self.connection.send_notification_to(
982 Agent,
983 v2::CancelSessionNotification::new(self.session_id.clone()),
984 )
985 }
986
987 /// Set a session configuration option.
988 ///
989 /// Only send a `config_id` the agent advertised for this session, with a
990 /// value from that option. The agent rejects an unknown `config_id` or an
991 /// invalid value with `-32602` and leaves the configuration unchanged.
992 /// The options of a child session are read-only, so do not call this for
993 /// one.
994 ///
995 /// The response contains the complete option set as of the response and
996 /// may report a different `currentValue` than requested; `currentValue`
997 /// is always the value the agent is using. Apply responses and
998 /// `config_option_update` notifications in the order received, each
999 /// replacing the whole list. A duplicate `config_option_update`
1000 /// notification for the same change may arrive before the response. The
1001 /// response is not cached on this command handle.
1002 ///
1003 /// See <https://agentclientprotocol.com/protocol/v2/session-config-options>.
1004 pub fn set_config_option(
1005 &self,
1006 config_id: impl Into<v2::SessionConfigId>,
1007 value: impl Into<v2::SessionConfigOptionValue>,
1008 ) -> SentRequest<v2::SetSessionConfigOptionResponse, V2> {
1009 self.connection.send_request_to(
1010 Agent,
1011 v2::SetSessionConfigOptionRequest::new(self.session_id.clone(), config_id, value),
1012 )
1013 }
1014
1015 /// Close the remote session and release its resources.
1016 ///
1017 /// The agent cancels the session's ongoing work as if `session/cancel` had
1018 /// been sent. When that cancels active foreground work, the agent sends the
1019 /// work's final updates and an `idle` state update with stop reason
1020 /// `cancelled` before it responds to `session/close`. A pending prompt
1021 /// whose user message closing kept from being inserted fails with `-32800`
1022 /// (request cancelled); one already inserted still succeeds with its
1023 /// message ID. Prompt responses need not precede the close response.
1024 /// Before it responds, the agent cancels every pending permission request
1025 /// and elicitation in the session with `$/cancel_request`.
1026 ///
1027 /// Existing clones of this local command handle are not invalidated, but
1028 /// the session is no longer active: the agent rejects later commands for it
1029 /// with `-32002` (resource not found). After the close response the agent
1030 /// sends no notifications or requests for the session. It still answers
1031 /// `session/prompt` requests that were pending.
1032 ///
1033 /// A child session cannot be closed on its own. Close its root session
1034 /// instead.
1035 ///
1036 /// Closing is idempotent. An agent should answer a close of an unknown or
1037 /// already-closed session with success, and an older agent may answer
1038 /// `-32002` instead, so this helper resolves a `-32002` response as a
1039 /// successful, empty [`v2::schema::CloseSessionResponse`](v2::CloseSessionResponse). Other errors are
1040 /// returned unchanged.
1041 ///
1042 /// See <https://agentclientprotocol.com/protocol/v2/session-setup#closing-active-sessions>.
1043 pub fn close(&self) -> SentRequest<v2::CloseSessionResponse, V2> {
1044 self.connection
1045 .send_request_to(Agent, v2::CloseSessionRequest::new(self.session_id.clone()))
1046 .recover_error(|error| {
1047 if error.code == v2::ErrorCode::ResourceNotFound {
1048 Ok(v2::CloseSessionResponse::new())
1049 } else {
1050 Err(error)
1051 }
1052 })
1053 }
1054}