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
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
use std::{
    path::{Path, PathBuf},
    sync::Arc,
};

use {
    crate::agent::{AgentCapabilities, AgentDefinition, ToolCapability},
    crate::config::Config,
    crate::session::SessionPersistence,
    crate::subagent::{self, RunState, RunStatus},
    rho_tools::cancellation::RunCancellation,
};

use super::{
    agent_binding::{AgentBinder, AgentInvocation, AgentRole, Launch},
    agent_concurrency::{AgentConcurrency, QueueWatch, RunSlot},
    headless_host::{self, ChildRun, ChildSession, ParentQuestions},
    runtime_child_host::RecordedChildren,
    session_runtime::{SessionRole, UnattendedApprovals},
    subagent_host_input::{ChildAsker, SubagentHostInputBridge},
    subagent_messaging::{
        NoticePostError, NoticePoster, SteeringSlot, SubagentNotice, SubagentNoticeBridge,
        ValidatedMessage,
    },
    subagent_pool::{ChildEventSender, ExternalRun, RunSession},
    title_agent::{generate_title, TitleRequest},
};

#[derive(Clone)]
pub(crate) struct AgentExecutor {
    config: Arc<std::sync::RwLock<Config>>,
    config_path: PathBuf,
    cwd: PathBuf,
    /// Live-resizable global + nested Claude capacity for delegated runs.
    concurrency: AgentConcurrency,
    host_input: SubagentHostInputBridge,
    notices: SubagentNoticeBridge,
    /// What answers a Rho child's approvals besides the child itself.
    approvals: UnattendedApprovals,
    /// The parent session's added workspace directories, inherited by future
    /// Rho runtime launches.
    added_dirs: Arc<std::sync::RwLock<crate::added_dirs::AddedDirs>>,
    /// The parent's environment, shared by Rho runtime launches. CLI runtime
    /// launches take it as it is when they start (#1659); a workflow run's
    /// handle is its own and never changes.
    environment: crate::session_environment::SessionEnvironment,
}

pub(crate) struct AgentLaunchRequest {
    pub(crate) binding: DelegatedBinding,
    pub(crate) prompt: String,
    pub(crate) run_id: String,
    /// The session that delegated the run.
    pub(crate) parent_session_id: rho_sdk::SessionId,
    /// The workspace the parent is saved in, `None` while it has no file;
    /// see [`SessionRole::Subagent`].
    pub(crate) parent_workspace: Option<PathBuf>,
    /// Whether the run's session is saved, as its parent's is.
    pub(crate) persistence: SessionPersistence,
    pub(crate) output_file: PathBuf,
    /// Where the child sends its session's events, when its host follows
    /// them.
    pub(crate) events: Option<ChildEventSender>,
    /// Where the children its agent starts on its own are recorded: set
    /// when its host follows the run, and kept only for a Claude Code
    /// definition that declares Claude's subagent tools.
    pub(crate) runtime_children: Option<RecordedChildren>,
    /// Where the run works.
    pub(crate) workspace: LaunchWorkspace,
    /// The conversation the run holds.
    pub(crate) conversation: ChildConversation,
}

/// The conversation a delegated run holds.
#[derive(Clone, Debug)]
pub(crate) enum ChildConversation {
    /// A new session, which gets a generated title.
    New,
    /// A follow-up of a finished Rho run: the session that run saved, which
    /// the follow-up continues with its prompt as the next turn, and the
    /// title the run had, which it keeps, or none, when it gets a generated
    /// one.
    FollowUp {
        session: rho_sdk::SessionId,
        title: Option<String>,
    },
}

/// Where one launch works.
#[derive(Clone, Debug)]
pub(crate) enum LaunchWorkspace {
    /// The executor's workspace, which its parent works in.
    Executor,
    /// A git worktree added for this run alone, which it works in at `cwd`.
    Worktree {
        worktree: rho_protocol::SessionWorktree,
        cwd: PathBuf,
    },
}

/// A delegated agent bound for launch, before anything about its run
/// exists, so a bad model or missing credential fails before any side
/// effect. Kept by a run's registry entry, so a follow-up launches as the
/// run did.
#[derive(Clone)]
pub(crate) struct DelegatedBinding {
    bound: super::agent_binding::BoundAgent,
    parent_answers_questions: bool,
}

impl DelegatedBinding {
    /// The id of the agent it bound.
    pub(crate) fn agent_id(&self) -> String {
        self.bound.id().to_string()
    }
}

