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
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
//! The sessions this process has open, each attached to the daemon.
//!
//! The daemon owns every session; this process attaches to the ones its
//! host opens, loads, or resumes, and relays them. A session's events
//! reach one pump task (`sessions/pump.rs`), in order, through the router
//! (`app::daemon_client`), and the requests the host sends about it
//! (`session/prompt`, config changes) hand the pump what it must sequence
//! with those events as [`Control`]s on the same channel, after the events
//! the connection already read ([`Live::deliver`]).
//!
//! A pump moves through each attachment in three steps: the attach's
//! replay (history shown to a host that loads a session, missed events
//! after a reattach, or nothing), then the host's response, which the
//! request releases through a gate so no update names a session before
//! the host learns of it, then live events. When the attachment ends with
//! the connection or the daemon, the session goes stale, and the next
//! request about it has the pump attach again after its cursor.
//!
//! Closing a session (`close.rs`) detaches it on ACP v1, and stops its work
//! on ACP v2.

mod close;
mod output;
mod pump;

use std::{
    collections::{BTreeMap, HashMap},
    future::Future,
    path::PathBuf,
    pin::Pin,
    sync::{
        atomic::{AtomicBool, AtomicU64, Ordering},
        Arc, Mutex, PoisonError,
    },
};

use agent_client_protocol::{
    v1::schema::{
        LoadSessionRequest, McpServer, MessageId, NewSessionRequest, ResumeSessionRequest,
        SessionId as AcpSessionId, SetSessionConfigOptionRequest, SetSessionConfigOptionResponse,
        SetSessionModeRequest, SetSessionModeResponse, UsageUpdate,
    },
    Error as AcpError, RequestCancellation,
};
use rho_protocol::{
    methods::{
        SessionAttach, SessionBackgroundStop, SessionCancel, SessionConfigure, SessionDetach,
        SessionNew, SessionProcesses,
    },
    BackgroundItem, BackgroundWork, ClientEnvironment, Cursor, JobState, ProcessOutput,
    ProcessOutputParams, Replay, SessionAttachParams, SessionAttachResponse,
    SessionBackgroundStopParams, SessionCancelParams, SessionChange, SessionConfigureParams,
    SessionDetachParams, SessionId, SessionNewParams, SessionOptions, SessionProcessesParams,
    SessionSetup, TurnId, TurnOutcome,
};
use tokio::{
    sync::{mpsc, oneshot, watch},
    task::JoinHandle,
};

use super::{
    daemon,
    inputs::{Asks, InputContext, TurnCancels},
    options,
    prompt::{Holds, Place},
    requests, AcpClientPort, Adapter, Foreground,
};
use crate::app::daemon_client::{Daemon, Link, Routed, SessionRoute};

pub(super) use close::Close;
use close::Wait;

/// What a session's pump reads, in order: what the router read for the
/// session, and what its requests hand it.
enum Inbound {
    Routed(Routed),
    Control(Control),
    /// Every event of the attachment a [`Control::Resync`] detached went
    /// before this, which the pump sends itself.
    Drained,
}

/// What a session's requests hand its pump.
pub(super) enum Control {
    /// Attach again after the cursor, once the last attachment ended;
    /// answered once the replay is through, or with why the attach failed.
    Resume(Replayed),
    /// Attach again in place for a host that resumes the session it has
    /// open, following on whatever turn the pump follows; see [`Resync`].
    Resync(Box<Resync>),
    /// A prompt of this host's is about to be sent; see [`Waiter`]. `turn`
    /// hears the turn the daemon answers it with, and closes unheard when
    /// the prompt started none. The pump waits for it before it reads on.
    Arm {
        waiter: Waiter,
        turn: oneshot::Receiver<TurnId>,
    },
    /// The daemon answered a config change with these options. The pump
    /// tells the host what changed, then answers, so the host hears the
    /// update before the response, and only once even when the daemon's
    /// `OptionsChanged` arrived first.
    Options(Box<SessionOptions>, oneshot::Sender<()>),
    /// Answered once the pump handled everything routed before it, so a
    /// response sent after the answer follows the updates sent before it.
    Flush(oneshot::Sender<()>),
}

