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
//! Rho's subagents as ACP v2 child sessions.
//!
//! A subagent the `agent` tool starts is background work of its parent
//! session, which [`super::background`] announces with a `subagent_update`
//! on the parent before the first `state_update` that lists it. A subagent
//! on Rho's runtime writes its own session, and the daemon streams a run's
//! session while it runs (`rho/session/observe`), so this module relays
//! that stream to the host as the child's own updates, under the child's
//! session id:
//!
//! - the child's `cwd` and `additionalDirectories`, which the observe
//!   answers with, on the parent's `subagent_update` before anything of
//!   the child's, and its options (its model among them) as its
//!   `config_option_update`, each `select` limited to its current value,
//!   since a host may not set a child's options;
//! - the task the parent gave it as a `session_message` from the parent,
//!   not a user message;
//! - its messages, thoughts and tool calls as any session's;
//! - its state as its own `state_update`, each one mirrored as the `state`
//!   of the parent's `subagent_update` before the next.
//!
//! The relay owns a child's state: the background list's finalization of a
//! child with a session only withdraws its `cancel` capability
//! ([`super::background::changes`]). A run that ends before the relay
//! could observe it, or whose stream ends without saying how, ends as the
//! parent's background list says it did ([`Subagents::ended`]). A relay
//! that loses the daemon reports the child `unknown`.
//!
//! The registry also records which children each parent announced on this
//! connection: the methods a host may not send for a child are refused for
//! them, and a subagent's question is put to the host under the child
//! ([`AcpClientPort::child_session`]). Closing or resuming the parent
//! forgets its children and stops their relays; a resume announces them
//! again and follows each one that still runs ([`Subagents::resume`]).
//!
//! [`AcpClientPort::child_session`]: crate::app::acp::AcpClientPort::child_session

use std::{
    collections::HashMap,
    sync::{Arc, Mutex, MutexGuard, PoisonError},
    time::Duration,
};

use agent_client_protocol::{v1::schema as v1, v2::schema as v2};
use agent_client_protocol::{v2::ConnectionTo as V2ConnectionTo, Client, Error as AcpError};
use rho_protocol::{
    methods::{JobList, SessionObserve},
    BackgroundItem, BackgroundStatus, BackgroundWork, ClientError, DetachReason, ErrorCode,
    JobKind, JobListParams, JobState, JobSummary, Replay, SessionAttachResponse, SessionEvent,
    SessionId, SessionObserveParams, SessionOptions,
};
use tokio::{
    sync::{mpsc, oneshot},
    task::JoinHandle,
};

use super::{background::subagent_idle, bridge, port::V2Port, requests};
use crate::app::{
    acp::{
        host_features::{HostFeatures, Toggles},
        prompt,
        sessions::Attacher,
        updates::{self, Delivery, Updates},
        Foreground, TurnEnd,
    },
    daemon_client::{Daemon, DaemonError, Part, Routed, StreamPosition},
};

/// How long a relay waits to ask again to observe a child whose run has
/// yet to open its session: the interval the session pump reads processes'
/// output at (`sessions::output::READ_EVERY`, whose cost is measured there).
const OBSERVE_AGAIN: Duration = Duration::from_millis(250);

/// The id a child session has on ACP: its own Rho session's, or its run's
/// when its runtime keeps no Rho session.
pub(super) fn child_id(run: &str, session: Option<&SessionId>) -> String {
    session.map_or_else(|| run.to_owned(), |session| session.as_str().to_owned())
}

/// One connection's children, by their ACP id.
pub(super) struct Subagents {
    daemon: Arc<Daemon>,
    /// What the host accepts, which a child's updates are mapped for.
    features: Mutex<HostFeatures>,
    children: Mutex<HashMap<String, Child>>,
}

/// A child announced on this connection.
struct Child {
    /// The ACP id of the session that announced it.
    parent: String,
    /// The relay of its session's stream, while one runs.
    relay: Option<JoinHandle<()>>,
    state: Arc<Mutex<ChildState>>,
}

