rho-coding-agent 3.7.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
//! `rho acp`: an ACP agent over stdio that relays the rho daemon.
//!
//! The daemon runs every session; this process is one of its clients, with
//! one connection for all the sessions its host opens (`app::daemon_client`,
//! whose errors `daemon.rs` maps to ACP errors). Each ACP request becomes
//! daemon requests (`sessions.rs`, `prompt.rs`, `auth.rs`), and each
//! session's daemon events become ACP updates (`updates.rs`) and host
//! prompts (`inputs.rs`). A connection that negotiates ACP v2 is served by
//! translating at its boundary (`v2`).

mod auth;
mod daemon;
mod elicitation;
mod host_features;
mod initialize_screen;
mod inputs;
mod markers;
mod options;
mod permission;
mod prompt;
mod requests;
mod sessions;
mod t3_prompt;
mod transport;
mod updates;
mod v2;

use std::{collections::BTreeSet, future::Future, pin::Pin, sync::Arc};

use agent_client_protocol::{
    schema::ProtocolVersion,
    v1::schema::{
        AgentAuthCapabilities, AgentCapabilities, AuthenticateRequest, CancelNotification,
        CloseSessionRequest, CompleteElicitationNotification, CreateElicitationRequest,
        CreateElicitationResponse, DeleteSessionRequest, Implementation, InitializeRequest,
        InitializeResponse, ListSessionsRequest, ListSessionsResponse, LoadSessionRequest,
        LoadSessionResponse, LogoutCapabilities, LogoutRequest, McpCapabilities, NewSessionRequest,
        NewSessionResponse, PromptCapabilities, PromptRequest, PromptResponse,
        RequestPermissionRequest, RequestPermissionResponse, ResumeSessionRequest,
        ResumeSessionResponse, SessionAdditionalDirectoriesCapabilities, SessionCapabilities,
        SessionCloseCapabilities, SessionDeleteCapabilities, SessionId, SessionListCapabilities,
        SessionNotification, SessionResumeCapabilities, SetSessionConfigOptionRequest,
        SetSessionModeRequest, StopReason,
    },
    v1::{ConnectionTo, Responder},
    Agent, Client, ConnectTo, Error as AcpError, JsonRpcResponse, Role,
};
use rho_protocol::{methods::SessionList, SessionListParams, SessionPart, SubagentRef};

use super::{
    daemon_client::Daemon,
    shutdown_signal::{ShutdownSignals, TerminalClosed},
};
use crate::{
    cli::Cli,
    herdr::{HerdrReporter, HerdrSource},
};
use auth::LoginFlight;
use host_features::{NegotiatedFeatures, Turns};
use requests::{Launch, LaunchHost};
use sessions::{Close, IfOpen, Sessions, Started};

/// Outbound ACP host port: session updates, permission prompts, and
/// elicitations, as one connection's protocol version sends them.
///
/// Implemented by [`ConnectionPort`] for v1 and `v2::port::V2Port` for v2.
/// Keep it object-safe. Dropping a returned request future before it
/// resolves abandons the request; the port then sends `$/cancel_request`.
pub(super) trait AcpClientPort: Send + Sync {
    fn send_session_notification(
        &self,
        notification: SessionNotification,
    ) -> Pin<Box<dyn Future<Output = Result<(), AcpError>> + Send + '_>>;

    fn request_permission(
        &self,
        request: RequestPermissionRequest,
    ) -> Pin<Box<dyn Future<Output = Result<RequestPermissionResponse, AcpError>> + Send + '_>>;

    /// `elicitation/create`, sent only to hosts that advertised its mode.
    fn create_elicitation(
        &self,
        request: CreateElicitationRequest,
    ) -> Pin<Box<dyn Future<Output = Result<CreateElicitationResponse, AcpError>> + Send + '_>>;

    /// `elicitation/complete`: the out-of-band step behind a URL-mode
    /// elicitation finished.
    fn complete_elicitation(
        &self,
        notification: CompleteElicitationNotification,
    ) -> Pin<Box<dyn Future<Output = Result<(), AcpError>> + Send + '_>>;