/// Told once an attachment's replay is through, with the session's
/// [`Current`] info, or why it never started.
pub(super) type Replayed = oneshot::Sender<Result<Current, AcpError>>;

/// What a session's info is as its replay ends. ACP v2 replays no past info,
/// so a v2 resume reports this after the replay.
#[derive(Debug)]
pub(super) struct Current {
    /// The session's title, once it has one.
    pub(super) title: Option<String>,
    /// The session's last usage report, if it has one.
    pub(super) usage: Option<UsageUpdate>,
    /// The directory the session works in, which its background processes
    /// start in.
    pub(super) workspace: PathBuf,
    /// The output the daemon retains of each background process the
    /// session runs, by id, for a host that shows it
    /// (`HostFeatures::display_terminals`); a v2 resume sends it whole as
    /// the process's terminal output.
    pub(super) output: BTreeMap<String, String>,
}

/// The attach that opened a session, which its pump starts on.
struct Opening {
    response: SessionAttachResponse,
    show: Show,
    replayed: Replayed,
    /// Released once the host has the response that names the session.
    gate: oneshot::Receiver<()>,
}

/// An in-place attach for a host's resume of a session open here. The
/// daemon replaces an attachment without marking where the old one's
/// events end, so the pump detaches first ([`Attacher::detach`]) and
/// attaches once it read them all ([`Inbound::Drained`]).
pub(super) struct Resync {
    from: ReplayFrom,
    setup: SessionSetup,
    replayed: Replayed,
    /// Released once the host has the resume's response.
    gate: oneshot::Receiver<()>,
}

/// Where a [`Resync`] replays from.
pub(super) enum ReplayFrom {
    /// The start, as history shown through this port.
    Start(Arc<dyn AcpClientPort>),
    /// The pump's cursor: the events the host missed, if any.
    Cursor,
}

/// What a pump does with an attachment's replay.
#[derive(Clone)]
pub(super) enum Show {
    /// History for a host that loads the session, marked as replay and
    /// sent through the loading request's port.
    History(Arc<dyn AcpClientPort>),
    /// Events the host missed while detached, handled as live.
    Missed,
    /// Nothing: the host has it, or the session is new.
    Skip,
}

impl Show {
    /// What a reattach after the cursor shows of a `replay` replay: a tail
    /// holds the events the host missed, and a reset the history it has.
    fn resumed(replay: Replay) -> Self {
        match replay {
            Replay::Tail => Self::Missed,
            Replay::Reset => Self::Skip,
        }
    }
}

/// Called with the daemon's id for the user message of an ACP v2 prompt,
/// which acknowledges the prompt.
pub(super) type Accept = Box<dyn FnOnce(MessageId) + Send>;

/// A prompt of this host's, waiting for its turn to end.
///
/// The turn's first user message is the prompt's own: the host already
/// shows it, so it is not echoed; an ACP v2 prompt's [`Accept`] reports it
/// instead. The turn's end ends the prompt. A waiter whose prompt gave up
/// (its receiver is gone) is dropped.
pub(super) struct Waiter {
    pub(super) outcome: oneshot::Sender<Result<TurnOutcome, AcpError>>,
    pub(super) accept: Arc<Mutex<Option<Accept>>>,
}

/// Whether a session's attachment delivers, as its pump last saw.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Attachment {
    /// Delivering; the session's job is in this state.
    Attached(JobState),
    /// Not attached yet, or the connection closed or the daemon stopped:
    /// attach again.
    Stale,
    /// The daemon deleted the session.
    Deleted,
}

impl Attachment {
    /// A turn of the session's is in progress, as far as this host knows:
    /// an attachment that no longer delivers reports none.
    fn busy(self) -> bool {
        matches!(self, Self::Attached(state) if busy(state))
    }

    /// What the session's foreground work is doing, as far as this host
    /// knows: an attachment that no longer delivers reports none.
    fn foreground(self) -> Foreground {
        match self {
            Self::Attached(state) => Foreground::of(state),
            Self::Stale | Self::Deleted => Foreground::Idle,
        }
    }
}