/// What the host was told of a child's state, and what would tell it how
/// the child's work ended. Locked while a state is sent, so the child's
/// own copy and the parent's mirror go out together.
#[derive(Default)]
struct ChildState {
    told: Option<Told>,
    /// How its run ended, as the parent's background list or the daemon's
    /// job list says.
    ended: Option<BackgroundStatus>,
    /// Whether its relay stopped, so no `turn_ended` of its stream is to
    /// come.
    unrelayed: bool,
    /// Whether its parent forgot it, after which the host hears nothing
    /// more of it: an aborted relay may still be handling an event.
    released: bool,
}

impl ChildState {
    /// The `idle` a child is due once both its relay stopped and its
    /// parent's list said how its run ended, unless it was told already.
    fn settled(&self) -> Option<v2::StateUpdate> {
        match (self.told, self.unrelayed, self.ended) {
            (Some(Told::Idle), _, _) => None,
            (_, true, Some(status)) => Some(subagent_idle(status)),
            (_, _, _) => None,
        }
    }
}

impl Drop for Child {
    fn drop(&mut self) {
        if let Some(relay) = self.relay.take() {
            relay.abort();
        }
    }
}

/// Whether a resume replayed its session's history.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Resumed {
    /// `replayFrom: start`: each child replays its own, too.
    Replayed,
    /// No replay: the host hears what is current only.
    Current,
}

/// Whether a child's relay port sends history (see [`V2Port::child`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum ChildReplay {
    History,
    Live,
}

impl Subagents {
    pub(super) fn new(daemon: Arc<Daemon>) -> Self {
        Self {
            daemon,
            features: Mutex::default(),
            children: Mutex::default(),
        }
    }

    /// Takes what the host accepts, as `initialize` negotiated it.
    pub(super) fn negotiated(&self, features: HostFeatures) {
        *lock(&self.features) = features;
    }

    /// Records that `parent` announced `child`; a child keeps its first
    /// parent.
    pub(super) fn announced(&self, parent: &v2::SessionId, child: &v2::SessionId) {
        lock(&self.children)
            .entry(child.0.to_string())
            .or_insert_with(|| Child {
                parent: parent.0.to_string(),
                relay: None,
                state: Arc::default(),
            });
    }

    /// Whether `session` is a child announced on this connection, which
    /// the host may not prompt, configure, resume, close, or delete.
    pub(super) fn is_child(&self, session: &str) -> bool {
        lock(&self.children).contains_key(session)
    }

    /// Whether `parent` announced `child`.
    pub(super) fn is_child_of(&self, parent: &str, child: &str) -> bool {
        lock(&self.children)
            .get(child)
            .is_some_and(|known| known.parent == parent)
    }

    /// Relays each running subagent of `work` that writes a Rho session and
    /// is not relayed yet, once `parent` announced it.
    pub(super) fn follow(
        &self,
        cx: &V2ConnectionTo<Client>,
        parent: &v2::SessionId,
        work: &[BackgroundWork],
    ) {
        for (child, session) in sessions(work) {
            self.relay(cx, parent, child, session, Show::Live);
        }
    }

    /// Relays `child`, which `parent` linked, unless it was relayed before.
    pub(super) fn linked(
        &self,
        cx: &V2ConnectionTo<Client>,
        parent: &v2::SessionId,
        child: String,
        session: SessionId,
    ) {
        let relayed = lock(&self.children)
            .get(&child)
            .is_some_and(|known| known.relay.is_some());
        if !relayed {
            self.relay(cx, parent, child, session, Show::Live);
        }
    }

    /// Takes how child `child` of `parent` ended, as the parent's background
    /// list says: the child is told so unless its relay will tell it, or
    /// told it already.
    pub(super) fn ended(
        &self,
        cx: &V2ConnectionTo<Client>,
        parent: &v2::SessionId,
        child: &str,
        status: BackgroundStatus,
    ) {
        let Some(state) = lock(&self.children)
            .get(child)
            .map(|known| Arc::clone(&known.state))
        else {
            return;
        };
        let mut state = lock(&state);
        state.ended = Some(status);
        if let Some(idle) = state.settled() {
            let child = v2::SessionId::new(child);
            tell(cx, parent, &child, &mut state, Told::Idle, idle);
        }
    }