    /// The turn of session `session_id` that the host was told is running
    /// ended as `end`, leaving `background` work: the turn of its own
    /// prompt, once acknowledged, or one it did not prompt, which was
    /// running when it attached or that began since. The session's pump
    /// tells it, so nothing it reports of later work can come first.
    /// [`TurnEnd::Unseen`] also repeats an idle state the host was not
    /// told while its prompt waited to be acknowledged. Only ACP v2
    /// reports turn state (`state_update`), so a v1 host has nothing to
    /// hear.
    fn turn_ended(
        &self,
        _session_id: &SessionId,
        _end: TurnEnd,
        _background: &[rho_protocol::BackgroundWork],
    ) {
    }

    /// Session `session_id`'s background work changed. Only ACP v2 reports
    /// background work (a `state_update`'s `background`), so a v1 host has
    /// nothing to hear.
    fn background_changed(&self, _session_id: &SessionId, _change: BackgroundChanged<'_>) {}

    /// Session `session_id`'s foreground work is now `foreground`, which no
    /// prompt of the host's reports: a turn it did not prompt began, the
    /// turn it follows began or stopped waiting for a person, or the
    /// session can be observed again after [`Self::unobservable`].
    /// [`Foreground::Idle`] only for that last case; otherwise a followed
    /// turn's end is reported by [`Self::turn_ended`]. Only ACP v2 reports
    /// turn state, so a v1 host has nothing to hear.
    fn foreground_changed(
        &self,
        _session_id: &SessionId,
        _foreground: Foreground,
        _background: &[rho_protocol::BackgroundWork],
    ) {
    }

    /// Session `session_id`'s work can no longer be observed, as when the
    /// daemon link is lost, until [`Self::foreground_changed`] reports it
    /// again. Only ACP v2 reports it (the `unknown` state), so a v1 host
    /// has nothing to hear.
    fn unobservable(&self, _session_id: &SessionId) {}

    /// The session a question of `child`, a subagent of session
    /// `session_id`, is put to the host under: the child's own, when the
    /// host was told of it as a session (ACP v2's child sessions). `None`
    /// puts it under `session_id`, as a v1 host has it.
    fn child_session(&self, _session_id: &SessionId, _child: &SubagentRef) -> Option<SessionId> {
        None
    }

    /// Session `session_id` is no longer relayed to the host, which hears
    /// nothing more of it, nor of the child sessions it was told of.
    fn released(&self, _session_id: &SessionId) {}

    /// Session `session_id` is about to ask the host to approve `plan`,
    /// markdown. Only ACP v2 shows a plan as such (a markdown
    /// `plan_update`); a v1 host reads it on the approval's card.
    fn plan_proposed(&self, _session_id: &SessionId, _plan: &str) {}

    /// The plan [`Self::plan_proposed`] showed is no longer proposed: the
    /// host kept planning, or the request ended without its approval.
    fn plan_withdrawn(&self, _session_id: &SessionId) {}

    /// Session `session_id`'s background process `process` wrote `text`
    /// since the last call, or since it started, which its terminal shows.
    /// Called only for a host that shows terminals
    /// (`HostFeatures::display_terminals`): ACP v2's display-only ones.
    fn terminal_output(&self, _session_id: &SessionId, _process: &str, _text: &str) {}
}

/// A session's background work went from `previous` to `current`.
pub(super) struct BackgroundChanged<'a> {
    pub(super) previous: &'a [rho_protocol::BackgroundWork],
    pub(super) current: &'a [rho_protocol::BackgroundWork],
    /// The directory the session works in, which its background processes
    /// start in.
    pub(super) workspace: &'a std::path::Path,
    /// What the host was told the session's foreground work is doing,
    /// which the repeated state reports; `None` while a prompt of the
    /// host's waits to be acknowledged, whose `running` will carry the
    /// list, so no state is repeated before it.
    pub(super) foreground: Option<Foreground>,
}

/// What a session's foreground work is doing, as ACP v2's `state_update`
/// reports it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Foreground {
    Running,
    /// A turn is under way and waits for a person to answer.
    RequiresAction,
    Idle,
}

impl Foreground {
    /// The foreground of a session whose job is in `state`. A state a newer
    /// daemon sends counts as idle, as it does for a prompt.
    pub(super) fn of(state: rho_protocol::JobState) -> Self {
        use rho_protocol::JobState;
        match state {
            JobState::Running | JobState::Queued => Self::Running,
            JobState::WaitingForInput => Self::RequiresAction,
            JobState::Idle
            | JobState::Completed
            | JobState::Failed
            | JobState::Cancelled
            | JobState::TimedOut
            | JobState::Interrupted
            | JobState::Unknown => Self::Idle,
            _ => Self::Idle,
        }
    }
}