/// What a session's requests and its pump share.
struct Shared {
    /// The options the host last heard of.
    options: Mutex<SessionOptions>,
    /// The session's background work, as the host was last told it. Held
    /// while telling the host anything that lists it, so reports from the
    /// pump and from a prompt reach the host in the order they read it.
    background: Mutex<Vec<BackgroundWork>>,
    attachment: watch::Sender<Attachment>,
}

/// Attaches sessions on the daemon for their pumps, and reads their
/// background processes' output: the daemon itself, or a fake in the
/// pump's tests. Implementors answer with the daemon's response
/// or the ACP error a refused or failed attach answers.
pub(super) trait Attacher: Send + Sync {
    /// Attaches `session` with `setup`, resuming after `after` when the
    /// daemon still buffers it.
    fn attach<'a>(
        &'a self,
        session: &'a SessionId,
        after: Option<&'a Cursor>,
        setup: &'a SessionSetup,
    ) -> Pin<Box<dyn Future<Output = Result<SessionAttachResponse, AcpError>> + Send + 'a>>;

    /// Ends `session`'s attachment, returning once every event it sent is
    /// routed. Nothing to end once the connection closed.
    fn detach<'a>(
        &'a self,
        session: &'a SessionId,
    ) -> Pin<Box<dyn Future<Output = Result<(), AcpError>> + Send + 'a>>;

    /// The output `session`'s process `process` wrote that the daemon
    /// still retains, from chunk `from` on. `None` when the daemon no
    /// longer knows the process, did not answer, or is not connected: a
    /// read never connects, as the attachment is what reads again then.
    fn process_output<'a>(
        &'a self,
        session: &'a SessionId,
        process: &'a str,
        from: u64,
    ) -> Pin<Box<dyn Future<Output = Option<ProcessOutput>> + Send + 'a>>;
}

impl Attacher for Daemon {
    fn attach<'a>(
        &'a self,
        session: &'a SessionId,
        after: Option<&'a Cursor>,
        setup: &'a SessionSetup,
    ) -> Pin<Box<dyn Future<Output = Result<SessionAttachResponse, AcpError>> + Send + 'a>> {
        Box::pin(async move {
            let link = self.link().await?;
            refuse_unapplied_system_prompt(&link, setup)?;
            let params = SessionAttachParams {
                session: session.clone(),
                after: after.cloned(),
                environment: ClientEnvironment::of_this_process(),
                setup: setup.clone(),
            };
            link.request::<SessionAttach>(&params)
                .await
                .map_err(|error| daemon::daemon_error(&error))
        })
    }

    fn detach<'a>(
        &'a self,
        session: &'a SessionId,
    ) -> Pin<Box<dyn Future<Output = Result<(), AcpError>> + Send + 'a>> {
        Box::pin(async move {
            let Some(link) = self.current().await else {
                return Ok(());
            };
            let params = SessionDetachParams {
                session: session.clone(),
            };
            link.request::<SessionDetach>(&params)
                .await
                .map_err(|error| daemon::daemon_error(&error))?;
            link.fence().await;
            Ok(())
        })
    }

    fn process_output<'a>(
        &'a self,
        session: &'a SessionId,
        process: &'a str,
        from: u64,
    ) -> Pin<Box<dyn Future<Output = Option<ProcessOutput>> + Send + 'a>> {
        Box::pin(async move {
            let link = self.current().await?;
            let params = SessionProcessesParams {
                session: session.clone(),
                output: Some(ProcessOutputParams {
                    process: process.to_owned(),
                    from,
                }),
            };
            match link.request::<SessionProcesses>(&params).await {
                Ok(response) => response.output,
                Err(error) => {
                    tracing::debug!(%error, "could not read a background process's output");
                    None
                }
            }
        })
    }
}

/// Refuses `setup`'s system prompt when the daemon behind `link` does not
/// apply one ([`rho_protocol::DaemonFeature::SystemPrompts`]): it would open
/// the session without it, and v2 requires a refusal of a prompt the agent
/// can't apply.
fn refuse_unapplied_system_prompt(link: &Link, setup: &SessionSetup) -> Result<(), AcpError> {
    if setup.system_prompt.is_none() || link.applies_system_prompts() {
        return Ok(());
    }
    Err(AcpError::invalid_params().data(
        "the running rho daemon is too old to apply systemPrompt; \
         run `rho daemon restart` to replace it with this build",
    ))
}