    /// Forgets `parent`'s children and stops their relays, as closing the
    /// parent or resuming it does: after a close the host may no longer
    /// name them, and a resume announces them again.
    pub(super) fn release(&self, parent: &str) {
        let released: Vec<Child> = {
            let mut children = lock(&self.children);
            let ids: Vec<String> = children
                .iter()
                .filter(|(_, child)| child.parent == parent)
                .map(|(id, _)| id.clone())
                .collect();
            ids.iter().filter_map(|id| children.remove(id)).collect()
        };
        for child in &released {
            lock(&child.state).released = true;
        }
        // Each stops its relay as it drops, outside the lock.
        drop(released);
    }

    /// The children of a resume of `parent`, which announced them again
    /// before this: relays each that runs in `work` again, from its start
    /// as history when the resume replayed, and otherwise from now. A
    /// replay waits for each child's history and gives every child it
    /// announced its own `replay_complete`, all before the response.
    pub(super) async fn resume(
        &self,
        cx: &V2ConnectionTo<Client>,
        parent: &v2::SessionId,
        work: &[BackgroundWork],
        resumed: Resumed,
    ) {
        let running: HashMap<String, SessionId> = sessions(work).collect();
        let announced: Vec<String> = lock(&self.children)
            .iter()
            .filter(|(_, child)| child.parent == parent.0.as_ref())
            .map(|(id, _)| id.clone())
            .collect();
        let mut caught_up = Vec::new();
        for child in announced {
            match (running.get(&child), resumed) {
                (Some(session), Resumed::Replayed) => {
                    let (told, waited) = oneshot::channel();
                    let history = Show::History {
                        port: V2Port::child(cx.clone(), ChildReplay::History),
                        caught_up: told,
                    };
                    self.relay(cx, parent, child, session.clone(), history);
                    caught_up.push(waited);
                }
                (Some(session), Resumed::Current) => {
                    self.relay(cx, parent, child, session.clone(), Show::Skip);
                }
                (None, Resumed::Replayed) => {
                    send(cx, &v2::SessionId::new(child), replay_complete());
                }
                (None, Resumed::Current) => {}
            }
        }
        for waited in caught_up {
            // A relay that stopped first ended its history as it did.
            let _ = waited.await;
        }
    }

    /// Starts relaying `child`'s `session`, showing the replay of its first
    /// observe as `show` says, unless a relay of it still runs: that one
    /// shows the child live, so a history asked of it is over at once. A
    /// relay that takes over from one that stopped shows no live replay
    /// again.
    fn relay(
        &self,
        cx: &V2ConnectionTo<Client>,
        parent: &v2::SessionId,
        child: String,
        session: SessionId,
        show: Show,
    ) {
        let mut children = lock(&self.children);
        let Some(known) = children.get_mut(&child) else {
            return;
        };
        let child = v2::SessionId::new(child);
        let show = match &known.relay {
            Some(relay) if !relay.is_finished() => {
                show.over(cx, &child);
                return;
            }
            // One that stopped, as when it lost the daemon, showed what the
            // child did until then.
            Some(_) => match show {
                Show::Live => Show::Skip,
                show @ (Show::Skip | Show::History { .. }) => show,
            },
            None => show,
        };
        let state = Arc::clone(&known.state);
        lock(&state).unrelayed = false;
        let relay = Relay {
            daemon: Arc::clone(&self.daemon),
            state,
            port: V2Port::child(cx.clone(), ChildReplay::Live),
            show,
            parent: parent.clone(),
            child,
            session,
            updates: Updates::new(*lock(&self.features)),
            position: None,
            pending: None,
        };
        known.relay = Some(tokio::spawn(relay.run()));
    }
}

/// The running subagents of `work` that write a Rho session, by ACP id.
fn sessions(work: &[BackgroundWork]) -> impl Iterator<Item = (String, SessionId)> + '_ {
    work.iter()
        .filter(|work| work.status.is_running())
        .filter_map(|work| match &work.item {
            BackgroundItem::Subagent {
                run,
                session: Some(session),
            } => Some((child_id(run, Some(session)), session.clone())),
            _ => None,
        })
}

/// A child's state, as its own `state_update` and the parent's mirror tell
/// it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Told {
    Running,
    RequiresAction,
    Idle,
    Unknown,
}

