rho-coding-agent 3.13.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
//! Registry of in-process delegated agent runs.
//!
//! Spawn, observe, stop, follow-up, cost accounting, host-input bind, notices,
//! and rail summaries live here so tools call a manager API instead of
//! executor internals. A parent's messages to its runs, which steer a
//! running run and follow up a finished one, are in `message`.

use std::{
    collections::HashMap,
    path::{Path, PathBuf},
    sync::{Arc, Mutex},
    time::{Duration, Instant},
};

use {
    crate::agent::AgentDefinition,
    crate::app::{
        agent_executor::{
            AgentExecutor, AgentLaunchRequest, AgentRunHandle, ChildConversation, DelegatedBinding,
            LaunchWorkspace,
        },
        runtime_child_host::{Announce, RecordedChildren},
        subagent_host_input::{SubagentHostInputBridge, SubagentHostInputRequest},
        subagent_messaging::{SubagentNotice, SubagentNoticeBridge},
        subagent_pool::{child_events, ChildObserver, StartedSubagent, SubagentPool},
    },
    crate::session::{tree::SubagentLink, SessionPersistence},
    crate::subagent::{self, RunStatus},
};

pub(crate) use super::subagent_messaging::ValidatedMessage;

mod message;

const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(10);

#[derive(Clone, Debug)]
pub struct SubagentSnapshot {
    pub id: String,
    pub agent_id: String,
    pub title: Option<String>,
    pub elapsed: Duration,
    pub status: RunStatus,
    pub done: bool,
    pub prior_notices: Vec<String>,
    /// Whether the run saves its own session, as its parent did when it
    /// started. A Claude session it did not save cannot be resumed.
    pub persistence: SessionPersistence,
}

/// A child a session has yet to be given the result of; see
/// [`SubagentManager::background`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct BackgroundChild {
    pub(crate) run: String,
    pub(crate) title: String,
    /// The child's own session, when it has one: see [`AgentRunHandle::session`].
    pub(crate) session: Option<rho_sdk::SessionId>,
    /// `Running` until the run ended, then how it ended.
    pub(crate) state: subagent::RunState,
}

/// Stable run identity and its best available task label for host presentation.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct SubagentTaskIdentity {
    pub run_id: String,
    pub agent_id: String,
    pub task: String,
    /// The run's own session, when it has one: see [`AgentRunHandle::session`].
    pub session: Option<rho_sdk::SessionId>,
}

/// The tool call that started a run, and what the run showed as when the
/// call finished.
struct Starter {
    call: String,
    title: Option<String>,
}

struct AgentEntry {
    agent_id: String,
    task_fallback: Option<String>,
    started: Instant,
    handle: AgentRunHandle,
    /// The parent session the run reports to.
    session_id: String,
    /// Whether the run saves its own session.
    persistence: SessionPersistence,
    observed: bool,
    explicitly_observed: bool,
    /// The tool call that started the run, when one did.
    started_by: Option<Starter>,
    /// What the run launched with, which a follow-up launches with again;
    /// `None` only for a run a test registers without launching it.
    launch: Option<RunLaunch>,
}

/// What a run launched with, besides its prompt, which a follow-up of the
/// run launches with again.
#[derive(Clone)]
struct RunLaunch {
    binding: DelegatedBinding,
    parent_session_id: rho_sdk::SessionId,
    parent_workspace: Option<PathBuf>,
    persistence: SessionPersistence,
    output_file: PathBuf,
    workspace: LaunchWorkspace,
    /// The workspace the run is listed in: its parent's, or its worktree.
    works_in: PathBuf,
    /// Where the parent's subagents' runs go, which the children the run's
    /// agent starts on its own share.
    placement: subagent::RunPlacement,
    /// The workspace the run index files those children's runs under
    /// (`subagent::reserve_run_directory`): the parent's own, as for its
    /// subagents', even for a run in a worktree.
    indexed_under: PathBuf,
}

