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::{ChildAsker, SubagentHostInputBridge},
subagent_messaging::{
NoticePostError, NoticePoster, SteeringSlot, SubagentNotice, SubagentNoticeBridge,
ValidatedMessage,
},
subagent_pool::ChildEventSender,
title_agent::{generate_title, TitleRequest},
};
#[derive(Clone)]
pub(crate) struct AgentExecutor {
config: Arc<std::sync::RwLock<Config>>,
config_path: PathBuf,
cwd: PathBuf,
concurrency: AgentConcurrency,
host_input: SubagentHostInputBridge,
notices: SubagentNoticeBridge,
approvals: UnattendedApprovals,
added_dirs: Arc<std::sync::RwLock<crate::added_dirs::AddedDirs>>,
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,
pub(crate) parent_session_id: rho_sdk::SessionId,
pub(crate) parent_workspace: Option<PathBuf>,
pub(crate) persistence: SessionPersistence,
pub(crate) output_file: PathBuf,
pub(crate) events: Option<ChildEventSender>,
}
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,
pub(crate) session: Option<ChildSession>,
pub(crate) events: Option<ChildEventSender>,
}
#[derive(Clone, Debug)]
enum MessagingSupport {
Rho { steering: SteeringSlot },
Queued {
messages: crate::cli_runtime::parent_messages::ParentMessageHandle,
},
}
struct RuntimeMessagingPorts {
messaging: MessagingSupport,
steering_slot: Option<SteeringSlot>,
parent_rx: Option<crate::cli_runtime::parent_messages::ParentMessageInbox>,
}
impl MessagingSupport {
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,
queue: QueueWatch,
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()
}
pub(crate) fn queue(&self) -> QueueWatch {
self.queue.clone()
}
pub(crate) fn session(&self) -> Option<&rho_sdk::SessionId> {
self.session.as_ref()
}
pub(crate) fn clone_status_watch(&self) -> tokio::sync::watch::Receiver<RunStatus> {
self.status.clone()
}
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");
}
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();
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(inbox);
Self {
cancellation: RunCancellation::new(),
status: status_rx,
completion: completion_rx,
messaging: MessagingSupport::Queued { messages },
queue: QueueWatch::default(),
session: None,
}
}
}
impl AgentExecutor {
pub(crate) fn cwd(&self) -> &Path {
&self.cwd
}
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(),
}
}
pub(crate) fn with_environment(
mut self,
environment: crate::session_environment::SessionEnvironment,
) -> Self {
self.environment = environment;
self
}
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
}
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.choose_auth(auth);
}
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();
#[cfg(windows)]
capabilities.remove(&ToolCapability::Bash);
#[cfg(not(windows))]
capabilities.remove(&ToolCapability::Powershell);
let parent_answers_questions = self.host_input.is_bound();
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,
})
}
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, ¤t_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)
}
crate::workflow::AgentRuntime::ClaudeCli
| crate::workflow::AgentRuntime::Cursor
| crate::workflow::AgentRuntime::Antigravity => (
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,
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());
let queued = self.concurrency.join(capacity_class);
let queue = queued.watch();
let child_session = bound.rho_config().map(|_| session.id().clone());
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);
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_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 {
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(
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: 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),
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,
asker: ChildAsker {
run_id: run_id.clone(),
agent_id: agent_id.clone(),
session: Some(session.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}")),
};
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);
}
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,
role: SessionRole,
persistence: SessionPersistence,
output_file: PathBuf,
parent_answers_questions: bool,
notice_target: Option<rho_sdk::SessionId>,
frozen_cli: Option<FrozenCliLaunch>,
hook_host_labels: rho_sdk::hooks::HookHostLabels,
session: ChildSession,
events: Option<ChildEventSender>,
}
struct FrozenCliLaunch {
executable: crate::cli_runtime::CliExecutable,
arguments: Vec<String>,
executable_identity: crate::workflow::ExecutableIdentity,
_verified_executable: crate::workflow::VerifiedExecutable,
}
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,
})
}
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)
}));
}
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);
}
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(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;