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