/// Launch request whose agent definition was resolved and frozen at plan time.
pub(crate) struct FrozenAgentLaunchRequest {
    pub(crate) agent: crate::workflow::ResolvedAgent,
    pub(crate) prompt: String,
    pub(crate) run_id: String,
    pub(crate) output_file: PathBuf,
    pub(crate) hook_host_labels: rho_sdk::hooks::HookHostLabels,
    /// The session a Rho runtime agent runs in, which its node recorded.
    /// A Rho agent's launch needs one; agents on other runtimes have none.
    pub(crate) session: Option<ChildSession>,
    /// Where the child sends its session's events, when its host follows
    /// them.
    pub(crate) events: Option<ChildEventSender>,
}

/// How a live handle can accept parent plain-text messages.
#[derive(Clone, Debug)]
enum MessagingSupport {
    /// Rho runtime: the child session's handle is published once it opens.
    Rho { steering: SteeringSlot },
    /// ACP runtimes: steered into the running turn when the agent supports
    /// `_session/steering`, otherwise delivered as the next `session/prompt`.
    Queued {
        messages: crate::cli_runtime::parent_messages::ParentMessageHandle,
    },
}

/// Messaging ports created with the run handle, before the session task starts.
struct RuntimeMessagingPorts {
    messaging: MessagingSupport,
    steering_slot: Option<SteeringSlot>,
    parent_rx: Option<crate::cli_runtime::parent_messages::ParentMessageInbox>,
}

impl MessagingSupport {
    /// Decides messaging support and the run's ports together, so the
    /// handle and session task cannot disagree about which path is live.
    fn for_runtime(runtime: &super::agent_binding::BoundRuntime) -> RuntimeMessagingPorts {
        match runtime {
            super::agent_binding::BoundRuntime::ClaudeCli { .. }
            | super::agent_binding::BoundRuntime::Antigravity { .. } => {
                let (handle, inbox) = crate::cli_runtime::parent_messages::message_channel();
                RuntimeMessagingPorts {
                    messaging: Self::Queued { messages: handle },
                    steering_slot: None,
                    parent_rx: Some(inbox),
                }
            }
            super::agent_binding::BoundRuntime::Rho { .. } => {
                let steering = SteeringSlot::new();
                RuntimeMessagingPorts {
                    messaging: Self::Rho {
                        steering: steering.clone(),
                    },
                    steering_slot: Some(steering),
                    parent_rx: None,
                }
            }
        }
    }
}

#[derive(Clone)]
pub(crate) struct AgentRunHandle {
    cancellation: RunCancellation,
    status: tokio::sync::watch::Receiver<RunStatus>,
    completion: tokio::sync::watch::Receiver<bool>,
    messaging: MessagingSupport,
    /// Where the run waits for capacity, while it does.
    queue: QueueWatch,
    /// The session the run shows its events under; `None` for a run on
    /// an external runtime that nobody follows.
    session: Option<RunSession>,
}

impl AgentRunHandle {
    pub(crate) fn cancel(&self) {
        self.cancellation.cancel();
    }

    pub(crate) fn status(&self) -> RunStatus {
        self.status.borrow().clone()
    }

    pub(crate) fn is_complete(&self) -> bool {
        *self.completion.borrow()
    }

    pub(crate) async fn wait(&mut self) -> RunStatus {
        while !*self.completion.borrow() {
            if self.completion.changed().await.is_err() {
                break;
            }
        }
        self.status()
    }

    /// Where the run waits for capacity; see [`QueueWatch::place`].
    pub(crate) fn queue(&self) -> QueueWatch {
        self.queue.clone()
    }

    /// The session the run shows its events under: the one a Rho child
    /// saves, or the one a run on an external runtime is recorded under;
    /// `None` for an external run nobody follows.
    pub(crate) fn session(&self) -> Option<&RunSession> {
        self.session.as_ref()
    }

    /// Clone of the live status watch used while the run is in flight.
    pub(crate) fn clone_status_watch(&self) -> tokio::sync::watch::Receiver<RunStatus> {
        self.status.clone()
    }