/// One session open on this host.
pub(super) struct Live {
    pub(super) id: SessionId,
    inbound: mpsc::UnboundedSender<Inbound>,
    shared: Arc<Shared>,
    /// Held while a prompt of this host's runs.
    pub(super) prompt: tokio::sync::Mutex<()>,
    /// Set by `session/cancel` until the prompt ends, so an ACP v1 prompt
    /// sent right after a cancel waits for the cancelled one; ACP v2
    /// prompts are held instead ([`Self::held`]).
    pub(super) cancelling: AtomicBool,
    /// Counts this host's cancels, which its input tasks read.
    cancels: TurnCancels,
    /// ACP v2 prompts waiting for the session, and its cancels, which drop
    /// the prompts held when they arrive.
    pub(super) held: Holds,
    /// Set once the host closes the session, before its prompt is
    /// cancelled, so a prompt queued behind the cancelled one ends
    /// cancelled instead of starting a turn the close would wait out.
    pub(super) closing: AtomicBool,
    attaching: tokio::sync::Mutex<()>,
    pump: JoinHandle<()>,
    /// The pump's input tasks, whose host requests a close withdraws.
    asks: Asks,
}

impl Live {
    /// Hands the pump `control` after every event `link` already read for
    /// the session, so the pump handles them in order: once a daemon
    /// response arrived, after the events the daemon sent before it. Fails
    /// when the pump is gone, dropping `control` and any answer it carries.
    pub(super) async fn deliver(&self, link: &Link, control: Control) -> Result<(), AcpError> {
        link.fence().await;
        self.inbound
            .send(Inbound::Control(control))
            .map_err(|_| super::resource_not_found(Some(self.id.as_str().to_owned())))
    }

    /// Starts watching the session's job just before a prompt is sent, so
    /// a prompt the daemon refuses as busy can wait for the turn in its way
    /// ([`Busy::ended`]).
    pub(super) fn watch_busy(&self) -> Busy {
        Busy(self.shared.attachment.subscribe())
    }
}

/// The session's job, as its pump saw it from just before a prompt was
/// sent.
pub(super) struct Busy(watch::Receiver<Attachment>);

impl Busy {
    /// Waits for the turn that kept the daemon from taking the prompt to
    /// end, once the pump handled everything read before the refusal: the
    /// daemon reports a turn `running` before it refuses a prompt for it,
    /// but that report may reach the pump later. Returns at once when the
    /// turn already ended, and on the first change when the pump has yet
    /// to hear of it, so the caller tries again and is refused again if
    /// the turn still runs. Also returns once the attachment ends.
    pub(super) async fn ended(mut self) {
        // One read: a state the pump sends between two reads would be
        // marked seen without counting as a change, and wait forever.
        let (busy, changed) = {
            let seen = self.0.borrow_and_update();
            (seen.busy(), seen.has_changed())
        };
        let _ = match (busy, changed) {
            (true, _) => self
                .0
                .wait_for(|attachment| !attachment.busy())
                .await
                .map(drop),
            (false, true) => Ok(()),
            (false, false) => self.0.changed().await,
        };
    }
}

/// What `session/load` and `session/resume` do with a session already open
/// here.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum IfOpen {
    /// Close it first, cancelling this host's prompt, and attach afresh,
    /// as ACP v1 does.
    Restart,
    /// Attach again in place, so this host's prompt runs on, as ACP v2
    /// resumes require.
    Resync,
}

/// The sessions this process has open, by ACP session id.
#[derive(Default)]
pub(super) struct Sessions {
    live: Mutex<HashMap<String, Arc<Live>>>,
    placeholders: Arc<AtomicU64>,
}

/// A session the host just opened or resynced, before the host has its
/// response.
pub(super) struct Started {
    pub(super) session_id: AcpSessionId,
    pub(super) options: SessionOptions,
    /// The session's job state when the attachment began: a turn another
    /// client started may be in progress.
    pub(super) state: JobState,
    /// The session's background work when the attachment began.
    pub(super) background: Vec<BackgroundWork>,
    /// The session's info when the attachment began.
    pub(super) current: Current,
    gate: oneshot::Sender<()>,
}