impl RunLaunch {
    /// The request that launches run `run_id` with `prompt`, holding
    /// `conversation`.
    fn request(
        self,
        run_id: &str,
        prompt: &str,
        events: Option<crate::app::subagent_pool::ChildEventSender>,
        conversation: ChildConversation,
    ) -> AgentLaunchRequest {
        // Only a run its host follows can tell it of its agent's children.
        let runtime_children = events.clone().map(|events| RecordedChildren {
            works_for: self.parent_session_id.clone(),
            placement: self.placement,
            workspace: self.works_in,
            indexed_under: self.indexed_under,
            announce: Announce::Events(events),
        });
        AgentLaunchRequest {
            binding: self.binding,
            prompt: prompt.to_owned(),
            run_id: run_id.to_owned(),
            parent_session_id: self.parent_session_id,
            parent_workspace: self.parent_workspace,
            persistence: self.persistence,
            output_file: self.output_file,
            events,
            runtime_children,
            workspace: self.workspace,
            conversation,
        }
    }
}

impl AgentEntry {
    /// The label shown for the run: its `title`, when it reported one,
    /// else the task it was given.
    fn display_title(&self, title: Option<String>) -> String {
        self.shown_title(title)
            .unwrap_or_else(|| "Delegated task".into())
    }

    /// The run's `title`, when it reported one that is not blank, else the
    /// task it was given, if any.
    fn shown_title(&self, title: Option<String>) -> Option<String> {
        title
            .filter(|title| !title.trim().is_empty())
            .or_else(|| self.task_fallback.clone())
    }

    fn snapshot(&self, id: &str) -> SubagentSnapshot {
        let status = self.handle.status();
        let elapsed = status
            .elapsed_duration(subagent::unix_now_secs())
            .unwrap_or_else(|| self.started.elapsed());
        SubagentSnapshot {
            id: id.to_string(),
            agent_id: self.agent_id.clone(),
            title: status.title.clone(),
            elapsed,
            done: self.handle.is_complete() && status.state.is_terminal(),
            status,
            prior_notices: Vec::new(),
            persistence: self.persistence,
        }
    }
}

/// A worktree being added for one delegated run, in a task of its own so
/// giving up on it never kills git midway, which would leave a worktree git
/// keeps locked. Dropped before [`Self::added`] returns, as a cancelled
/// `agent` call drops it, it lets git finish and discards what git made.
pub(crate) struct AddingWorktree(
    Option<tokio::task::JoinHandle<anyhow::Result<crate::worktree::Added>>>,
);

impl AddingWorktree {
    /// The worktree, once git has added it.
    pub(crate) async fn added(mut self) -> anyhow::Result<crate::worktree::Added> {
        let task = self.0.as_mut().expect("worktree task is taken only here");
        let added = task.await;
        self.0 = None;
        added?
    }
}

impl Drop for AddingWorktree {
    fn drop(&mut self) {
        let Some(task) = self.0.take() else {
            return;
        };
        let Ok(runtime) = tokio::runtime::Handle::try_current() else {
            return;
        };
        runtime.spawn(async move {
            let Ok(Ok(added)) = task.await else {
                return;
            };
            if let Err(error) = crate::worktree::discard(&added.worktree).await {
                tracing::warn!(
                    path = %added.worktree.path.display(),
                    branch = %added.worktree.branch,
                    %error,
                    "could not discard the worktree of a cancelled agent call"
                );
            }
        });
    }
}

#[derive(Clone, Debug)]
pub struct SubagentNotification {
    pub snapshot: SubagentSnapshot,
}

#[derive(Clone)]
pub struct SubagentManager {
    inner: Arc<Mutex<HashMap<String, AgentEntry>>>,
    executor: AgentExecutor,
    /// Notified each time a run of this manager ends.
    ended: Arc<tokio::sync::Notify>,
    /// Notified each time a run of this manager is registered.
    started: Arc<tokio::sync::Notify>,
    parent: Arc<Mutex<ParentBinding>>,
    /// Hears of each run this manager starts, when the host shares its
    /// pool (see `subagent_pool`).
    observer: Option<Arc<dyn ChildObserver>>,
    /// Where worktrees for `worktree: true` runs go in place of the rho
    /// home's `worktrees` directory, where session worktrees go and the
    /// daemon's cleanup looks: a directory a test gives one of its own.
    worktree_root: Option<PathBuf>,
}