    /// Stages a parent message for the next Rho provider turn or CLI child turn.
    pub(crate) async fn message_from_parent(
        &self,
        message: &ValidatedMessage,
    ) -> anyhow::Result<()> {
        match &self.messaging {
            MessagingSupport::Rho { steering } => {
                if self.is_complete() {
                    anyhow::bail!("delegated run has already finished");
                }
                steering.send(message).await
            }
            MessagingSupport::Queued { messages } => {
                if self.is_complete() {
                    anyhow::bail!("delegated run has already finished");
                }
                // Drain frames the body the same way Rho steering does.
                messages
                    .send(message.as_str().to_string())
                    .map_err(|error| anyhow::anyhow!("{error}"))
            }
        }
    }

    #[cfg(test)]
    pub(crate) fn controlled_for_test(
        status: tokio::sync::watch::Receiver<RunStatus>,
        completion: tokio::sync::watch::Receiver<bool>,
        cancellation: RunCancellation,
    ) -> Self {
        let (messages, inbox) = crate::cli_runtime::parent_messages::message_channel();
        // No child reads this inbox; parent messages fail closed.
        drop(inbox);
        Self {
            cancellation,
            status,
            completion,
            messaging: MessagingSupport::Queued { messages },
            queue: QueueWatch::default(),
            session: None,
        }
    }

    #[cfg(test)]
    pub(crate) fn completed_for_test(status: RunStatus) -> Self {
        let (_status_tx, status_rx) = tokio::sync::watch::channel(status);
        let (_completion_tx, completion_rx) = tokio::sync::watch::channel(true);
        let (messages, inbox) = crate::cli_runtime::parent_messages::message_channel();
        // Drop the inbox so late parent messages fail closed like a finished run.
        drop(inbox);
        Self {
            cancellation: RunCancellation::new(),
            status: status_rx,
            completion: completion_rx,
            messaging: MessagingSupport::Queued { messages },
            queue: QueueWatch::default(),
            session: None,
        }
    }
}

impl AgentExecutor {
    /// The workspace runs are spawned in.
    pub(crate) fn cwd(&self) -> &Path {
        &self.cwd
    }

    /// Where a worktree added for a run starts its branch, as the current
    /// config says.
    pub(crate) fn worktree_start(&self) -> crate::worktree::Start {
        crate::worktree::Start::of(&self.config.read().expect("delegated config lock"))
    }

    /// An executor whose runs take capacity from `concurrency`: a pool of
    /// their own, or one their host shares (see `subagent_pool`).
    pub(crate) fn new(
        config: Config,
        config_path: PathBuf,
        cwd: PathBuf,
        concurrency: AgentConcurrency,
        host_input: SubagentHostInputBridge,
        notices: SubagentNoticeBridge,
    ) -> Self {
        Self {
            config: Arc::new(std::sync::RwLock::new(config)),
            config_path,
            cwd,
            concurrency,
            host_input,
            notices,
            approvals: UnattendedApprovals::Alone,
            added_dirs: Arc::default(),
            environment: Default::default(),
        }
    }

    /// Every launch runs in the parent's environment.
    pub(crate) fn with_environment(
        mut self,
        environment: crate::session_environment::SessionEnvironment,
    ) -> Self {
        self.environment = environment;
        self
    }

    /// What answers each Rho child's approvals besides the child itself,
    /// such as a workflow run's approval session or classifier template.
    pub(crate) fn with_approvals(mut self, approvals: UnattendedApprovals) -> Self {
        self.approvals = approvals;
        self
    }

    pub(crate) fn host_input(&self) -> &SubagentHostInputBridge {
        &self.host_input
    }

    pub(crate) fn notices(&self) -> &SubagentNoticeBridge {
        &self.notices
    }

    /// Atomically updates the parent session's provider selection inherited by
    /// future **Rho** runtime delegated agents. The parent runs on `auth`,
    /// so a child starts on it as chosen rather than settling it again.
    ///
    /// Claude-cli agents never read this snapshot for spawn: binding copies
    /// Claude model/tools/inherit from the definition only, byte-for-byte.
    pub(crate) fn update_selection(
        &self,
        provider: &str,
        model: &str,
        reasoning: rho_sdk::ReasoningLevel,
        auth: &str,
    ) {
        let mut config = self.config.write().expect("delegated config lock");
        config
            .run_conversation_on(provider.into(), model.into(), auth.into())
            .choose_auth(auth);
        config.reasoning = reasoning;
    }

    /// Updates the added directories future launches inherit. Already-spawned
    /// agents keep the scope they started with.
    pub(crate) fn update_added_dirs(&self, added_dirs: crate::added_dirs::AddedDirs) {
        *self.added_dirs.write().expect("delegated added dirs lock") = added_dirs;
    }