impl Started {
    /// Lets the session's live updates through, once the host has the
    /// response that names it.
    pub(super) fn open(self) {
        let _ = self.gate.send(());
    }
}

impl Sessions {
    fn get(&self, id: &str) -> Option<Arc<Live>> {
        lock(&self.live).get(id).cloned()
    }

    fn remove(&self, id: &str) -> Option<Arc<Live>> {
        lock(&self.live).remove(id)
    }

    fn take_all(&self) -> Vec<Arc<Live>> {
        lock(&self.live).drain().map(|(_, live)| live).collect()
    }
}

impl Adapter {
    fn port(&self) -> Result<Arc<dyn AcpClientPort>, AcpError> {
        self.negotiated
            .client()
            .ok_or_else(|| AcpError::internal_error().data("ACP connection not initialized"))
    }

    /// Runs `report` with the background work of open session `id`, as
    /// the host was last told it, none for a session not open here, and
    /// holds it so no other report of it interleaves.
    pub(super) fn with_background<T>(
        &self,
        id: &AcpSessionId,
        report: impl FnOnce(&[BackgroundWork]) -> T,
    ) -> T {
        match self.sessions.get(&id.0) {
            Some(live) => report(&lock(&live.shared.background)),
            None => report(&[]),
        }
    }

    /// Whether session `id` is open here.
    pub(super) fn is_open(&self, id: &AcpSessionId) -> bool {
        self.sessions.get(&id.0).is_some()
    }

    /// Stops the running piece of open session `id`'s background work that
    /// `find` picks. Work the host does not see running is invalid params,
    /// as ACP v2 has the cancel of an unknown or finished item answered.
    pub(super) async fn stop_background(
        &self,
        id: &AcpSessionId,
        find: impl FnOnce(&[BackgroundWork]) -> Option<BackgroundItem>,
    ) -> Result<(), AcpError> {
        let live = self.live(id).await?;
        let work = find(&lock(&live.shared.background)).ok_or_else(|| {
            AcpError::invalid_params().data("no such running background work in this session")
        })?;
        self.stop_work(&live, work).await
    }

    /// Stops the running background work `find` picks in whichever open
    /// session has it, as a cancel naming a child session asks. Returns
    /// whether a session had it.
    pub(super) async fn stop_any_background(
        &self,
        find: impl Fn(&[BackgroundWork]) -> Option<BackgroundItem>,
    ) -> bool {
        let lives: Vec<_> = lock(&self.sessions.live).values().cloned().collect();
        for live in lives {
            let Some(work) = find(&lock(&live.shared.background)) else {
                continue;
            };
            if let Err(error) = self.stop_work(&live, work).await {
                tracing::warn!(%error, "could not stop an ACP session's background work");
            }
            return true;
        }
        false
    }

    async fn stop_work(&self, live: &Live, work: BackgroundItem) -> Result<(), AcpError> {
        let link = self.daemon.link().await?;
        let params = SessionBackgroundStopParams {
            session: live.id.clone(),
            work,
        };
        link.request::<SessionBackgroundStop>(&params)
            .await
            .map_err(|error| daemon::daemon_error(&error))?;
        Ok(())
    }

    /// The open session `id`, attached or not.
    fn open_live(&self, id: &AcpSessionId) -> Result<Arc<Live>, AcpError> {
        self.sessions
            .get(&id.0)
            .ok_or_else(|| super::resource_not_found(Some(id.0.to_string())))
    }

    /// The open session `id`, attached.
    pub(super) async fn live(&self, id: &AcpSessionId) -> Result<Arc<Live>, AcpError> {
        let live = self.open_live(id)?;
        {
            // Held across the reattach, so concurrent requests reattach once.
            let _attaching = live.attaching.lock().await;
            let attachment = *live.shared.attachment.borrow();
            match attachment {
                Attachment::Attached(_) => {}
                Attachment::Stale => self.resume(&live).await?,
                Attachment::Deleted => {
                    self.sessions.remove(&id.0);
                    self.forget(&live);
                    return Err(super::resource_not_found(Some(id.0.to_string())));
                }
            }
        }
        Ok(live)
    }