/// The session a manager's subagents report to.
#[derive(Clone)]
struct ParentBinding {
    /// Where the subagents' run artifacts go.
    placement: subagent::RunPlacement,
    /// The workspace the parent is saved in, `None` while it has no file.
    /// Each subagent's session records it with the parent's id.
    workspace: Option<PathBuf>,
    /// Whether the subagents' own sessions are saved: not when their
    /// parent's is not, since a child of nothing on disk could never be
    /// reached or deleted with it.
    persistence: SessionPersistence,
}

impl SubagentManager {
    /// A manager whose runs take capacity from `pool`, and report to its
    /// observer when it has one.
    pub(crate) fn new(
        config: crate::config::Config,
        config_path: PathBuf,
        cwd: PathBuf,
        pool: SubagentPool,
    ) -> Self {
        let (concurrency, observer) = pool.into_parts(config.agent_concurrency);
        Self {
            inner: Arc::new(Mutex::new(HashMap::new())),
            executor: AgentExecutor::new(
                config,
                config_path,
                cwd,
                concurrency,
                SubagentHostInputBridge::new(),
                SubagentNoticeBridge::new(),
            ),
            ended: Arc::new(tokio::sync::Notify::new()),
            started: Arc::new(tokio::sync::Notify::new()),
            parent: Arc::new(Mutex::new(ParentBinding {
                placement: subagent::RunPlacement::parentless(),
                workspace: None,
                persistence: SessionPersistence::Saved,
            })),
            observer,
            worktree_root: None,
        }
    }

    /// Adds runs' worktrees under `root` instead of the rho home's.
    #[cfg(test)]
    pub(crate) fn with_worktree_root(mut self, root: PathBuf) -> Self {
        self.worktree_root = Some(root);
        self
    }

    /// Delegated agents run in the parent's environment.
    pub(crate) fn with_environment(
        mut self,
        environment: crate::session_environment::SessionEnvironment,
    ) -> Self {
        self.executor = self.executor.with_environment(environment);
        self
    }

    /// Sends the questionnaires of this manager's children to `sender`.
    pub(crate) fn bind_host_input_to(
        &self,
        sender: tokio::sync::mpsc::Sender<SubagentHostInputRequest>,
    ) {
        self.executor.host_input().bind_parent_to(sender);
    }

    /// Atomically replaces the notice binding, retaining in-flight channel notices.
    ///
    /// Pass `None` for the first bind. When rebinding, pass the prior receiver so
    /// posts that already returned `Ok` stay deliverable on the retired generation.
    pub(crate) fn rebind_notices(
        &self,
        old_receiver: Option<tokio::sync::mpsc::Receiver<SubagentNotice>>,
    ) -> crate::app::subagent_messaging::NoticeRebind {
        self.executor.notices().rebind_parent(old_receiver)
    }

    pub(crate) fn unbind_notices(&self) {
        self.executor.notices().unbind_parent();
    }

    /// Binds session `session_id`, whose file is `storage` once it has one,
    /// as the session later subagents report to: their artifacts go in that
    /// file's folder, their sessions record the file's session as their
    /// parent, and they save those sessions as `persistence` says the
    /// parent does.
    pub(crate) fn bind_parent_session(
        &self,
        session_id: impl Into<String>,
        storage: Option<&crate::session::Session>,
        persistence: SessionPersistence,
    ) {
        *self.parent.lock().expect("delegated session lock") = ParentBinding {
            placement: subagent::RunPlacement::for_parent_session(
                session_id,
                storage.and_then(crate::session::Session::subagents_dir),
            ),
            workspace: storage.map(|stored| stored.cwd().to_path_buf()),
            persistence,
        };
    }