    pub(crate) fn update_permission_mode(&self, mode: crate::permission::PermissionMode) {
        self.config
            .write()
            .expect("delegated config lock")
            .permission_mode = mode;
    }

    #[cfg(test)]
    pub(crate) fn launch_permission_mode(&self) -> crate::permission::PermissionMode {
        self.config
            .read()
            .expect("delegated config lock")
            .permission_mode
    }

    /// Binds `definition` for a delegated run, with `model_override` in
    /// place of its model when given.
    pub(crate) fn bind_delegated(
        &self,
        definition: Arc<AgentDefinition>,
        model_override: Option<&str>,
    ) -> anyhow::Result<DelegatedBinding> {
        let config = self.config.read().expect("delegated config lock").clone();
        let mut capabilities = AgentCapabilities::all_host_tools();
        // web_search is gated after bind against the agent provider/model.
        #[cfg(windows)]
        capabilities.remove(&ToolCapability::Bash);
        #[cfg(not(windows))]
        capabilities.remove(&ToolCapability::Powershell);
        // Delegated questionnaires require a live parent host-input bridge.
        let parent_answers_questions = self.host_input.is_bound();
        if !parent_answers_questions {
            capabilities.remove(&ToolCapability::Questionnaire);
        }
        let bound = AgentBinder::bind_with_credentials(
            definition,
            AgentInvocation {
                role: AgentRole::Delegated,
                available_tools: capabilities,
            },
            &config,
            model_override.map(super::agent_binding::ModelOverride::Reference),
            self.environment.credentials().as_ref(),
        )?;
        Ok(DelegatedBinding {
            bound,
            parent_answers_questions,
        })
    }

    pub(crate) fn spawn(&self, request: AgentLaunchRequest) -> anyhow::Result<AgentRunHandle> {
        let DelegatedBinding {
            bound,
            parent_answers_questions,
        } = request.binding;
        // Notices share the parent-session binding, not the questionnaire one.
        let notice_target = self
            .notices
            .is_bound()
            .then(|| request.parent_session_id.clone());
        let (session, title) = match request.conversation {
            ChildConversation::New => (
                ChildSession::New(rho_sdk::SessionId::new()),
                RunTitle::Generate,
            ),
            ChildConversation::FollowUp { session, title } => (
                ChildSession::FollowUp {
                    id: session,
                    // The parent's mode now, which may be narrower than the
                    // one the run it follows up was bound under.
                    ceiling: self
                        .config
                        .read()
                        .expect("delegated config lock")
                        .permission_mode,
                },
                title.map_or(RunTitle::Generate, RunTitle::Keep),
            ),
        };
        self.spawn_bound(BoundLaunchRequest {
            bound,
            prompt: request.prompt,
            run_id: request.run_id,
            role: SessionRole::Subagent {
                parent: request.parent_session_id,
                parent_workspace: request.parent_workspace,
            },
            workspace: request.workspace,
            persistence: request.persistence,
            output_file: request.output_file,
            parent_answers_questions,
            notice_target,
            frozen_cli: None,
            hook_host_labels: rho_sdk::hooks::HookHostLabels::new(),
            session,
            title,
            events: request.events,
            runtime_children: request.runtime_children,
        })
    }