/// What a relay shows of an observe's replay. The events after it are
/// live, and show as such.
enum Show {
    /// As live updates: the host has seen none of it, or missed it.
    Live,
    /// Nothing: the host has it, or a resume without replay reports what
    /// is current only.
    Skip,
    /// As history, through `port`, which the child's `replay_complete`
    /// ends, then its current options and state; `caught_up` then tells
    /// the resume waiting for it.
    History {
        port: V2Port,
        caught_up: oneshot::Sender<()>,
    },
}

impl Show {
    /// What an observe again after the cursor shows of its `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::Live,
            Replay::Reset => Self::Skip,
        }
    }

    /// Ends a history no relay will show: `child`'s `replay_complete`, then
    /// the resume hears it is through.
    fn over(self, cx: &V2ConnectionTo<Client>, child: &v2::SessionId) {
        if let Self::History { caught_up, .. } = self {
            send(cx, child, replay_complete());
            let _ = caught_up.send(());
        }
    }
}

/// The task that relays one child's stream.
struct Relay {
    daemon: Arc<Daemon>,
    state: Arc<Mutex<ChildState>>,
    port: V2Port,
    /// What the current observe's replay shows.
    show: Show,
    parent: v2::SessionId,
    child: v2::SessionId,
    session: SessionId,
    updates: Updates,
    /// Where the stream is, once observed.
    position: Option<StreamPosition>,
    /// The child's options and state as the observe began, which a replay
    /// reports once the child's history is over.
    pending: Option<(SessionOptions, JobState)>,
}

/// What a relay does once its observe ends.
enum Next {
    /// Observe again after the cursor: the daemon dropped the observe as
    /// it fell behind.
    Again,
    Stop(Stopped),
}

/// Why a relay stopped.
#[derive(Clone, Copy)]
enum Stopped {
    /// The run ended, or its session cannot be followed.
    Ended,
    /// The daemon is gone.
    Lost,
    /// Its parent forgot the child.
    Released,
}

impl Relay {
    async fn run(mut self) {
        // A relay of the child that a resume or close aborted may have left
        // the daemon following it for this connection, and the events its
        // forwarder queued would come ahead of this observe's replay.
        if let Err(error) = Attacher::detach(&*self.daemon, &self.session).await {
            tracing::debug!(%error, "could not stop following a subagent's session");
        }
        loop {
            let routed = self.daemon.route_channel(&self.session);
            let params = SessionObserveParams {
                session: self.session.clone(),
                after: self
                    .position
                    .as_ref()
                    .and_then(StreamPosition::cursor)
                    .cloned(),
            };
            let next = match self.daemon.request::<SessionObserve>(&params).await {
                Ok(response) => {
                    self.begin(&response);
                    self.read(routed).await
                }
                // The run has yet to open its session, so it has no history
                // a resume would wait for.
                Err(DaemonError::Request(error))
                    if error.error_code() == Some(ErrorCode::SessionBusy) =>
                {
                    self.daemon.unroute(&self.session);
                    self.history_over();
                    tokio::time::sleep(OBSERVE_AGAIN).await;
                    Next::Again
                }
                Err(
                    error @ (DaemonError::Unreachable(_)
                    | DaemonError::Request(ClientError::Closed | ClientError::Frame(_))),
                ) => {
                    tracing::debug!(%error, "could not observe a subagent's session");
                    Next::Stop(Stopped::Lost)
                }
                Err(DaemonError::Request(error)) => {
                    tracing::debug!(%error, "could not observe a subagent's session");
                    Next::Stop(Stopped::Ended)
                }
            };
            match next {
                Next::Again => {}
                Next::Stop(Stopped::Released) => return,
                Next::Stop(stopped) => {
                    self.daemon.unroute(&self.session);
                    self.history_over();
                    if matches!(stopped, Stopped::Ended) {
                        self.learn_how_it_ended().await;
                    }
                    self.stopped(stopped);
                    return;
                }
            }
        }
    }