/// How a turn ended, as far as the host can tell.
pub(super) enum TurnEnd {
    /// With this stop reason, or the error it failed with.
    Ended(Result<StopReason, AcpError>),
    /// While the host was not following it, so how is unknown.
    Unseen,
}

/// The [`AcpClientPort`] of an ACP v1 connection.
struct ConnectionPort {
    cx: ConnectionTo<Client>,
}

impl AcpClientPort for ConnectionPort {
    fn send_session_notification(
        &self,
        notification: SessionNotification,
    ) -> Pin<Box<dyn Future<Output = Result<(), AcpError>> + Send + '_>> {
        Box::pin(async move { self.cx.send_notification(notification) })
    }

    fn request_permission(
        &self,
        request: RequestPermissionRequest,
    ) -> Pin<Box<dyn Future<Output = Result<RequestPermissionResponse, AcpError>> + Send + '_>>
    {
        Box::pin(async move { self.cx.send_request(request).block_task().await })
    }

    fn create_elicitation(
        &self,
        request: CreateElicitationRequest,
    ) -> Pin<Box<dyn Future<Output = Result<CreateElicitationResponse, AcpError>> + Send + '_>>
    {
        Box::pin(async move { self.cx.send_request(request).block_task().await })
    }

    fn complete_elicitation(
        &self,
        notification: CompleteElicitationNotification,
    ) -> Pin<Box<dyn Future<Output = Result<(), AcpError>> + Send + '_>> {
        Box::pin(async move { self.cx.send_notification(notification) })
    }
}

/// One `rho acp` process: its daemon connection and the sessions its host
/// has open.
pub(super) struct Adapter {
    daemon: Arc<Daemon>,
    launch: Launch,
    negotiated: NegotiatedFeatures,
    sessions: Sessions,
    herdr: HerdrReporter,
    logins: LoginFlight,
}

impl Adapter {
    fn new(cli: &Cli) -> anyhow::Result<Self> {
        let cwd = std::env::current_dir()?;
        let added_dirs = crate::added_dirs::launch_added_dirs(&cli.add_dirs, &cwd)?;
        let without = [
            (cli.no_tools, SessionPart::Tools),
            (cli.no_system_prompt, SessionPart::SystemPrompt),
            (cli.no_subagents, SessionPart::Subagents),
        ]
        .into_iter()
        .filter_map(|(left_out, part)| left_out.then_some(part))
        .collect::<BTreeSet<_>>();
        Ok(Self {
            // An editor's host answers its sessions' approvals.
            daemon: Arc::new(Daemon::for_frontend()),
            launch: Launch {
                agent: cli.agent.clone(),
                added_dirs: added_dirs.as_slice().to_vec(),
                without,
                host: match &cli.command {
                    Some(crate::cli::Command::Acp(args)) if args.t3code => LaunchHost::T3Code,
                    _ => LaunchHost::Other,
                },
            },
            negotiated: NegotiatedFeatures::default(),
            sessions: Sessions::default(),
            // Headless, so Herdr does not treat the pane as an interactive
            // Rho.
            herdr: HerdrReporter::from_env().with_source(HerdrSource::Headless),
            logins: LoginFlight::default(),
        })
    }

    /// The v1 handshake. The v2 adapter translates the response.
    pub(super) async fn initialize(&self, request: &InitializeRequest) -> InitializeResponse {
        InitializeResponse::new(ProtocolVersion::V1)
            .agent_capabilities(
                AgentCapabilities::new()
                    .load_session(true)
                    .prompt_capabilities(prompt_capabilities())
                    // Host stdio servers are the ACP baseline; Streamable
                    // HTTP is the transport Rho also speaks. SSE is not.
                    .mcp_capabilities(McpCapabilities::new().http(true))
                    // `additionalDirectories` on `session/new`, `session/load`,
                    // and `session/resume`; `session/close`; `session/list` and
                    // `session/delete` for host history.
                    .session_capabilities(
                        SessionCapabilities::new()
                            .additional_directories(SessionAdditionalDirectoriesCapabilities::new())
                            .resume(SessionResumeCapabilities::new())
                            .close(SessionCloseCapabilities::new())
                            .list(SessionListCapabilities::new())
                            .delete(SessionDeleteCapabilities::new()),
                    )
                    .auth(AgentAuthCapabilities::new().logout(LogoutCapabilities::new())),
            )
            .auth_methods(self.auth_methods(request).await)
            // Hosts display `version` as the agent version; it matches `rho --version`.
            .agent_info(Implementation::new("rho", env!("CARGO_PKG_VERSION")).title("Rho"))
    }