    /// Starts a workflow node from persisted launch metadata without looking up
    /// or rebinding an agent definition.
    pub(crate) fn spawn_frozen(
        &self,
        request: FrozenAgentLaunchRequest,
    ) -> anyhow::Result<AgentRunHandle> {
        let config = self.config.read().expect("delegated config lock").clone();
        let mut current_tools = AgentCapabilities::all_host_tools();
        #[cfg(windows)]
        current_tools.remove(&ToolCapability::Bash);
        #[cfg(not(windows))]
        current_tools.remove(&ToolCapability::Powershell);
        current_tools.remove(&ToolCapability::Questionnaire);
        let bound = AgentBinder::bind_frozen(&request.agent, &config, &current_tools)?;
        let (frozen_cli, session) = match request.agent.runtime {
            crate::workflow::AgentRuntime::Rho => {
                let session = request.session.ok_or_else(|| {
                    anyhow::anyhow!("a Rho agent launch has no session to run in")
                })?;
                (None, session)
            }
            // The launch's session is a Rho child's; a run on these runtimes
            // is recorded under a fresh one. `bind_frozen` above already
            // refused a retired runtime.
            crate::workflow::AgentRuntime::ClaudeCli
            | crate::workflow::AgentRuntime::Antigravity
            | crate::workflow::AgentRuntime::RetiredCursor => (
                // Checked now to fail the node early; `apply_frozen` checks
                // again just before spawn, on the launch's own `PATH`.
                Some(frozen_cli_launch(
                    request.agent,
                    self.environment.current().path().as_deref(),
                )?),
                ChildSession::New(rho_sdk::SessionId::new()),
            ),
        };
        self.spawn_bound(BoundLaunchRequest {
            bound,
            prompt: request.prompt,
            run_id: request.run_id,
            role: SessionRole::WorkflowNode,
            workspace: LaunchWorkspace::Executor,
            // Saved even when a `--no-save` run started the workflow: a
            // workflow run is its own durable record, which its nodes'
            // sessions are part of and `rho workflow` resumes from.
            persistence: SessionPersistence::Saved,
            output_file: request.output_file,
            parent_answers_questions: false,
            notice_target: None,
            frozen_cli,
            hook_host_labels: request.hook_host_labels,
            session,
            title: RunTitle::Generate,
            events: request.events,
            runtime_children: None,
        })
    }