    pub fn update_selection(
        &self,
        provider: &str,
        model: &str,
        reasoning: rho_sdk::ReasoningLevel,
        auth: &str,
    ) {
        self.executor
            .update_selection(provider, model, reasoning, auth);
    }

    /// Updates the policy snapshot used by future launches. Already-spawned
    /// agents retain the mode captured when they were launched.
    pub(crate) fn update_permission_mode(&self, mode: crate::permission::PermissionMode) {
        self.executor.update_permission_mode(mode);
    }

    /// Updates the added workspace directories future launches inherit.
    pub(crate) fn update_added_dirs(&self, added_dirs: crate::added_dirs::AddedDirs) {
        self.executor.update_added_dirs(added_dirs);
    }

    /// Binds `definition` for a delegated run, before anything about the run
    /// exists.
    pub(crate) fn bind(
        &self,
        definition: &AgentDefinition,
        model_override: Option<&str>,
    ) -> anyhow::Result<DelegatedBinding> {
        self.executor
            .bind_delegated(Arc::new(definition.clone()), model_override)
    }

    /// Starts adding a git worktree for one delegated run, at the place in
    /// the repository its runs would otherwise work at, starting where the
    /// config says.
    pub(crate) fn add_worktree(&self) -> AddingWorktree {
        let executor = self.executor.clone();
        let root = self.worktree_root.clone();
        AddingWorktree(Some(tokio::spawn(async move {
            let root = match root {
                Some(root) => root,
                None => crate::worktree::root(&crate::paths::rho_dir()?),
            };
            let workspace = crate::paths::canonicalize(executor.cwd())?;
            Ok(crate::worktree::add(&root, &workspace, executor.worktree_start()).await?)
        })))
    }

    /// Starts and registers a run of `binding` in `workspace`, returning its
    /// id. A worktree added for the run is discarded when it cannot start.
    pub(crate) async fn spawn(
        &self,
        binding: DelegatedBinding,
        prompt: &str,
        cwd: &Path,
        workspace: LaunchWorkspace,
    ) -> anyhow::Result<String> {
        let worktree = match &workspace {
            LaunchWorkspace::Executor => None,
            LaunchWorkspace::Worktree { worktree, .. } => Some(worktree.clone()),
        };
        let error = match self.start(binding, prompt, cwd, workspace).await {
            Ok(id) => return Ok(id),
            Err(error) => error,
        };
        let Some(worktree) = worktree else {
            return Err(error);
        };
        match crate::worktree::discard(&worktree).await {
            Ok(()) => Err(error),
            Err(discard) => Err(anyhow::anyhow!(
                "{error}; could not discard the worktree added for it ({}, branch {}): {discard}",
                worktree.path.display(),
                worktree.branch
            )),
        }
    }

