1use std::{
10 fmt,
11 io::{self, Read, Write},
12 num::NonZeroUsize,
13 path::PathBuf,
14 time::Duration,
15};
16
17use rho_protocol::{TurnError, TurnOutcome as WireOutcome};
18use rho_sdk::UserInput;
19
20use super::{
21 agent_binding::BoundAgent,
22 automation_protocol::{JsonlStream, RunEnd, TerminalReason},
23 headless_host::{self, HeadlessView, PromptEnd, RunReporter, StopCause, Stops},
24 session_commands::{self, BuiltInCommand, CommandScope, CommandSet, Hosting, PromptCommand},
25 session_events::outcome,
26 session_runtime::{
27 CommandRejected, HostCapabilities, PromptScope, RunShape, SessionBuild, SessionLaunch,
28 SessionOpening, SessionRole, SessionRuntime, Turn, TurnOutcome, UnattendedApprovals,
29 },
30 shutdown_signal::{ShutdownSignal, ShutdownSignals},
31};
32use crate::{
33 cli::{Command, OutputFormat},
34 config::Config,
35 diagnostics::RuntimeDiagnostics,
36 herdr::{HerdrReporter, HerdrState},
37 session::SessionPersistence,
38};
39
40mod terminal;
41
42pub(super) use terminal::outcome_exit;
43
44#[derive(Clone, Debug)]
46pub struct AutomationExit {
47 end: RunEnd,
48}
49
50impl AutomationExit {
51 pub(super) fn new(code: u8, reason: TerminalReason, message: impl Into<String>) -> Self {
52 Self {
53 end: RunEnd {
54 reason,
55 exit_code: code,
56 message: Some(message.into()),
57 },
58 }
59 }
60
61 pub(super) fn configuration(message: impl Into<String>) -> Self {
63 Self::new(2, TerminalReason::ConfigurationError, message)
64 }
65
66 pub(super) fn authentication(message: impl Into<String>) -> Self {
69 Self::new(1, TerminalReason::Authentication, message)
70 }
71
72 pub(super) fn other(message: impl Into<String>) -> Self {
74 Self::new(1, TerminalReason::OtherError, message)
75 }
76
77 pub fn exit_code(&self) -> u8 {
79 self.end.exit_code
80 }
81}
82
83impl fmt::Display for AutomationExit {
84 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
85 formatter.write_str(self.end.message.as_deref().unwrap_or_default())
86 }
87}
88
89impl std::error::Error for AutomationExit {}
90
91#[derive(Debug)]
93pub struct AutomationInterrupted {
94 signal: ShutdownSignal,
95}
96
97impl AutomationInterrupted {
98 fn new(signal: ShutdownSignal) -> Self {
99 Self { signal }
100 }
101
102 pub fn exit_code(&self) -> u8 {
104 self.signal.exit_code()
105 }
106}
107
108impl fmt::Display for AutomationInterrupted {
109 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
110 write!(formatter, "rho run interrupted by {}", self.signal)
111 }
112}
113
114impl std::error::Error for AutomationInterrupted {}
115
116pub(super) struct Startup<'a> {
118 pub config: &'a Config,
119 pub config_path: PathBuf,
120 pub cwd: PathBuf,
121 pub left_out: super::session_runtime::LeftOut,
123 pub agent: BoundAgent,
124 pub output_file: Option<PathBuf>,
125 pub output: OutputFormat,
126 pub max_steps: Option<NonZeroUsize>,
127 pub timeout: Option<Duration>,
128 pub persistence: SessionPersistence,
130 pub diagnostics: RuntimeDiagnostics,
131 pub herdr: HerdrReporter,
132 pub added_dirs: crate::added_dirs::AddedDirs,
134}
135
136const RUN_COMMANDS: CommandSet = CommandSet {
140 built_ins: &[BuiltInCommand::Init],
141 workflows: Hosting::Refused,
142 agents: Hosting::Runs,
143 sessions_label: "rho run",
144};
145
146pub(super) fn prompt_for_command(command: &Option<Command>) -> anyhow::Result<Option<String>> {
147 match command {
148 Some(Command::Run { prompt, stdin, .. }) => {
149 prompt_from_stdin(prompt.clone(), *stdin).map(Some)
150 }
151 Some(
152 Command::Attach { .. }
153 | Command::Login { .. }
154 | Command::CredentialStore { .. }
155 | Command::Sessions { .. }
156 | Command::Mcp { .. }
157 | Command::ModelPrompt { .. }
158 | Command::Plugins { .. }
159 | Command::Workflow { .. }
160 | Command::WorkflowPlannerWorker
161 | Command::Update { .. }
162 | Command::Uninstall { .. }
163 | Command::Doctor { .. }
164 | Command::Worktrees { .. }
165 | Command::Acp(_)
166 | Command::Daemon { .. },
167 )
168 | None => Ok(None),
169 #[cfg(debug_assertions)]
170 Some(Command::AcpFixtureAgent(_)) => Ok(None),
171 }
172}
173
174pub(super) fn emit_startup_failure(exit: AutomationExit) -> AutomationExit {
178 end_failed(&mut JsonlStream::stdout(), exit)
179}
180
181fn end_failed(stream: &mut JsonlStream, exit: AutomationExit) -> AutomationExit {
184 end_stream(stream, Err(exit)).expect_err("a failed run ends failed")
185}
186
187pub(super) fn end_stream(
190 stream: &mut JsonlStream,
191 exit: Result<(), AutomationExit>,
192) -> Result<(), AutomationExit> {
193 let end = match &exit {
194 Ok(()) => RunEnd::completed(),
195 Err(exit) => exit.end.clone(),
196 };
197 stream.end(&end);
198 stream_written(stream)?;
199 exit
200}
201
202pub(super) fn stream_written(stream: &JsonlStream) -> Result<(), AutomationExit> {
204 stream
205 .failure()
206 .map_or(Ok(()), |failure| Err(output_error(failure)))
207}
208
209pub(super) fn output_error(failure: &str) -> AutomationExit {
211 AutomationExit::new(1, TerminalReason::OutputError, failure)
212}
213
214pub(super) fn write_failed(error: io::Error) -> AutomationExit {
216 output_error(&format!("could not write output: {error}"))
217}
218
219pub(super) async fn run(prompt_text: String, startup: Startup<'_>) -> anyhow::Result<()> {
220 let mut jsonl = (startup.output == OutputFormat::Jsonl).then(JsonlStream::stdout);
221 let deadline = startup
222 .timeout
223 .map(|timeout| tokio::time::Instant::now() + timeout);
224 let mut stops = Stops::on_signals(ShutdownSignals::install()?).or_at(deadline);
227 let reporter_result = startup
230 .output_file
231 .as_ref()
232 .map(|path| {
233 RunReporter::new(
234 path.clone(),
235 startup.agent.artifact_identity(),
236 startup.cwd.clone(),
237 &prompt_text,
238 startup.output == OutputFormat::Text,
239 )
240 })
241 .transpose();
242 let mut reporter = match reporter_result {
243 Ok(reporter) => reporter,
244 Err(error) => {
245 let exit = AutomationExit::new(1, TerminalReason::OutputError, error.to_string());
246 let exit = match &mut jsonl {
247 Some(stream) => end_failed(stream, exit),
248 None => exit,
249 };
250 return Err(exit.into());
251 }
252 };
253
254 let terminal = run_session(
255 prompt_text,
256 &startup,
257 &mut stops,
258 reporter.as_mut(),
259 jsonl.as_mut(),
260 )
261 .await;
262 if let Some(reporter) = reporter.as_mut() {
263 match &terminal {
264 RunTerminal::Finished { answer, outcome } => match outcome {
265 WireOutcome::MaxSteps { .. } => reporter.finish_stopped(),
266 _ => reporter.finish_ok(answer),
267 },
268 RunTerminal::Timeout | RunTerminal::Interrupted(_) => reporter.finish_stopped(),
269 RunTerminal::Failed { error, .. } => reporter.finish_error(error),
270 }
271 }
272 emit_and_exit_terminal(terminal, jsonl.as_mut(), reporter.is_some())
273}
274
275async fn run_session(
282 prompt_text: String,
283 startup: &Startup<'_>,
284 stops: &mut Stops,
285 reporter: Option<&mut RunReporter>,
286 jsonl: Option<&mut JsonlStream>,
287) -> RunTerminal {
288 let build = SessionBuild {
289 launch: SessionLaunch {
290 config_path: startup.config_path.clone(),
291 left_out: startup.left_out,
292 diagnostics: startup.diagnostics.clone(),
293 agent: startup.agent.clone(),
294 prompt_suffix: None,
295 },
296 host: HostCapabilities::unattended(UnattendedApprovals::Alone),
297 run: RunShape {
298 role: SessionRole::Run,
299 max_steps: startup.max_steps,
300 hook_labels: Default::default(),
301 },
302 };
303 let opening = SessionOpening {
304 build,
305 process_config: startup.config,
306 host_mcp: Default::default(),
307 cwd: &startup.cwd,
308 added_dirs: startup.added_dirs.clone(),
309 };
310 let mut view = HeadlessView::new();
311 if let Some(reporter) = reporter {
312 view = view.reporting_to(reporter);
313 }
314 if let Some(stream) = jsonl {
315 view = view.streaming_jsonl(stream);
316 }
317 let herdr = &startup.herdr;
318 let open = async {
319 let runtime =
320 SessionRuntime::open_new(opening, rho_sdk::SessionId::new(), startup.persistence)
321 .await?;
322 let _ = herdr.report_state(HerdrState::Working, None, None).await;
323 anyhow::Ok(runtime)
324 };
325 let end = headless_host::run_prompt(
326 stops,
327 &mut view,
328 startup.config,
329 open,
330 |runtime, view, scope, process_config| {
331 Box::pin(run_text(runtime, view, scope, prompt_text, process_config))
332 },
333 )
334 .await;
335 let _ = herdr.report_state(HerdrState::Idle, None, None).await;
336 let _ = herdr.release().await;
337 let end = match view.output_failure() {
339 Some(message) => PromptEnd::Failed(output_error(&message).into()),
340 None => end,
341 };
342 let selection = startup.agent.rho_config().unwrap_or(startup.config);
344 let terminal = RunTerminal::of(end, selection);
345 view.end_turn(terminal.turn_outcome());
346 terminal
347}
348
349async fn run_text(
353 runtime: &mut SessionRuntime,
354 view: &mut HeadlessView<'_>,
355 prompt: &PromptScope,
356 text: String,
357 process_config: &Config,
358) -> anyhow::Result<TurnOutcome> {
359 let input = UserInput::text(text);
360 let home = crate::paths::home_dir();
361 let command = {
362 let scope = CommandScope::of(runtime, home.as_deref(), process_config);
363 tokio::select! {
365 biased;
366 () = prompt.cancellation().cancelled() => return Ok(TurnOutcome::Cancelled),
367 command = session_commands::resolve(input.clone(), &scope, RUN_COMMANDS) => command,
368 }
369 };
370 let rejected =
371 |message: String| -> anyhow::Error { AutomationExit::configuration(message).into() };
372 view.prompt(&input);
373 match command.map_err(|rejected_command| rejected(rejected_command.to_string()))? {
374 PromptCommand::Turn {
375 input: model,
376 calls,
377 } => {
378 let turn = Turn {
379 display: input,
380 model,
381 calls,
382 };
383 runtime
384 .run_prompt_turn(view, prompt, turn, process_config)
385 .await
386 }
387 PromptCommand::RunAsAgent(task) => {
388 runtime
389 .rebind_agent(prompt, &task, process_config)
390 .await
391 .map_err(|error| match error.downcast::<CommandRejected>() {
392 Ok(CommandRejected(message)) => rejected(message),
393 Err(error) => error,
394 })?;
395 view.bind(runtime, process_config);
397 let turn = Turn {
399 display: input,
400 model: task.input,
401 calls: Vec::new(),
402 };
403 runtime
404 .run_prompt_turn(view, prompt, turn, process_config)
405 .await
406 }
407 PromptCommand::Compact { .. } | PromptCommand::StartWorkflow(_) => Err(rejected(
410 "could not run the command: not available in rho run".into(),
411 )),
412 }
413}
414
415fn write_text_answer(answer: &rho_sdk::RunOutcome, has_reporter: bool) -> anyhow::Result<()> {
416 let result = (|| -> io::Result<()> {
417 let mut stdout = io::stdout().lock();
418 if has_reporter {
419 writeln!(stdout, "\n[subagent run complete]")?;
420 } else {
421 writeln!(stdout, "{}", answer.text())?;
422 }
423 stdout.flush()
424 })();
425 result.map_err(|error| write_failed(error).into())
426}
427
428const TIMEOUT_MESSAGE: &str = "rho run timed out";
429
430enum RunTerminal {
433 Finished {
435 answer: rho_sdk::RunOutcome,
436 outcome: WireOutcome,
437 },
438 Timeout,
439 Interrupted(ShutdownSignal),
440 Failed {
442 error: anyhow::Error,
443 turn: TurnError,
444 },
445}
446
447impl RunTerminal {
448 fn of(end: PromptEnd, selection: &Config) -> Self {
451 match end {
452 PromptEnd::Finished(answer) => Self::Finished {
453 outcome: outcome::finished(&answer),
454 answer,
455 },
456 PromptEnd::Stopped(StopCause::Timeout) => Self::Timeout,
457 PromptEnd::Stopped(StopCause::Interrupted(signal)) => Self::Interrupted(signal),
458 PromptEnd::Stopped(StopCause::Cancelled) => {
459 unreachable!("rho run's stops have no parent cancel")
460 }
461 PromptEnd::Failed(error) => Self::Failed {
462 turn: terminal::turn_error(&error, selection),
463 error,
464 },
465 }
466 }
467
468 fn turn_outcome(&self) -> WireOutcome {
471 match self {
472 Self::Finished { outcome, .. } => outcome.clone(),
473 Self::Timeout | Self::Interrupted(_) => WireOutcome::Cancelled,
474 Self::Failed { turn, .. } => WireOutcome::Failed {
475 error: turn.clone(),
476 },
477 }
478 }
479}
480
481fn emit_and_exit_terminal(
484 terminal: RunTerminal,
485 jsonl: Option<&mut JsonlStream>,
486 has_reporter: bool,
487) -> anyhow::Result<()> {
488 let (end, exit) = match terminal {
489 RunTerminal::Finished { answer, outcome } => {
490 if jsonl.is_none() {
491 write_text_answer(&answer, has_reporter)?;
492 }
493 match terminal::outcome_exit(&outcome) {
494 Ok(()) => (RunEnd::completed(), Ok(())),
495 Err(exit) => exited(exit),
496 }
497 }
498 RunTerminal::Timeout => exited(AutomationExit::new(
499 124,
500 TerminalReason::Timeout,
501 TIMEOUT_MESSAGE,
502 )),
503 RunTerminal::Interrupted(signal) => {
504 let interrupted = AutomationInterrupted::new(signal);
505 let end = RunEnd {
506 reason: TerminalReason::Interrupted,
507 exit_code: interrupted.exit_code(),
508 message: Some(interrupted.to_string()),
509 };
510 (end, Err(interrupted.into()))
511 }
512 RunTerminal::Failed { error, turn } => {
513 let exit = terminal::failure(&error, turn);
514 if exit.end.reason == TerminalReason::ProviderError {
515 print_provider_diagnostic(&error);
516 }
517 exited(exit)
518 }
519 };
520 if let Some(stream) = jsonl {
521 stream.end(&end);
522 stream_written(stream)?;
525 }
526 exit
527}
528
529fn exited(exit: AutomationExit) -> (RunEnd, anyhow::Result<()>) {
531 (exit.end.clone(), Err(exit.into()))
532}
533
534fn print_provider_diagnostic(error: &anyhow::Error) {
541 let diagnostic = error.chain().find_map(|cause| match cause.downcast_ref() {
542 Some(rho_sdk::Error::Provider(provider)) => provider.diagnostic(),
543 _ => None,
544 });
545 if let Some(diagnostic) = diagnostic {
546 eprintln!("provider diagnostic: {diagnostic}");
547 }
548}
549
550pub(super) fn prompt_from_stdin(parts: Vec<String>, read_stdin: bool) -> anyhow::Result<String> {
551 if !read_stdin && crate::stdio::stdin_is_redirected() {
552 anyhow::bail!(
553 "stdin is redirected but --stdin was not set; pass --stdin to include piped input"
554 );
555 }
556 prompt_from_reader(parts, read_stdin, &mut io::stdin())
557}
558
559fn prompt_from_reader(
560 parts: Vec<String>,
561 read_stdin: bool,
562 stdin: &mut impl Read,
563) -> anyhow::Result<String> {
564 let mut chunks = Vec::new();
565 let inline = parts.join(" ").trim().to_string();
566 if !inline.is_empty() {
567 chunks.push(inline);
568 }
569 if read_stdin {
570 let mut buffer = String::new();
571 stdin.read_to_string(&mut buffer)?;
572 let buffer = buffer.trim().to_string();
573 if !buffer.is_empty() {
574 chunks.push(buffer);
575 }
576 }
577
578 let prompt = chunks.join("\n\n");
579 if prompt.is_empty() {
580 anyhow::bail!("rho run requires a prompt argument or --stdin");
581 }
582 Ok(prompt)
583}
584
585#[cfg(test)]
586#[path = "automation_tests.rs"]
587mod tests;