    fn spawn_bound(&self, request: BoundLaunchRequest) -> anyhow::Result<AgentRunHandle> {
        let BoundLaunchRequest {
            bound,
            prompt,
            run_id,
            role,
            workspace,
            persistence,
            output_file,
            parent_answers_questions,
            notice_target,
            frozen_cli,
            hook_host_labels,
            session,
            title,
            events,
            runtime_children,
        } = request;
        let (cwd, worktree) = match workspace {
            LaunchWorkspace::Executor => (self.cwd.clone(), None),
            LaunchWorkspace::Worktree { worktree, cwd } => (cwd, Some(worktree)),
        };

        let capacity_class = bound.runtime().capacity_class();
        let RuntimeMessagingPorts {
            messaging,
            steering_slot,
            parent_rx,
        } = MessagingSupport::for_runtime(bound.runtime());

        // In line for capacity from now, so runs start in the order they
        // were spawned.
        let queued = self.concurrency.join(capacity_class);
        let queue = queued.watch();
        // A Rho child writes the session it was given; a run on another
        // runtime keeps its runtime's own, and is recorded under the given
        // one for a host that follows it.
        let (child_session, events, external) = match (bound.rho_config(), events) {
            (Some(_), events) => (Some(RunSession::Rho(session.id().clone())), events, None),
            (None, Some(events)) => {
                let external = ExternalRun {
                    events,
                    session: session.id().clone(),
                    cwd: cwd.clone(),
                    provenance: role.provenance(),
                    run: run_id.clone(),
                    status: output_file.clone(),
                    prompt: prompt.clone(),
                    persistence,
                };
                let child_session = RunSession::External(session.id().clone());
                (Some(child_session), None, Some(external))
            }
            (None, None) => (None, None, None),
        };
        // The run's title counts toward the session it works for, as the
        // run's own usage does; a run nobody delegated keeps it.
        let title_session = role
            .parent()
            .cloned()
            .unwrap_or_else(|| session.id().clone());
        let mut initial = bound.artifact_identity().queued_status();
        initial.parent_session_id = role.parent().map(ToString::to_string);
        initial.worktree = worktree;
        if let RunTitle::Keep(kept) = &title {
            initial.title = Some(kept.clone());
        }
        // Executor owns the Queued and Starting boundaries; sinks
        // continue_from Starting. Write Queued here so the handle can observe
        // status before the task runs.
        subagent::initialize_status(&output_file, &initial)?;
        let (status_tx, status) = tokio::sync::watch::channel(initial);
        let (completion_tx, completion) = tokio::sync::watch::channel(false);
        let cancellation = RunCancellation::new();
        let task_cancellation = cancellation.clone();
        let live_title = std::sync::Arc::new(std::sync::Mutex::new(None));
        let title_config = self.config.read().expect("delegated config lock").clone();
        let added_dirs = self
            .added_dirs
            .read()
            .expect("delegated added dirs lock")
            .clone();
        let config_path = self.config_path.clone();
        let environment = self.environment.clone();
        let host_input = self.host_input.clone();
        let notices = self.notices.clone();
        let persisted_output = output_file.clone();
        let approvals = self.approvals.clone();
        let task_steering_slot = steering_slot.clone();
        let task_concurrency = self.concurrency.clone();
        let task_queue = queue.clone();

        let task_status_tx = status_tx.clone();
        let title_output = output_file.clone();
        let title_agent_id = bound.id().to_string();
        let title_slot = std::sync::Arc::clone(&live_title);
        let task_live_title = std::sync::Arc::clone(&live_title);
        let task: tokio::task::JoinHandle<anyhow::Result<()>> = tokio::spawn(async move {
            // Acquire runtime-aware capacity before work starts. Claude runs
            // take Claude capacity first so queued Claude work cannot occupy
            // global permits while waiting on the nested pool; Rho takes only
            // the global pool. Dropping the guard returns every held permit.
            let Some(runtime_permits) = queued.acquire(&task_cancellation).await else {
                let mut stopped = task_status_tx.borrow().clone();
                stopped.state = RunState::Stopped;
                stopped.last_activity = Some("cancelled before execution".into());
                stopped.mark_finished_now();
                task_status_tx.send_replace(stopped.clone());
                subagent::write_status(&output_file, &stopped)?;
                return Ok(());
            };
            task_status_tx.send_modify(RunStatus::start_now);
            subagent::write_status(&output_file, &task_status_tx.borrow().clone())?;

            if let RunTitle::Generate = title {
                spawn_run_title(
                    TitleRequest {
                        config: title_config,
                        config_path: config_path.clone(),
                        cwd: cwd.clone(),
                        added_dirs: added_dirs.clone(),
                        environment: environment.clone(),
                        session: title_session,
                        input: crate::title::run_input(&title_agent_id, &prompt),
                    },
                    RunTitleSinks {
                        output_file: title_output,
                        status_tx: task_status_tx.clone(),
                        live_title: title_slot,
                    },
                );
            }

            let started_status = task_status_tx.borrow().clone();
            match bound.into_launch(super::agent_binding::CliRunInputs {
                prompt: crate::cli_runtime::CliPrompt::text(prompt.clone()),
                output_file: output_file.clone(),
                cwd: cwd.clone(),
                cancellation: task_cancellation.clone(),
                status_tx: Some(task_status_tx.clone()),
                started_status: Some(started_status),
                // A CLI agent takes the parent's environment as it is
                // now, at launch; a Rho child shares the live one
                // through `environment` (#1659).
                environment: environment.current(),
            }) {
                Launch::ClaudeCli(mut session) => {
                    append_child_communication_contract(&mut session.system_prompt);
                    session.overrides.observer = external
                        .map(|run| run.observer(&session.identity, session.permission_mode));
                    session.parent_messages = parent_rx;
                    session.persistence = persistence;
                    session.overrides.live_title = Some(std::sync::Arc::clone(&task_live_title));
                    // Only a definition that declares Claude's subagent
                    // tools has the subagents they start recorded, which
                    // turns them on, as the fence allows.
                    session.overrides.runtime_children = runtime_children
                        .filter(|_| {
                            crate::claude_runtime::fence::declares_nested_agents(&session.tools)
                        })
                        .map(|children| children.host(&session.identity, session.permission_mode));
                    if let Some(frozen) = frozen_cli {
                        apply_frozen(&mut session.overrides, frozen, session.environment.path());
                    }
                    crate::claude_runtime::session::run_session(session).await
                }
                Launch::Antigravity(mut session) => {
                    append_child_communication_contract(&mut session.system_prompt);
                    session.overrides.observer = external
                        .map(|run| run.observer(&session.identity, session.permission_mode));
                    session.parent_messages = parent_rx;
                    session.overrides.live_title = Some(std::sync::Arc::clone(&task_live_title));
                    if let Some(frozen) = frozen_cli {
                        apply_frozen(&mut session.overrides, frozen, session.environment.path());
                    }
                    crate::antigravity_runtime::session::run_session(session).await
                }
                Launch::Rho(bound) => {
                    let agent_id = bound.id().to_string();
                    let slot =
                        Arc::new(RunSlot::new(runtime_permits, &task_concurrency, task_queue));
                    let questions = parent_answers_questions.then(|| ParentQuestions {
                        bridge: host_input,
                        asker: ChildAsker {
                            run_id: run_id.clone(),
                            agent_id: agent_id.clone(),
                            session: Some(session.id().clone()),
                        },
                        slot: Arc::clone(&slot),
                    });
                    let notices = notice_target.map(|parent_session_id| {
                        Arc::new(DelegatedNoticePoster {
                            run_id,
                            agent_id,
                            parent_session_id,
                            notices,
                        }) as Arc<dyn NoticePoster>
                    });
                    let ran = headless_host::run_child(ChildRun {
                        bound,
                        config_path,
                        cwd,
                        prompt,
                        output_file,
                        role,
                        persistence,
                        questions,
                        slot: Arc::clone(&slot),
                        notices,
                        steering_slot: task_steering_slot,
                        cancellation: task_cancellation,
                        status_tx: task_status_tx,
                        live_title: task_live_title,
                        hook_host_labels,
                        approvals,
                        session,
                        added_dirs,
                        environment,
                        events,
                    })
                    .await;
                    // Explicitly: the runtime's tasks may hold the slot past
                    // the run's end.
                    slot.release();
                    ran
                }
            }
        });

        tokio::spawn(async move {
            let failure = match task.await {
                Ok(Ok(())) => None,
                Ok(Err(error)) => Some(format!("delegated agent failed: {error:#}")),
                Err(error) if error.is_panic() => Some("delegated agent task panicked".into()),
                Err(error) => Some(format!("delegated agent task failed to join: {error}")),
            };
            // Completion must imply a terminal status, even if a successful
            // runtime forgot to finalize its status sink. Parent waiters rely
            // on that invariant to drain this handle rather than wake forever.
            // Edited in place, under the channel's lock, so a title the
            // title task lands meanwhile is kept.
            let mut finished = None;
            status_tx.send_if_modified(|status| {
                if status.state.is_terminal() {
                    return false;
                }
                status.state = RunState::Error;
                status.error = Some(failure.unwrap_or_else(|| {
                    "delegated agent finished without a terminal status".into()
                }));
                status.mark_finished_now();
                finished = Some(status.clone());
                true
            });
            if let Some(finished) = finished {
                let _ = subagent::write_status(&persisted_output, &finished);
            }
            // Close the live window so late parent messages fail closed.
            if let Some(slot) = steering_slot {
                slot.clear();
            }
            let _delivery = super::notification_delivery::lock();
            completion_tx.send_replace(true);
        });

        Ok(AgentRunHandle {
            cancellation,
            status,
            completion,
            queue,
            session: child_session,
            messaging,
        })
    }
}