    /// `session/list`: the daemon's saved sessions, a page at a time.
    pub(super) async fn list_sessions(
        &self,
        request: &ListSessionsRequest,
    ) -> Result<ListSessionsResponse, AcpError> {
        let params = SessionListParams {
            cwd: request.cwd.clone(),
            cursor: request.cursor.clone(),
            limit: None,
        };
        let page = self.daemon.request::<SessionList>(&params).await?;
        Ok(requests::session_list(page))
    }

    fn toggles(&self) -> host_features::Toggles {
        self.negotiated.get().toggles
    }
}

/// The v1 responses to the requests that open a session, showing its
/// options as a host with `toggles` draws them.
impl Started {
    fn new_session_response(&self, toggles: host_features::Toggles) -> NewSessionResponse {
        NewSessionResponse::new(self.session_id.clone())
            .config_options(options::config_options(&self.options, toggles))
            .modes(options::modes(&self.options.permission_mode))
    }

    fn load_session_response(&self, toggles: host_features::Toggles) -> LoadSessionResponse {
        LoadSessionResponse::new()
            .config_options(options::config_options(&self.options, toggles))
            .modes(options::modes(&self.options.permission_mode))
    }

    fn resume_session_response(&self, toggles: host_features::Toggles) -> ResumeSessionResponse {
        ResumeSessionResponse::new()
            .config_options(options::config_options(&self.options, toggles))
            .modes(options::modes(&self.options.permission_mode))
    }
}

pub(super) async fn run(cli: Cli) -> anyhow::Result<()> {
    // Probe stdin before the transport starts reading it. See
    // `stdin_is_terminal`.
    let _ = crate::stdio::stdin_is_terminal();
    // Installed before the host can reach this agent, so a stop signal
    // always detaches its sessions.
    let mut stops = ShutdownSignals::install()?;
    let mut hangup = TerminalClosed::install()?;
    let adapter = Arc::new(Adapter::new(&cli)?);
    // Host integrations do not change protocol negotiation: each connection
    // uses the highest version both sides support.
    const VERSIONS: &[ProtocolVersion] = &[ProtocolVersion::V1, ProtocolVersion::V2];
    let server = Agent
        .protocol_router()
        .with_v1(v1_agent(Arc::clone(&adapter)))
        .with_v2(v2::agent(Arc::clone(&adapter)))
        .connect_to(transport::HostStdio::new(VERSIONS));
    let served = tokio::select! {
        served = tokio::spawn(server) => served
            .map_err(|error| anyhow::anyhow!("ACP server task failed: {error}"))
            .and_then(|served| served.map_err(acp_error)),
        () = stopped(&mut stops, &mut hangup) => Ok(()),
    };
    // Cancels this host's prompts and detaches, so no turn of this host's
    // runs on unwatched; a second signal stops waiting for the daemon.
    tokio::select! {
        () = adapter.close_all() => {}
        () = stopped(&mut stops, &mut hangup) => {}
    }
    served
}

/// Returns once this process is told to stop: by a shutdown signal, or by
/// the terminal closing, as when a host closes the one it ran the agent in.
async fn stopped(stops: &mut ShutdownSignals, hangup: &mut TerminalClosed) {
    tokio::select! {
        _ = stops.recv() => {}
        () = hangup.recv() => {}
    }
}

/// The prompt content Rho accepts beyond text and resource links. ACP v2
/// refuses a prompt carrying any other type (`v2::requests::prompt_request`).
fn prompt_capabilities() -> PromptCapabilities {
    PromptCapabilities::new()
        .image(true)
        .audio(false)
        .embedded_context(true)
}