    /// `session/new`: a new daemon session, attached, with the host's
    /// `system_prompt`, which only v2 takes.
    pub(super) async fn new_session(
        &self,
        request: &NewSessionRequest,
        system_prompt: Option<rho_protocol::SystemPrompt>,
    ) -> Result<Started, AcpError> {
        let cwd = requests::session_cwd(&request.cwd)?;
        let setup = self.launch.setup(
            &request.additional_directories,
            &request.mcp_servers,
            system_prompt,
            self.negotiated.get(),
        );
        let link = self.daemon.link().await?;
        refuse_unapplied_system_prompt(&link, &setup)?;
        let created = link
            .request::<SessionNew>(&SessionNewParams {
                cwd,
                environment: ClientEnvironment::of_this_process(),
                agent: self.launch.agent.clone(),
                setup: setup.clone(),
                parent: None,
                grant: None,
                worktree: false,
            })
            .await
            .map_err(|error| daemon::daemon_error(&error))?;
        self.open(created.session, setup, Show::Skip).await
    }

    /// `session/load`: the saved session, its history replayed through
    /// `port`, with the host's `system_prompt` when it brings one, which
    /// only v2 takes; without one it keeps the prompt it saved.
    pub(super) async fn load_session(
        &self,
        request: &LoadSessionRequest,
        system_prompt: Option<rho_protocol::SystemPrompt>,
        port: Arc<dyn AcpClientPort>,
        if_open: IfOpen,
    ) -> Result<Started, AcpError> {
        self.reopen(
            &request.session_id,
            &request.additional_directories,
            &request.mcp_servers,
            system_prompt,
            Show::History(port),
            if_open,
        )
        .await
    }

    /// `session/resume`: the saved session, whose history the host has,
    /// with `system_prompt` as for [`Self::load_session`].
    pub(super) async fn resume_session(
        &self,
        request: &ResumeSessionRequest,
        system_prompt: Option<rho_protocol::SystemPrompt>,
        if_open: IfOpen,
    ) -> Result<Started, AcpError> {
        self.reopen(
            &request.session_id,
            &request.additional_directories,
            &request.mcp_servers,
            system_prompt,
            Show::Skip,
            if_open,
        )
        .await
    }

    /// `session/load` and `session/resume`. A session already open here is
    /// restarted or resynced as `if_open` says; a deleted one is opened
    /// afresh.
    async fn reopen(
        &self,
        session_id: &AcpSessionId,
        additional_directories: &[std::path::PathBuf],
        servers: &[McpServer],
        system_prompt: Option<rho_protocol::SystemPrompt>,
        show: Show,
        if_open: IfOpen,
    ) -> Result<Started, AcpError> {
        let setup = self.launch.setup(
            additional_directories,
            servers,
            system_prompt,
            self.negotiated.get(),
        );
        // Before the session's attachment is touched; the attach checks
        // again on the connection it goes over.
        refuse_unapplied_system_prompt(&*self.daemon.link().await?, &setup)?;
        if let Some(live) = self.sessions.get(&session_id.0) {
            let attachment = *live.shared.attachment.borrow();
            match (if_open, attachment) {
                (IfOpen::Resync, Attachment::Attached(_) | Attachment::Stale) => {
                    return self.resync(&live, setup, show).await;
                }
                (IfOpen::Resync, Attachment::Deleted) | (IfOpen::Restart, _) => {}
            }
            self.sessions.remove(&session_id.0);
            self.detach(&live, Wait::Prompt).await;
            // The old attachment's events still in flight are routed, and
            // dropped, before the new one's route takes their place.
            if let Some(link) = self.daemon.current().await {
                link.fence().await;
            }
        }
        self.open(SessionId::new(session_id.0.as_ref()), setup, show)
            .await
    }