    async fn start(
        &self,
        binding: DelegatedBinding,
        prompt: &str,
        cwd: &Path,
        workspace: LaunchWorkspace,
    ) -> anyhow::Result<String> {
        let ParentBinding {
            placement,
            workspace: parent_workspace,
            persistence,
        } = self.parent.lock().expect("delegated session lock").clone();
        // Every host binds its session before a turn can call the `agent`
        // tool, so a subagent always has the parent it reports to.
        let Some(session_id) = placement.parent_session_id().map(str::to_owned) else {
            anyhow::bail!("could not start subagent: no parent session is bound");
        };
        let parent_session_id = rho_sdk::SessionId::from_string(session_id.clone())
            .map_err(|error| anyhow::anyhow!("could not start subagent: {error}"))?;
        let works_in = match &workspace {
            LaunchWorkspace::Executor => cwd.to_path_buf(),
            LaunchWorkspace::Worktree { cwd, .. } => cwd.clone(),
        };
        let agent_id = binding.agent_id();
        let run_cwd = cwd.to_path_buf();
        let reserving = placement.clone();
        let (id, directory) = tokio::task::spawn_blocking(move || {
            subagent::reserve_run_directory(&reserving, &run_cwd)
        })
        .await??;
        let launch = RunLaunch {
            binding,
            parent_session_id,
            parent_workspace,
            persistence,
            output_file: directory.join(subagent::RESULT_FILE_NAME),
            workspace,
            works_in,
            placement,
            indexed_under: cwd.to_path_buf(),
        };
        let (events, followed) = child_events(self.observer.as_ref());
        let request = launch
            .clone()
            .request(&id, prompt, events, ChildConversation::New);
        let handle = match self.executor.spawn(request) {
            Ok(handle) => handle,
            Err(error) => {
                let cleanup_id = id.clone();
                let cleanup_directory = directory.clone();
                let cleanup = tokio::task::spawn_blocking(move || {
                    subagent::release_run_directory(&cleanup_id, &cleanup_directory)
                })
                .await?;
                if let Err(cleanup_error) = cleanup {
                    return Err(anyhow::anyhow!(
                        "{error}; failed to clean up delegated run reservation: {cleanup_error}"
                    ));
                }
                return Err(error);
            }
        };
        let task = crate::title::placeholder(prompt);
        if let Some(observer) = &self.observer {
            observer.subagent_started(StartedSubagent::of(
                id.clone(),
                launch.works_in.clone(),
                &handle,
                followed,
                task.clone(),
            ));
        }
        let ending = handle.clone();
        self.inner.lock().expect("delegated registry lock").insert(
            id.clone(),
            AgentEntry {
                agent_id,
                task_fallback: task,
                started: Instant::now(),
                handle,
                session_id,
                persistence,
                observed: false,
                explicitly_observed: false,
                started_by: None,
                launch: Some(launch),
            },
        );
        self.registered(ending);
        Ok(id)
    }

    /// Wakes whoever waits for a run to start, and later for it to end, once
    /// the run `handle` drives is registered, so whoever the notice wakes
    /// finds it.
    fn registered(&self, mut handle: AgentRunHandle) {
        self.started.notify_waiters();
        let ended = Arc::clone(&self.ended);
        tokio::spawn(async move {
            handle.wait().await;
            ended.notify_waiters();
        });
    }

    #[cfg(test)]
    pub(crate) fn insert_completed_for_test(
        &self,
        id: &str,
        session_id: &str,
        total_cost_usd: Option<f64>,
    ) {
        self.insert_completed_status_for_test(
            id,
            session_id,
            crate::subagent::RunStatus {
                state: crate::subagent::RunState::Ok,
                total_cost_usd,
                ..crate::subagent::RunStatus::default()
            },
        );
    }

    #[cfg(test)]
    pub(crate) fn insert_completed_status_for_test(
        &self,
        id: &str,
        session_id: &str,
        status: crate::subagent::RunStatus,
    ) {
        self.insert_handle_for_test(id, session_id, AgentRunHandle::completed_for_test(status));
    }

    #[cfg(test)]
    pub(crate) fn post_notice_for_test(&self, notice: SubagentNotice) {
        self.executor.notices().post(notice).unwrap();
    }

    #[cfg(test)]
    pub(crate) fn insert_handle_for_test(
        &self,
        id: &str,
        session_id: &str,
        handle: AgentRunHandle,
    ) {
        let _delivery = super::notification_delivery::lock();
        self.inner.lock().expect("delegated registry lock").insert(
            id.to_string(),
            AgentEntry {
                agent_id: "fixture".into(),
                task_fallback: None,
                started: Instant::now(),
                handle,
                session_id: session_id.into(),
                persistence: SessionPersistence::Saved,
                observed: false,
                explicitly_observed: false,
                started_by: None,
                launch: None,
            },
        );
    }

    /// Records that tool call `call` started run `id`, as the call
    /// finishes, with what the run shows as now, which
    /// [`Self::run_started_by`] answers.
    pub(crate) fn record_starter(&self, id: &str, call: &str) {
        if let Some(entry) = self
            .inner
            .lock()
            .expect("delegated registry lock")
            .get_mut(id)
        {
            entry.started_by = Some(Starter {
                call: call.to_owned(),
                title: entry.shown_title(entry.handle.status().title),
            });
        }
    }