    /// Asks the daemon how the child's run ended, unless the host was told
    /// or the parent's background list said: a run that ended before its
    /// session could be followed has a saved replay that does not say, and
    /// one that started and ended between two of its parent's background
    /// reports is never listed. A rare case, so the job list's size is
    /// paid only then.
    async fn learn_how_it_ended(&self) {
        {
            let state = lock(&self.state);
            if state.told == Some(Told::Idle) || state.ended.is_some() {
                return;
            }
        }
        let jobs = match self.daemon.request::<JobList>(&JobListParams {}).await {
            Ok(response) => response.jobs,
            Err(error) => {
                tracing::debug!(%error, "could not ask how a subagent's run ended");
                return;
            }
        };
        if let Some(status) = run_ended(&jobs, &self.session) {
            lock(&self.state).ended.get_or_insert(status);
        }
    }

    /// Ends the relay: a child whose work it did not see end ends as the
    /// parent's background list says, now if it said so already, or else
    /// once it does; one the daemon lost with it is `unknown`.
    fn stopped(&self, stopped: Stopped) {
        let mut state = lock(&self.state);
        state.unrelayed = true;
        let (told, update) = match (state.settled(), stopped) {
            (Some(idle), _) => (Told::Idle, idle),
            (None, Stopped::Lost) if state.told != Some(Told::Idle) => (
                Told::Unknown,
                v2::StateUpdate::Unknown(v2::UnknownStateUpdate::new()),
            ),
            (None, Stopped::Lost | Stopped::Ended | Stopped::Released) => return,
        };
        self.tell_locked(&mut state, told, update);
    }

    /// Takes the observe's `response`: the child's directories go on the
    /// parent's association at once, and its options and state once a
    /// replay of its history is over. An observe again after the cursor
    /// shows its replay as [`Show::resumed`] says.
    fn begin(&mut self, response: &SessionAttachResponse) {
        match &mut self.position {
            Some(position) => {
                position.reattached(response);
                self.history_over();
                self.show = Show::resumed(response.replay);
            }
            None => self.position = Some(StreamPosition::attached(response)),
        }
        let directories: Vec<v2::AbsolutePath> = response
            .options
            .added_dirs
            .iter()
            .cloned()
            .map(v2::AbsolutePath::new)
            .collect();
        let placed = v2::SubagentUpdate::new(self.child.clone())
            .cwd(v2::AbsolutePath::new(response.workspace.clone()))
            .additional_directories(directories);
        send(
            self.port.cx(),
            &self.parent,
            v2::SessionUpdate::SubagentUpdate(placed),
        );
        self.pending = Some((response.options.clone(), response.state));
        if !matches!(self.show, Show::History { .. }) {
            self.current();
        }
    }

    /// Reports the child's options and state as the observe began.
    fn current(&mut self) {
        let Some((options, state)) = self.pending.take() else {
            return;
        };
        self.options(&options);
        self.busy(Foreground::of(state));
    }

    async fn read(&mut self, mut routed: mpsc::UnboundedReceiver<Routed>) -> Next {
        if !self
            .position
            .as_ref()
            .is_some_and(StreamPosition::replaying)
        {
            self.history_over();
        }
        while let Some(next) = routed.recv().await {
            match next {
                Routed::Event { seq, event } => {
                    if lock(&self.state).released {
                        return Next::Stop(Stopped::Released);
                    }
                    self.updates.observe(&event);
                    let Some(position) = self.position.as_mut() else {
                        return Next::Stop(Stopped::Ended);
                    };
                    match position.observe(seq) {
                        Part::Live => self.live(&event),
                        Part::Replayed { left, .. } => {
                            match &self.show {
                                Show::Live => self.live(&event),
                                Show::History { .. } => self.replayed(&event),
                                Show::Skip => {}
                            }
                            if left == 0 {
                                self.history_over();
                            }
                        }
                    }
                }
                Routed::Detached(DetachReason::Lagged) => return Next::Again,
                Routed::Detached(DetachReason::DaemonStopping | DetachReason::Restarting)
                | Routed::Lost => return Next::Stop(Stopped::Lost),
                // The run ended, or its session is gone.
                Routed::Detached(_) => return Next::Stop(Stopped::Ended),
            }
        }
        Next::Stop(Stopped::Ended)
    }

    /// Ends a resume's replay of the child, if one is under way: its
    /// `replay_complete`, then its current options and state, and then
    /// the resume hears it is through. What follows shows live.
    fn history_over(&mut self) {
        let show = std::mem::replace(&mut self.show, Show::Live);
        let Show::History { caught_up, .. } = show else {
            self.show = show;
            return;
        };
        send(self.port.cx(), &self.child, replay_complete());
        // The resume answers as soon as it hears, so the current options
        // and state go out first.
        self.current();
        let _ = caught_up.send(());
    }