struct BoundLaunchRequest {
    bound: super::agent_binding::BoundAgent,
    prompt: String,
    run_id: String,
    /// A subagent with its parent, or a workflow node.
    role: SessionRole,
    workspace: LaunchWorkspace,
    /// Whether the child's session is saved: a Rho runtime child's session
    /// file, or a Claude child's Claude session. Antigravity has no unsaved
    /// session, so its children keep theirs either way.
    persistence: SessionPersistence,
    output_file: PathBuf,
    /// Whether a parent session listens for this child's questionnaires.
    /// `false` removes the capability before bind.
    parent_answers_questions: bool,
    /// Parent session that can receive this child's notices, when one is
    /// listening. `None` withholds both child notice tools.
    notice_target: Option<rho_sdk::SessionId>,
    frozen_cli: Option<FrozenCliLaunch>,
    hook_host_labels: rho_sdk::hooks::HookHostLabels,
    /// The session a Rho runtime child runs in, and another runtime's run
    /// is recorded under.
    session: ChildSession,
    title: RunTitle,
    /// Where the child sends its session's events.
    events: Option<ChildEventSender>,
    /// Where the children its agent starts on its own are recorded, if
    /// anywhere (see [`AgentLaunchRequest::runtime_children`]).
    runtime_children: Option<RecordedChildren>,
}

/// Where a run's title comes from.
enum RunTitle {
    /// A title model names it from its prompt.
    Generate,
    /// The title the run it follows up had.
    Keep(String),
}

struct FrozenCliLaunch {
    /// Frozen image, wrapped in its interpreter when the binary is a script.
    executable: crate::cli_runtime::CliExecutable,
    executable_identity: crate::workflow::ExecutableIdentity,
    // Keep descriptor-backed paths alive until the child has exited.
    _verified_executable: crate::workflow::VerifiedExecutable,
}