    /// The run tool call `call` of the bound parent session started,
    /// running or not, with its own session when it has one and what it
    /// showed as when the call finished, which a later title does not
    /// change. `None` when more than one did: a provider may reuse a call
    /// id across turns, and no run is better than another call's.
    pub(crate) fn run_started_by(&self, call: &str) -> Option<SubagentLink> {
        let parent = self.parent.lock().expect("delegated session lock").clone();
        let parent = parent.placement.parent_session_id()?;
        let entries = self.inner.lock().expect("delegated registry lock");
        let mut started = entries
            .iter()
            .filter(|(_, entry)| {
                entry.session_id == parent
                    && entry
                        .started_by
                        .as_ref()
                        .is_some_and(|starter| starter.call == call)
            })
            .map(|(id, entry)| SubagentLink {
                run: id.clone(),
                session: entry
                    .handle
                    .session()
                    .map(|session| session.id().as_str().to_owned()),
                title: entry
                    .started_by
                    .as_ref()
                    .and_then(|starter| starter.title.clone()),
            });
        let run = started.next()?;
        started.next().is_none().then_some(run)
    }

    /// Read launch metadata without acknowledging a completion notification.
    pub(crate) fn status(&self, id: &str) -> Option<SubagentSnapshot> {
        let id = crate::subagent::normalize_id(id).ok()?;
        self.inner
            .lock()
            .expect("delegated registry lock")
            .get(&id)
            .map(|entry| entry.snapshot(&id))
    }

    pub fn list(&self) -> Vec<SubagentSnapshot> {
        let entries = self.inner.lock().expect("delegated registry lock");
        let mut snapshots = entries
            .iter()
            .map(|(id, entry)| entry.snapshot(id))
            .collect::<Vec<_>>();
        snapshots.sort_by_key(|snapshot| std::cmp::Reverse(snapshot.elapsed));
        snapshots
    }

    /// Display identity without marking a run's result as observed.
    pub(crate) fn task_identity(&self, id: &str) -> Option<SubagentTaskIdentity> {
        let id = crate::subagent::normalize_id(id).ok()?;
        let entries = self.inner.lock().expect("delegated registry lock");
        let entry = entries.get(&id)?;
        let task = entry.display_title(entry.handle.status().title);
        Some(SubagentTaskIdentity {
            run_id: id,
            agent_id: entry.agent_id.clone(),
            task,
            session: entry.handle.session().map(|session| session.id().clone()),
        })
    }

    #[cfg(test)]
    pub fn has_running_for_session(&self, session_id: &str) -> bool {
        self.inner
            .lock()
            .expect("delegated registry lock")
            .values()
            .any(|entry| entry.session_id == session_id && !entry.handle.is_complete())
    }

    /// Whether a child of session `session_id` that no turn was given yet
    /// still runs: among undelivered children, exactly those
    /// [`Self::has_pending_notification`] does not count.
    pub(crate) fn has_running(&self, session_id: &str) -> bool {
        self.inner
            .lock()
            .expect("delegated registry lock")
            .iter()
            .any(|(id, entry)| {
                entry.session_id == session_id && !entry.observed && !entry.snapshot(id).done
            })
    }

    /// True while this session still has an undelivered child.
    pub fn has_active_or_pending_notification(&self, session_id: &str) -> bool {
        self.inner
            .lock()
            .expect("delegated registry lock")
            .values()
            .any(|entry| entry.session_id == session_id && !entry.observed)
    }

    /// Whether a finished child of session `session_id` waits to be
    /// delivered. Running children are excluded: a host that wakes the
    /// idle session sleeps on [`Self::parent_wake`].
    // Only the daemon wakes an idle parent.
    pub(crate) fn has_pending_notification(&self, session_id: &str) -> bool {
        self.inner
            .lock()
            .expect("delegated registry lock")
            .iter()
            .any(|(id, entry)| {
                entry.session_id == session_id && !entry.observed && entry.snapshot(id).done
            })
    }