/// The ACP v1 agent for one connection.
fn v1_agent(adapter: Arc<Adapter>) -> impl ConnectTo<Client> {
    Agent
        .v1()
        .name("rho")
        .on_receive_request(
            {
                let adapter = Arc::clone(&adapter);
                async move |request: InitializeRequest, responder, cx| {
                    adapter.negotiated.record(
                        &request,
                        Arc::new(ConnectionPort { cx: cx.clone() }),
                        Turns::Prompted,
                    );
                    let adapter = Arc::clone(&adapter);
                    spawn_response(&cx, responder, async move {
                        Ok(adapter.initialize(&request).await)
                    })
                }
            },
            agent_client_protocol::on_receive_request!(),
        )
        .on_receive_request(
            {
                let adapter = Arc::clone(&adapter);
                async move |request: NewSessionRequest, responder, cx| {
                    let adapter = Arc::clone(&adapter);
                    let port: Arc<dyn AcpClientPort> = Arc::new(ConnectionPort { cx: cx.clone() });
                    cx.spawn(async move {
                        let started = adapter.new_session(&request, /*system_prompt*/ None).await;
                        let toggles = adapter.toggles();
                        respond_started(responder, &port, started, |started| {
                            started.new_session_response(toggles)
                        })
                        .await
                    })
                }
            },
            agent_client_protocol::on_receive_request!(),
        )
        .on_receive_request(
            {
                let adapter = Arc::clone(&adapter);
                async move |request: LoadSessionRequest, responder, cx| {
                    let adapter = Arc::clone(&adapter);
                    let port: Arc<dyn AcpClientPort> = Arc::new(ConnectionPort { cx: cx.clone() });
                    cx.spawn(async move {
                        let started = adapter
                            .load_session(
                                &request,
                                /*system_prompt*/ None,
                                Arc::clone(&port),
                                IfOpen::Restart,
                            )
                            .await;
                        let toggles = adapter.toggles();
                        respond_started(responder, &port, started, |started| {
                            started.load_session_response(toggles)
                        })
                        .await
                    })
                }
            },
            agent_client_protocol::on_receive_request!(),
        )
        .on_receive_request(
            {
                let adapter = Arc::clone(&adapter);
                async move |request: ResumeSessionRequest, responder, cx| {
                    let adapter = Arc::clone(&adapter);
                    let port: Arc<dyn AcpClientPort> = Arc::new(ConnectionPort { cx: cx.clone() });
                    cx.spawn(async move {
                        let started = adapter
                            .resume_session(&request, /*system_prompt*/ None, IfOpen::Restart)
                            .await;
                        let toggles = adapter.toggles();
                        respond_started(responder, &port, started, |started| {
                            started.resume_session_response(toggles)
                        })
                        .await
                    })
                }
            },
            agent_client_protocol::on_receive_request!(),
        )
        .on_receive_request(
            {
                let adapter = Arc::clone(&adapter);
                async move |request: PromptRequest, responder, cx| {
                    let adapter = Arc::clone(&adapter);
                    spawn_response(&cx, responder, async move {
                        let prompted = adapter
                            .prompt(
                                &request.session_id,
                                &request.prompt,
                                /*accept*/ None,
                                prompt::BusyPrompt::Reject,
                            )
                            .await?;
                        let stop = match prompted {
                            prompt::Prompted::Ended(stop) => stop,
                            // A v1 prompt names no key, so the daemon never
                            // takes it for one sent again.
                            prompt::Prompted::SentAgain { .. } => StopReason::EndTurn,
                        };
                        Ok(PromptResponse::new(stop))
                    })
                }
            },
            agent_client_protocol::on_receive_request!(),
        )
        .on_receive_request(
            {
                let adapter = Arc::clone(&adapter);
                async move |request: ListSessionsRequest, responder, cx| {
                    let adapter = Arc::clone(&adapter);
                    spawn_response(&cx, responder, async move {
                        adapter.list_sessions(&request).await
                    })
                }
            },
            agent_client_protocol::on_receive_request!(),
        )
        .on_receive_request(
            {
                let adapter = Arc::clone(&adapter);
                async move |request: DeleteSessionRequest, responder, cx| {
                    let adapter = Arc::clone(&adapter);
                    spawn_response(&cx, responder, async move {
                        adapter.delete_session(&request, Close::Detach).await
                    })
                }
            },
            agent_client_protocol::on_receive_request!(),
        )
        .on_receive_request(
            {
                let adapter = Arc::clone(&adapter);
                async move |request: SetSessionConfigOptionRequest, responder, cx| {
                    let adapter = Arc::clone(&adapter);
                    spawn_response(&cx, responder, async move {
                        adapter.set_config_option(&request).await
                    })
                }
            },
            agent_client_protocol::on_receive_request!(),
        )
        .on_receive_request(
            {
                let adapter = Arc::clone(&adapter);
                async move |request: SetSessionModeRequest, responder, cx| {
                    let adapter = Arc::clone(&adapter);
                    spawn_response(&cx, responder, async move {
                        adapter.set_session_mode(&request).await
                    })
                }
            },
            agent_client_protocol::on_receive_request!(),
        )
        .on_receive_request(
            {
                let adapter = Arc::clone(&adapter);
                async move |request: CloseSessionRequest, responder, cx| {
                    let adapter = Arc::clone(&adapter);
                    spawn_response(&cx, responder, async move {
                        adapter.close_session(&request, Close::Detach).await
                    })
                }
            },
            agent_client_protocol::on_receive_request!(),
        )
        .on_receive_request(
            {
                let adapter = Arc::clone(&adapter);
                async move |request: AuthenticateRequest, responder, cx| {
                    let adapter = Arc::clone(&adapter);
                    let port = ConnectionPort { cx: cx.clone() };
                    let request_id = responder.id().clone();
                    // A host that cancels sign-in cancels the login with it.
                    let cancellation = responder.cancellation();
                    spawn_response(&cx, responder, async move {
                        let auth = &request.method_id.0;
                        adapter
                            .authenticate(auth, request_id, &port, cancellation)
                            .await
                    })
                }
            },
            agent_client_protocol::on_receive_request!(),
        )
        .on_receive_request(
            {
                let adapter = Arc::clone(&adapter);
                async move |_request: LogoutRequest, responder, cx| {
                    let adapter = Arc::clone(&adapter);
                    spawn_response(&cx, responder, async move { adapter.logout().await })
                }
            },
            agent_client_protocol::on_receive_request!(),
        )
        .on_receive_notification(
            {
                let adapter = Arc::clone(&adapter);
                async move |notification: CancelNotification, _cx| {
                    adapter.cancel(&notification.session_id).await;
                    Ok(())
                }
            },
            agent_client_protocol::on_receive_notification!(),
        )
        .on_close({
            let adapter = Arc::clone(&adapter);
            async move |_cx| {
                adapter.close_all().await;
                Ok(())
            }
        })
}