/// `agent`'s frozen executable, verified with interpreters found on
/// `search_path`.
fn frozen_cli_launch(
    agent: crate::workflow::ResolvedAgent,
    search_path: Option<&std::ffi::OsStr>,
) -> anyhow::Result<FrozenCliLaunch> {
    crate::workflow::HandleLaunch::CURRENT.ensure()?;
    let identity = agent
        .executable_identity
        .as_ref()
        .ok_or_else(|| anyhow::anyhow!("frozen CLI launch has no executable identity"))?;
    let verified_executable = crate::workflow::verify_executable_identity(identity, search_path)?;
    let script_path = crate::workflow::verified_handle_path(
        &verified_executable.executable.file,
        std::path::Path::new(&identity.file.canonical_path),
    )?;
    let executable = if let Some(interpreter) = &verified_executable.interpreter {
        let interpreter_path = crate::workflow::verified_handle_path(
            &interpreter.file,
            std::path::Path::new(&interpreter.identity.canonical_path),
        )?;
        let leading_args = verified_executable
            .interpreter_arguments
            .iter()
            .map(std::ffi::OsString::from)
            .chain([script_path.into_os_string()])
            .collect();
        crate::cli_runtime::CliExecutable::interpreted(interpreter_path, leading_args)
    } else {
        crate::cli_runtime::CliExecutable::from_path(script_path)
    };
    Ok(FrozenCliLaunch {
        executable,
        executable_identity: identity.clone(),
        _verified_executable: verified_executable,
    })
}

/// Launches `frozen` in place of the runtime's own executable, verifying
/// it just before spawn with any `#!/usr/bin/env` interpreter found on
/// `search_path`, the `PATH` of the environment the agent runs in (#1659).
fn apply_frozen(
    overrides: &mut crate::cli_runtime::CliSessionOverrides,
    frozen: FrozenCliLaunch,
    search_path: Option<std::ffi::OsString>,
) {
    let expected_identity = frozen.executable_identity;
    let verified_executable = frozen._verified_executable;
    overrides.executable = Some(frozen.executable);
    overrides.before_spawn = Some(Box::new(move |command| {
        crate::workflow::verify_executable_identity(&expected_identity, search_path.as_deref())
            .map_err(std::io::Error::other)?;
        let mut files = vec![&verified_executable.executable.file];
        if let Some(interpreter) = &verified_executable.interpreter {
            files.push(&interpreter.file);
        }
        crate::workflow::configure_handle_inheritance(command, &files)
            .map_err(std::io::Error::other)
    }));
}

/// External runtimes receive the same child contract as delegated Rho sessions.
fn append_child_communication_contract(prompt: &mut crate::agent::PromptPolicy) {
    let (crate::agent::PromptPolicy::Extend(text) | crate::agent::PromptPolicy::Replace(text)) =
        prompt;
    if !text.is_empty() {
        text.push_str("\n\n");
    }
    text.push_str(super::subagent_messaging::CHILD_COMMUNICATION_CONTRACT);
}

/// Posts a delegated child's notices to the parent session that started it.
struct DelegatedNoticePoster {
    run_id: String,
    agent_id: String,
    parent_session_id: rho_sdk::SessionId,
    notices: SubagentNoticeBridge,
}

impl NoticePoster for DelegatedNoticePoster {
    fn post(
        &self,
        message: ValidatedMessage,
        delivery: super::subagent_messaging::NoticeDelivery,
    ) -> Result<(), NoticePostError> {
        self.notices.post(SubagentNotice {
            acknowledged: Default::default(),
            run_id: self.run_id.clone(),
            agent_id: self.agent_id.clone(),
            parent_session_id: self.parent_session_id.clone(),
            message: message.into_string(),
            delivery,
        })
    }
}

struct RunTitleSinks {
    output_file: PathBuf,
    status_tx: tokio::sync::watch::Sender<RunStatus>,
    live_title: crate::run_artifacts::LiveRunTitle,
}

/// Names a run from `request`, beside the run, into `sinks`. A title that
/// fails leaves the run unnamed.
fn spawn_run_title(request: TitleRequest, sinks: RunTitleSinks) {
    tokio::spawn(async move {
        let title = match generate_title(request).await {
            Ok(title) => title,
            Err(error) => {
                tracing::warn!(error = %format!("{error:#}"), "could not title delegated run");
                return;
            }
        };
        {
            let mut slot = sinks
                .live_title
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            if slot.is_none() {
                *slot = Some(title.clone());
            }
        }
        sinks.status_tx.send_modify(|status| {
            if status.title.is_none() {
                status.title = Some(title.clone());
            }
        });
        let _ = subagent::apply_generated_title(&sinks.output_file, &title);
    });
}

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