rho-coding-agent 3.3.0

A fast Rust agent harness with a small footprint and opinionated defaults
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
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},
    headless_host::{self, ChildRun, ChildSession, ParentQuestions},
    session_runtime::{SessionRole, UnattendedApprovals},
    subagent_host_input::SubagentHostInputBridge,
    subagent_messaging::{
        NoticePostError, NoticePoster, SteeringSlot, SubagentNotice, SubagentNoticeBridge,
        ValidatedMessage,
    },
    subagent_pool::ChildEventSender,
};

#[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) definition: Arc<AgentDefinition>,
    pub(crate) model_override: Option<String>,
    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 a Rho child sends its session's events, when its host follows
    /// them.
    pub(crate) events: Option<ChildEventSender>,
}

/// 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 a Rho 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::Cursor { .. }
            | 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 Rho session the run writes; `None` on another runtime.
    session: Option<rho_sdk::SessionId>,
}

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 Rho session the run writes; `None` for a run on another runtime,
    /// which keeps that runtime's own session.
    pub(crate) fn session(&self) -> Option<&rho_sdk::SessionId> {
        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
    }

    /// 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.
    ///
    /// 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.provider = provider.to_string();
        config.model = model.to_string();
        config.reasoning = reasoning;
        config.auth = auth.to_string();
    }

    /// 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
    }

    pub(crate) fn spawn(&self, request: AgentLaunchRequest) -> anyhow::Result<AgentRunHandle> {
        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();
        // Notices share the parent-session binding, not the questionnaire one.
        let notice_target = self
            .notices
            .is_bound()
            .then(|| request.parent_session_id.clone());
        if !parent_answers_questions {
            capabilities.remove(&ToolCapability::Questionnaire);
        }
        let bound = AgentBinder::bind_with_credentials(
            request.definition,
            AgentInvocation {
                role: AgentRole::Delegated,
                available_tools: capabilities,
            },
            &config,
            request
                .model_override
                .as_deref()
                .map(super::agent_binding::ModelOverride::Reference),
            self.environment.credentials().as_ref(),
        )?;

        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,
            },
            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: ChildSession::New(rho_sdk::SessionId::new()),
            events: request.events,
        })
    }

    /// 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; these runtimes ignore it.
            crate::workflow::AgentRuntime::ClaudeCli
            | crate::workflow::AgentRuntime::Cursor
            | crate::workflow::AgentRuntime::Antigravity => (
                // 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,
            // 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,
            events: request.events,
        })
    }

    fn spawn_bound(&self, request: BoundLaunchRequest) -> anyhow::Result<AgentRunHandle> {
        let BoundLaunchRequest {
            bound,
            prompt,
            run_id,
            role,
            persistence,
            output_file,
            parent_answers_questions,
            notice_target,
            frozen_cli,
            hook_host_labels,
            session,
            events,
        } = request;

        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 that runtime's own.
        let child_session = bound.rho_config().map(|_| session.id().clone());
        let mut initial = bound.artifact_identity().queued_status();
        initial.parent_session_id = role.parent().map(ToString::to_string);
        // 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 cwd = self.cwd.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_status_tx = status_tx.clone();
        let title_run_id = run_id.clone();
        let title_output = output_file.clone();
        let title_cwd = self.cwd.clone();
        let title_prompt = prompt.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())?;

            spawn_run_title(
                &title_config,
                title_prompt,
                title_agent_id,
                title_run_id,
                title_cwd,
                environment.credentials(),
                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: 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.parent_messages = parent_rx;
                    session.persistence = persistence;
                    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::claude_runtime::session::run_session(session).await
                }
                Launch::Cursor(mut session) => {
                    append_child_communication_contract(&mut session.system_prompt);
                    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::cursor_runtime::session::run_session(session).await
                }
                Launch::Antigravity(mut session) => {
                    append_child_communication_contract(&mut session.system_prompt);
                    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 questions = parent_answers_questions.then(|| ParentQuestions {
                        bridge: host_input,
                        run_id: run_id.clone(),
                        agent_id: agent_id.clone(),
                    });
                    let notices = notice_target.map(|parent_session_id| {
                        Arc::new(DelegatedNoticePoster {
                            run_id,
                            agent_id,
                            parent_session_id,
                            notices,
                        }) as Arc<dyn NoticePoster>
                    });
                    headless_host::run_child(ChildRun {
                        bound,
                        config_path,
                        cwd,
                        prompt,
                        output_file,
                        role,
                        persistence,
                        questions,
                        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
                }
            }
        });

        let failure_status = status.clone();
        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.
            let mut finished = failure_status.borrow().clone();
            if !finished.state.is_terminal() {
                finished.state = RunState::Error;
                finished.error = Some(failure.unwrap_or_else(|| {
                    "delegated agent finished without a terminal status".into()
                }));
                finished.mark_finished_now();
                status_tx.send_replace(finished.clone());
                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,
    /// Whether the child's session is saved: a Rho runtime child's session
    /// file, or a Claude child's Claude session. Cursor and Antigravity have
    /// no unsaved session, so their 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; other runtimes ignore it.
    session: ChildSession,
    /// Where a Rho runtime child sends its session's events; other runtimes
    /// ignore it.
    events: Option<ChildEventSender>,
}

struct FrozenCliLaunch {
    /// Frozen image, wrapped in its interpreter when the binary is a script.
    executable: crate::cli_runtime::CliExecutable,
    /// The CLI's own frozen argv; never contains the interpreter prefix, so
    /// runtimes can regenerate argv and overlay identity flags from it.
    arguments: Vec<String>,
    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,
        arguments: agent.arguments,
        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.frozen_argv = Some(frozen.arguments);
    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,
}

fn spawn_run_title(
    config: &Config,
    prompt: String,
    agent_id: String,
    run_id: String,
    workspace_path: PathBuf,
    credentials: Arc<dyn rho_providers::credentials::CredentialStore>,
    sinks: RunTitleSinks,
) {
    let model = crate::title::title_model_from_config(config);
    let session_id =
        rho_sdk::SessionId::from_string(run_id).unwrap_or_else(|_| rho_sdk::SessionId::new());
    tokio::spawn(async move {
        let usage_recording = crate::usage::default_recording().await;
        let cancellation = rho_sdk::CancellationToken::new();
        let title = crate::title::generate_title(
            model,
            format!("Agent name: {agent_id}\n\nTask assignment:\n{prompt}"),
            session_id,
            workspace_path,
            credentials,
            usage_recording,
            cancellation,
        )
        .await;
        let Ok(title) = title else {
            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;