    /// Has open session `live`'s pump attach again in place with `setup`
    /// ([`Resync`]), showing the replay as `show` says, and returns once
    /// the replay is through.
    async fn resync(
        &self,
        live: &Live,
        setup: SessionSetup,
        show: Show,
    ) -> Result<Started, AcpError> {
        // Held across the attach, so a request finding the session stale
        // meanwhile does not attach it too.
        let _attaching = live.attaching.lock().await;
        let link = self.daemon.link().await?;
        // A lost connection took the session's route with it.
        self.daemon.route(&live.id, route(&live.inbound));
        let (replayed, through) = oneshot::channel();
        let (gate, gate_receiver) = oneshot::channel();
        let from = match show {
            Show::History(port) => ReplayFrom::Start(port),
            Show::Missed | Show::Skip => ReplayFrom::Cursor,
        };
        let resync = Resync {
            from,
            setup,
            replayed,
            gate: gate_receiver,
        };
        live.deliver(&link, Control::Resync(Box::new(resync)))
            .await?;
        let current = through.await.unwrap_or_else(|_| Err(daemon::lost()))?;
        // The pump waits for the gate, so nothing changes these meanwhile.
        let Attachment::Attached(state) = *live.shared.attachment.borrow() else {
            return Err(daemon::lost());
        };
        Ok(Started {
            session_id: AcpSessionId::new(live.id.as_str()),
            options: lock(&live.shared.options).clone(),
            state,
            background: lock(&live.shared.background).clone(),
            current,
            gate,
        })
    }

    /// Attaches session `id` and starts its pump; returns once the replay
    /// is through.
    async fn open(
        &self,
        id: SessionId,
        setup: SessionSetup,
        show: Show,
    ) -> Result<Started, AcpError> {
        let port = self.port()?;
        let acp_id = AcpSessionId::new(id.as_str());
        let (inbound, receiver) = mpsc::unbounded_channel();
        self.daemon.route(&id, route(&inbound));
        let response = match self.daemon.attach(&id, /*after*/ None, &setup).await {
            Ok(response) => response,
            Err(error) => {
                self.daemon.unroute(&id);
                return Err(error);
            }
        };
        let options = response.options.clone();
        let state = response.state;
        let background = response.background.clone();
        let shared = Arc::new(Shared {
            options: Mutex::new(options.clone()),
            background: Mutex::new(background.clone()),
            attachment: watch::channel(Attachment::Stale).0,
        });
        let asks = Asks::default();
        let cancels = TurnCancels::default();
        let context = InputContext {
            daemon: Arc::clone(&self.daemon),
            session: id.clone(),
            acp_id: acp_id.clone(),
            port,
            features: self.negotiated.get(),
            placeholders: Arc::clone(&self.sessions.placeholders),
            asks: asks.clone(),
            cancels: cancels.clone(),
        };
        let (replayed, through) = oneshot::channel();
        let (gate, gate_receiver) = oneshot::channel();
        let attacher: Arc<dyn Attacher> = self.daemon.clone();
        // The pump's recovery attaches bring no system prompt: the session
        // keeps the one it has, which another client may have changed since.
        let recovery = SessionSetup {
            system_prompt: None,
            ..setup
        };
        let pump = pump::spawn(
            context,
            attacher,
            (inbound.downgrade(), receiver),
            Arc::clone(&shared),
            recovery,
            &self.herdr,
            Opening {
                response,
                show,
                replayed,
                gate: gate_receiver,
            },
        );
        let live = Arc::new(Live {
            id,
            inbound,
            shared,
            prompt: tokio::sync::Mutex::new(()),
            cancelling: AtomicBool::new(false),
            cancels,
            held: Holds::default(),
            closing: AtomicBool::new(false),
            attaching: tokio::sync::Mutex::new(()),
            pump,
            asks,
        });
        lock(&self.sessions.live).insert(acp_id.0.to_string(), Arc::clone(&live));
        let current = match through.await.unwrap_or_else(|_| Err(daemon::lost())) {
            Ok(current) => current,
            Err(error) => {
                self.sessions.remove(&acp_id.0);
                self.detach(&live, Wait::Prompt).await;
                return Err(error);
            }
        };
        Ok(Started {
            session_id: acp_id,
            options,
            state,
            background,
            current,
            gate,
        })
    }