    /// Relays `event` as it happens.
    fn live(&mut self, event: &SessionEvent) {
        match event {
            SessionEvent::UserMessage { .. } => {
                let message = self.task(event);
                send(self.port.cx(), &self.child, message);
            }
            SessionEvent::State { state, .. } => self.busy(Foreground::of(*state)),
            SessionEvent::TurnEnded { outcome, .. } => {
                // The answer text no chunk showed comes before the idle.
                self.mapped(event, Delivery::Live);
                let end = TurnEnd::Ended(prompt::stop_reason(outcome.clone()));
                let idle = v2::IdleStateUpdate::new().stop_reason(requests::stop_reason(&end));
                self.tell_locked(
                    &mut lock(&self.state),
                    Told::Idle,
                    v2::StateUpdate::Idle(idle),
                );
            }
            SessionEvent::OptionsChanged { options } => self.options(options),
            // The child's questions are its parent's requests, and its own
            // background work is not shown.
            SessionEvent::InputRequested { .. }
            | SessionEvent::InputResolved { .. }
            | SessionEvent::Background { .. } => {}
            event => self.mapped(event, Delivery::Live),
        }
    }

    /// Relays `event` of a resume's replay as history, which holds no
    /// states.
    fn replayed(&mut self, event: &SessionEvent) {
        match event {
            SessionEvent::UserMessage { .. } => {
                let message = self.task(event);
                if let Show::History { port, .. } = &self.show {
                    let replayed = v2::UpdateSessionNotification::new(self.child.clone(), message)
                        .meta(updates::replay_meta());
                    if let Err(error) = port.cx().send_notification(replayed) {
                        tracing::debug!(%error, "could not replay a subagent's task over ACP v2");
                    }
                }
            }
            SessionEvent::State { .. }
            | SessionEvent::OptionsChanged { .. }
            | SessionEvent::InputRequested { .. }
            | SessionEvent::InputResolved { .. }
            | SessionEvent::Background { .. } => {}
            // A turn's end holds no state, only the answer text no chunk
            // showed.
            event => self.mapped(event, Delivery::Replay),
        }
    }

    /// Sends `event` as Rho's adapter maps it for any session, through the
    /// history's port for a replay.
    fn mapped(&mut self, event: &SessionEvent, delivery: Delivery) {
        let child = v1::SessionId::new(self.child.0.clone());
        let mapped = self.updates.map(event);
        let port = match (&self.show, delivery) {
            (Show::History { port, .. }, Delivery::Replay) => port,
            _ => &self.port,
        };
        for update in mapped {
            port.forward(updates::notification(&child, update, delivery));
        }
    }

    /// The `session_message` a user message of the child's stream is: the
    /// task its parent gave it.
    fn task(&mut self, event: &SessionEvent) -> v2::SessionUpdate {
        let mut id = None;
        let mut content = Vec::new();
        for update in self.updates.map(event) {
            if let v1::SessionUpdate::UserMessageChunk(chunk) = update {
                id = id.or(chunk.message_id);
                match bridge::<_, v2::ContentBlock>(&chunk.content) {
                    Ok(block) => content.push(block),
                    Err(error) => tracing::warn!(%error, "could not report a subagent's task"),
                }
            }
        }
        let id = id.map_or_else(|| format!("{}-task", self.child.0), |id| id.0.to_string());
        v2::SessionUpdate::SessionMessage(
            v2::SessionMessage::new(id)
                .sender_session_id(self.parent.clone())
                .recipient_session_id(self.child.clone())
                .content(content),
        )
    }

    fn options(&self, options: &SessionOptions) {
        match child_options(options) {
            Ok(update) => send(self.port.cx(), &self.child, update),
            Err(error) => tracing::warn!(%error, "could not report a subagent's options"),
        }
    }