    /// The notices children queued for session `session_id` that no turn
    /// delivered.
    pub(crate) fn undelivered_notices(&self, session_id: &str) -> Vec<SubagentNotice> {
        self.executor.notices().undelivered(session_id)
    }

    /// Resolves once a child ends or queues a notice from now on, whatever
    /// waits already: the two things that can give an idle parent a turn.
    pub(crate) fn parent_wake(&self) -> impl std::future::Future<Output = ()> + Send + 'static {
        let ended = Arc::clone(&self.ended).notified_owned();
        let posted = self.executor.notices().posted();
        async move {
            tokio::select! {
                () = ended => {}
                () = posted => {}
            }
        }
    }

    /// Resolves once a child is registered or ends from now on. Subscribe
    /// before reading [`Self::background`], so a change in between still
    /// wakes.
    pub(crate) fn changed(&self) -> impl std::future::Future<Output = ()> + Send + 'static {
        let started = Arc::clone(&self.started).notified_owned();
        let ended = Arc::clone(&self.ended).notified_owned();
        async move {
            tokio::select! {
                () = started => {}
                () = ended => {}
            }
        }
    }

    /// The children of session `session_id` whose result it has yet to be
    /// given: running, or finished and undelivered, oldest first.
    pub(crate) fn background(&self, session_id: &str) -> Vec<BackgroundChild> {
        let entries = self.inner.lock().expect("delegated registry lock");
        let mut children: Vec<_> = entries
            .iter()
            .filter(|(_, entry)| entry.session_id == session_id && !entry.observed)
            .map(|(id, entry)| {
                let status = entry.handle.status();
                let title = entry.display_title(status.title);
                let state = if entry.handle.is_complete() {
                    status.state
                } else {
                    subagent::RunState::Running
                };
                (
                    entry.started,
                    BackgroundChild {
                        run: id.clone(),
                        title,
                        session: entry.handle.session().map(|session| session.id().clone()),
                        state,
                    },
                )
            })
            .collect();
        children.sort_by(|(left, a), (right, b)| left.cmp(right).then_with(|| a.run.cmp(&b.run)));
        children.into_iter().map(|(_, child)| child).collect()
    }

    /// Asks running child `id` of session `session_id` to stop, without
    /// waiting: its result, cancelled, is delivered like any other.
    pub(crate) fn cancel(&self, session_id: &str, id: &str) -> anyhow::Result<()> {
        let entries = self.inner.lock().expect("delegated registry lock");
        let entry = entries
            .get(id)
            .filter(|entry| entry.session_id == session_id)
            .ok_or_else(|| anyhow::anyhow!("unknown delegated run '{id}'"))?;
        if entry.handle.is_complete() {
            anyhow::bail!("delegated run '{id}' already ended");
        }
        entry.handle.cancel();
        Ok(())
    }

    /// Waits for any current child to finish without marking its result delivered.
    /// Hosts call this at a provider boundary, after all launches have registered.
    pub(crate) async fn wait_for_notification(&self, session_id: &str) {
        let handles = {
            let entries = self.inner.lock().expect("delegated registry lock");
            // Include unobserved terminals too: completion can change while
            // this registry lock is held, and their wait returns immediately.
            entries
                .values()
                .filter(|entry| entry.session_id == session_id && !entry.observed)
                .map(|entry| entry.handle.clone())
                .collect::<Vec<_>>()
        };
        let mut waits = handles
            .into_iter()
            .map(|mut handle| async move { handle.wait().await })
            .collect::<futures_util::stream::FuturesUnordered<_>>();
        if futures_util::StreamExt::next(&mut waits).await.is_none() {
            std::future::pending::<()>().await;
        }
    }

    /// Atomically drains every unobserved terminal background run for the
    /// session and marks the whole batch observed, in launch order so batched
    /// delivery is deterministic.
    pub fn take_notifications(&self, session_id: &str) -> Vec<SubagentNotification> {
        let mut entries = self.inner.lock().expect("delegated registry lock");
        let mut notifications = entries
            .iter_mut()
            .filter_map(|(id, entry)| {
                if entry.observed || entry.session_id != session_id {
                    return None;
                }
                let snapshot = entry.snapshot(id);
                snapshot.done.then(|| {
                    entry.observed = true;
                    (entry.started, SubagentNotification { snapshot })
                })
            })
            .collect::<Vec<_>>();
        notifications.sort_by(|(a_started, a), (b_started, b)| {
            a_started
                .cmp(b_started)
                .then_with(|| a.snapshot.id.cmp(&b.snapshot.id))
        });
        notifications
            .into_iter()
            .map(|(_, notification)| notification)
            .collect()
    }

    /// Returns drained notifications so a failed turn setup can deliver them
    /// again. Only terminal background entries still present are reopened.
    pub fn restore_notifications(&self, notifications: &[SubagentNotification]) {
        if notifications.is_empty() {
            return;
        }
        let mut entries = self.inner.lock().expect("delegated registry lock");
        for notification in notifications {
            let Some(entry) = entries.get_mut(&notification.snapshot.id) else {
                continue;
            };
            let snapshot = entry.snapshot(&notification.snapshot.id);
            if snapshot.done && entry.observed && !entry.explicitly_observed {
                entry.observed = false;
            }
        }
    }

    /// Returns the run snapshot; a terminal snapshot counts as delivered, so
    /// automatic notification will not repeat a result the parent already
    /// read through `status` or `stop`.
    pub fn observe(&self, id: &str) -> Option<SubagentSnapshot> {
        let id = crate::subagent::normalize_id(id).ok()?;
        let _delivery = super::notification_delivery::lock();
        let mut entries = self.inner.lock().expect("delegated registry lock");
        let entry = entries.get_mut(&id)?;
        let mut snapshot = entry.snapshot(&id);
        if snapshot.done {
            snapshot.prior_notices = self
                .executor
                .notices()
                .pending_for_run(&id)
                .into_iter()
                .map(|notice| {
                    notice.acknowledge();
                    notice.message
                })
                .collect();
            entry.observed = true;
            entry.explicitly_observed = true;
        }
        Some(snapshot)
    }

    #[cfg(test)]
    pub async fn wait_done(&self, id: &str) -> Option<SubagentSnapshot> {
        let id = crate::subagent::normalize_id(id).ok()?;
        let mut handle = self
            .inner
            .lock()
            .expect("delegated registry lock")
            .get(&id)?
            .handle
            .clone();
        handle.wait().await;
        self.status(&id)
    }

    pub async fn stop(&self, id: &str) -> anyhow::Result<SubagentSnapshot> {
        let id = crate::subagent::normalize_id(id)?;
        let mut handle = self
            .inner
            .lock()
            .expect("delegated registry lock")
            .get(&id)
            .ok_or_else(|| anyhow::anyhow!("unknown delegated run '{id}'"))?
            .handle
            .clone();
        handle.cancel();
        tokio::time::timeout(SHUTDOWN_TIMEOUT, handle.wait())
            .await
            .map_err(|_| anyhow::anyhow!("timed out stopping delegated run '{id}'"))?;
        // Stopping hands the terminal snapshot to the caller, so it counts
        // as delivered and is not repeated by automatic notification.
        self.observe(&id)
            .ok_or_else(|| anyhow::anyhow!("delegated run '{id}' disappeared"))
    }

    pub async fn shutdown(&self) {
        let handles = self
            .inner
            .lock()
            .expect("delegated registry lock")
            .values()
            .map(|entry| entry.handle.clone())
            .collect::<Vec<_>>();
        for handle in &handles {
            handle.cancel();
        }
        let waits = handles.into_iter().map(|mut handle| async move {
            handle.wait().await;
        });
        let _ = tokio::time::timeout(SHUTDOWN_TIMEOUT, futures_util::future::join_all(waits)).await;
    }
}

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