/// Answers `session/new`, `session/load`, or `session/resume` with
/// `respond(started)`, then sends the session's commands and lets its live
/// updates through: updates name a session the host learns from the
/// response, so they follow it.
async fn respond_started<Resp: JsonRpcResponse>(
    responder: Responder<Resp>,
    port: &Arc<dyn AcpClientPort>,
    started: Result<Started, AcpError>,
    respond: impl FnOnce(&Started) -> Resp,
) -> Result<(), AcpError> {
    let started = match started {
        Ok(started) => started,
        Err(error) => return responder.respond_with_error(error),
    };
    responder.respond(respond(&started))?;
    let commands = updates::notification(
        &started.session_id,
        updates::commands_update(&started.options.commands),
        updates::Delivery::Live,
    );
    if let Err(error) = port.send_session_notification(commands).await {
        tracing::warn!(%error, "could not advertise ACP commands");
    }
    started.open();
    Ok(())
}

fn spawn_response<Resp, Counterpart, Fut>(
    cx: &ConnectionTo<Counterpart>,
    responder: Responder<Resp>,
    work: Fut,
) -> Result<(), AcpError>
where
    Resp: JsonRpcResponse + Send + 'static,
    Counterpart: Role,
    Fut: Future<Output = Result<Resp, AcpError>> + Send + 'static,
{
    cx.spawn(async move {
        match work.await {
            Ok(response) => responder.respond(response),
            Err(error) => responder.respond_with_error(error),
        }
    })
}

/// `resource_not_found` as ACP v1 writes it, for a session the host names
/// that this adapter does not hold. Every `-32002` the adapter sends names
/// a session: v2 rewrites each one into its `data.sessionId` form
/// (`v2::errors::session_scoped`), so another missing resource needs
/// another code.
fn resource_not_found(uri: Option<String>) -> AcpError {
    agent_client_protocol::v1::schema::Error::resource_not_found(uri).into()
}

fn acp_error(error: AcpError) -> anyhow::Error {
    anyhow::Error::msg(error.to_string())
}