use std::{path::PathBuf, sync::Arc};
use rho_sdk::UserInput;
use rho_tools::cancellation::RunCancellation;
use super::{run_prompt, HeadlessView, ParentQuestions, PromptEnd, RunReporter, Stops};
use crate::{
app::{
agent_binding::BoundAgent,
cli_config::{settle_bound_config, ProviderRefreshStatus, SettledConfig},
session_runtime::{
HostCapabilities, LeftOut, NodeSession, QuestionSupport, RunShape, SessionBuild,
SessionLaunch, SessionOpening, SessionRole, SessionRuntime, Turn, TurnStart,
UnattendedApprovals,
},
shutdown_signal::ShutdownSignals,
subagent_messaging::{NoticePoster, SteeringSlot, CHILD_COMMUNICATION_CONTRACT},
subagent_pool::ChildEventSender,
},
session::SessionPersistence,
subagent::RunStatus,
};
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum ChildSession {
New(rho_sdk::SessionId),
Reopen(rho_sdk::SessionId),
}
impl ChildSession {
pub(crate) fn id(&self) -> &rho_sdk::SessionId {
match self {
Self::New(id) | Self::Reopen(id) => id,
}
}
}
pub(crate) struct ChildRun {
pub(crate) bound: BoundAgent,
pub(crate) config_path: PathBuf,
pub(crate) cwd: PathBuf,
pub(crate) prompt: String,
pub(crate) output_file: PathBuf,
pub(crate) role: SessionRole,
pub(crate) persistence: SessionPersistence,
pub(crate) questions: Option<ParentQuestions>,
pub(crate) notices: Option<Arc<dyn NoticePoster>>,
pub(crate) steering_slot: Option<SteeringSlot>,
pub(crate) cancellation: RunCancellation,
pub(crate) status_tx: tokio::sync::watch::Sender<RunStatus>,
pub(crate) live_title: crate::run_artifacts::LiveRunTitle,
pub(crate) hook_host_labels: rho_sdk::hooks::HookHostLabels,
pub(crate) approvals: UnattendedApprovals,
pub(crate) session: ChildSession,
pub(crate) added_dirs: crate::added_dirs::AddedDirs,
pub(crate) environment: crate::session_environment::SessionEnvironment,
pub(crate) events: Option<ChildEventSender>,
}
pub(crate) async fn run_child(run: ChildRun) -> anyhow::Result<()> {
let ChildRun {
bound,
config_path,
cwd,
prompt,
output_file,
role,
persistence,
questions,
notices,
steering_slot,
cancellation,
status_tx,
live_title,
hook_host_labels,
approvals,
session,
added_dirs,
environment,
events,
} = run;
let bound_config = bound
.rho_config()
.ok_or_else(|| anyhow::anyhow!("agent {} does not run on rho", bound.id()))?
.clone();
let SettledConfig {
config,
diagnostics,
} = settle_bound_config(
bound_config,
&bound,
environment.credentials().as_ref(),
&ProviderRefreshStatus::NotAttempted,
rho_providers::model::ReasoningRequestSource::PersistedOrDefault,
)
.await?;
let started_status = status_tx.borrow().clone();
let mut reporter = RunReporter::continue_from(
output_file,
started_status,
cwd.clone(),
&prompt,
status_tx,
live_title,
steering_slot.clone(),
)?;
let max_steps = std::num::NonZeroUsize::new(
bound
.step_limit()
.try_into()
.map_err(|_| anyhow::anyhow!("agent step limit does not fit this platform"))?,
)
.ok_or_else(|| anyhow::anyhow!("agent step limit must be positive"))?;
let mut stops = Stops::on_signals(ShutdownSignals::install()?).or_cancelled(cancellation);
let (id, saved) = match session {
ChildSession::New(id) => (id, None),
ChildSession::Reopen(id) => match NodeSession::find(&cwd, &id, &bound) {
Ok(NodeSession::Unsaved) => (id, None),
Ok(NodeSession::Saved(stored)) => (id, Some(stored)),
Ok(NodeSession::Answered(reply)) => {
reporter.finish_answered(reply);
return Ok(());
}
Err(error) => {
reporter.finish_error(&error);
return Err(error);
}
},
};
let build = SessionBuild {
launch: SessionLaunch {
config_path,
left_out: LeftOut {
subagents: true,
..LeftOut::default()
},
diagnostics,
agent: bound,
prompt_suffix: Some(CHILD_COMMUNICATION_CONTRACT),
},
host: HostCapabilities {
surfaces: None,
pull_requests: None,
questions: match &questions {
Some(_) => QuestionSupport::Available,
None => QuestionSupport::Unavailable,
},
environment,
parent_notices: notices,
..HostCapabilities::unattended(approvals)
},
run: RunShape {
role,
max_steps: Some(max_steps),
hook_labels: hook_host_labels,
},
};
let opening = SessionOpening {
build,
process_config: &config,
host_mcp: Default::default(),
cwd: &cwd,
added_dirs,
};
let open = async {
let runtime = match saved {
None => SessionRuntime::open_new(opening, id, persistence).await?,
Some(stored) => SessionRuntime::open_saved(opening, stored).await?,
};
if let Some(slot) = &steering_slot {
slot.publish(runtime.handle());
}
anyhow::Ok(runtime)
};
let mut view = HeadlessView::new()
.reporting_to(&mut reporter)
.with_parent_questions(questions);
if let Some(events) = events {
view = view.streaming_to(events);
}
let end = run_prompt(
&mut stops,
&mut view,
&config,
open,
|runtime, view, scope, process_config| {
let start = if runtime.has_conversation() {
TurnStart::Continue
} else {
let input = UserInput::text(prompt);
view.prompt(&input);
TurnStart::Prompt(Turn {
display: input.clone(),
model: input,
calls: Vec::new(),
})
};
Box::pin(runtime.run_prompt_turn(view, scope, start, process_config))
},
)
.await;
drop(view);
match end {
PromptEnd::Finished(outcome) => reporter.finish_ok(&outcome),
PromptEnd::Stopped(_) => reporter.finish_stopped(),
PromptEnd::Failed(error) => {
reporter.finish_error(&error);
return Err(error);
}
}
Ok(())
}