    /// Tells the host the child is busy as `foreground` says; the turn's
    /// end says how its work stopped, so an idle state tells nothing.
    fn busy(&self, foreground: Foreground) {
        let (told, state) = match foreground {
            Foreground::Running => (
                Told::Running,
                v2::StateUpdate::Running(v2::RunningStateUpdate::new()),
            ),
            Foreground::RequiresAction => (
                Told::RequiresAction,
                v2::StateUpdate::RequiresAction(v2::RequiresActionStateUpdate::new()),
            ),
            Foreground::Idle => return,
        };
        self.tell_locked(&mut lock(&self.state), told, state);
    }

    fn tell_locked(&self, state: &mut ChildState, told: Told, update: v2::StateUpdate) {
        tell(
            self.port.cx(),
            &self.parent,
            &self.child,
            state,
            told,
            update,
        );
    }
}

/// How the subagent run that wrote `session` ended, as `jobs` says, once it
/// did.
fn run_ended(jobs: &[JobSummary], session: &SessionId) -> Option<BackgroundStatus> {
    let job = jobs
        .iter()
        .rev()
        .find(|job| job.kind == JobKind::Subagent && job.session.as_ref() == Some(session))?;
    match job.state {
        JobState::Completed => Some(BackgroundStatus::Completed),
        JobState::Failed | JobState::TimedOut => Some(BackgroundStatus::Failed),
        JobState::Cancelled => Some(BackgroundStatus::Cancelled),
        JobState::Interrupted | JobState::Unknown => Some(BackgroundStatus::Unknown),
        JobState::Idle | JobState::Queued | JobState::Running | JobState::WaitingForInput => None,
        // A state a newer daemon sends.
        _ => Some(BackgroundStatus::Unknown),
    }
}

/// Tells the host child `child` of `parent` is in state `update`, which is
/// `told`, on the child and then as the parent's mirror, unless that is
/// what it was told last.
fn tell(
    cx: &V2ConnectionTo<Client>,
    parent: &v2::SessionId,
    child: &v2::SessionId,
    state: &mut ChildState,
    told: Told,
    update: v2::StateUpdate,
) {
    if state.released || state.told == Some(told) {
        return;
    }
    state.told = Some(told);
    send(cx, child, v2::SessionUpdate::StateUpdate(update.clone()));
    let mirror = v2::SubagentUpdate::new(child.clone()).state(update);
    send(cx, parent, v2::SessionUpdate::SubagentUpdate(mirror));
}

/// A child's `config_option_update`: its options as any session's, each
/// `select` offering only its current value, as the host may not change
/// them.
fn child_options(options: &SessionOptions) -> Result<v2::SessionUpdate, AcpError> {
    let options = requests::setup(options, Toggles::Select)?
        .config_options
        .into_iter()
        .map(|mut option| {
            if let v2::SessionConfigKind::Select(select) = &mut option.kind {
                let current = select.current_value.clone();
                let choices = match &select.options {
                    v2::SessionConfigSelectOptions::Grouped(groups) => {
                        groups.iter().flat_map(|group| &group.options).collect()
                    }
                    v2::SessionConfigSelectOptions::Ungrouped(choices) => choices.iter().collect(),
                    // A shape a newer schema adds.
                    _ => Vec::new(),
                };
                let kept: Vec<_> = choices
                    .into_iter()
                    .filter(|choice| choice.value == current)
                    .cloned()
                    .collect();
                if kept.is_empty() {
                    tracing::warn!(
                        option = %option.config_id.0,
                        "a subagent's option offers no choice for its current value"
                    );
                } else {
                    select.options = kept.into();
                }
            }
            option
        })
        .collect();
    Ok(v2::SessionUpdate::ConfigOptionUpdate(
        v2::ConfigOptionUpdate::new(options),
    ))
}

fn replay_complete() -> v2::SessionUpdate {
    v2::SessionUpdate::ReplayComplete(v2::ReplayComplete::new())
}

/// Sends `update` on `session`; a host that is gone hears nothing more.
/// Nothing a relay sends announces a child.
fn send(cx: &V2ConnectionTo<Client>, session: &v2::SessionId, update: v2::SessionUpdate) {
    let notification = v2::UpdateSessionNotification::new(session.clone(), update);
    if let Err(error) = cx.send_notification(notification) {
        tracing::debug!(%error, "could not send a subagent's update over ACP v2");
    }
}

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

#[cfg(test)]
#[path = "subagents_tests.rs"]
mod tests;