    /// Has a stale session's pump attach again after its cursor: the events
    /// the host missed show as live, and a reset's history is skipped.
    /// Returns once the replay is through.
    async fn resume(&self, live: &Live) -> Result<(), AcpError> {
        self.daemon.route(&live.id, route(&live.inbound));
        let (replayed, through) = oneshot::channel();
        live.inbound
            .send(Inbound::Control(Control::Resume(replayed)))
            .map_err(|_| daemon::lost())?;
        through.await.unwrap_or_else(|_| Err(daemon::lost()))?;
        Ok(())
    }

    /// `session/set_config_option`.
    pub(super) async fn set_config_option(
        &self,
        request: &SetSessionConfigOptionRequest,
    ) -> Result<SetSessionConfigOptionResponse, AcpError> {
        let live = self.live(&request.session_id).await?;
        let toggles = self.negotiated.get().toggles;
        let current = lock(&live.shared.options).clone();
        let change = options::change(request, &current, toggles)?;
        let options = self.configure(&live, change).await?;
        Ok(SetSessionConfigOptionResponse::new(
            options::config_options(&options, toggles),
        ))
    }

    /// `session/set_mode`.
    pub(super) async fn set_session_mode(
        &self,
        request: &SetSessionModeRequest,
    ) -> Result<SetSessionModeResponse, AcpError> {
        let live = self.live(&request.session_id).await?;
        let change = options::mode_change(&request.mode_id.0)?;
        self.configure(&live, change).await?;
        Ok(SetSessionModeResponse::new())
    }

    async fn configure(
        &self,
        live: &Live,
        change: SessionChange,
    ) -> Result<SessionOptions, AcpError> {
        let link = self.daemon.link().await?;
        let params = SessionConfigureParams {
            session: live.id.clone(),
            change,
        };
        let response = link
            .request::<SessionConfigure>(&params)
            .await
            .map_err(|error| daemon::daemon_error(&error))?;
        let (told, heard) = oneshot::channel();
        let control = Control::Options(Box::new(response.options.clone()), told);
        // A session closed meanwhile has no host to tell.
        if live.deliver(&link, control).await.is_ok() {
            let _ = heard.await;
        }
        Ok(response.options)
    }

    /// Takes a place in open session `id`'s line for an ACP v2 prompt the
    /// connection just read, before it reads the next message, so cancels
    /// read later cover it while it is held.
    pub(super) fn hold(
        &self,
        id: &AcpSessionId,
        cancellation: RequestCancellation,
    ) -> Result<Place, AcpError> {
        Ok(Place::new(self.open_live(id)?, cancellation))
    }

    /// `session/cancel`: drops the session's held prompts and asks the
    /// daemon to stop its turn, which withdraws the turn's open input
    /// requests from the host.
    pub(super) async fn cancel(&self, session_id: &AcpSessionId) {
        if let Some(live) = self.sessions.get(&session_id.0) {
            self.cancel_live(&live).await;
        }
    }

    async fn cancel_live(&self, live: &Live) {
        live.held.cancel();
        live.cancels.cancel();
        live.cancelling.store(true, Ordering::Release);
        self.stop_turn(live).await;
    }

    /// Asks the daemon to stop `live`'s turn under way.
    pub(super) async fn stop_turn(&self, live: &Live) {
        // A closed connection already failed the prompt; the turn runs on in
        // the daemon, as when this process is killed.
        let Some(link) = self.daemon.current().await else {
            return;
        };
        let params = SessionCancelParams {
            session: live.id.clone(),
        };
        if let Err(error) = link.request::<SessionCancel>(&params).await {
            tracing::warn!(%error, "could not cancel an ACP session's turn");
        }
    }
}

/// The router's route to a pump reading `inbound`.
fn route(inbound: &mpsc::UnboundedSender<Inbound>) -> SessionRoute {
    let inbound = inbound.clone();
    Box::new(move |routed| {
        let _ = inbound.send(Inbound::Routed(routed));
    })
}

/// A turn is in progress: running, queued, or waiting for an answer.
fn busy(state: JobState) -> bool {
    matches!(
        state,
        JobState::Running | JobState::Queued | JobState::WaitingForInput
    )
}

fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
    mutex.lock().unwrap_or_else(PoisonError::into_inner)
}