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::SessionTools(_)
162 | Command::Update { .. }
163 | Command::Uninstall { .. }
164 | Command::Doctor { .. }
165 | Command::Worktrees { .. }
166 | Command::Acp(_)
167 | Command::Daemon { .. },
168 )
169 | None => Ok(None),
170 #[cfg(debug_assertions)]
171 Some(Command::AcpFixtureAgent(_)) => Ok(None),
172 #[cfg(feature = "browser")]
173 Some(Command::Browser { .. }) => Ok(None),
174 }
175}
176
177pub(super) fn emit_startup_failure(exit: AutomationExit) -> AutomationExit {
181 end_failed(&mut JsonlStream::stdout(), exit)
182}
183
184fn end_failed(stream: &mut JsonlStream, exit: AutomationExit) -> AutomationExit {
187 end_stream(stream, Err(exit)).expect_err("a failed run ends failed")
188}
189
190pub(super) fn end_stream(
193 stream: &mut JsonlStream,
194 exit: Result<(), AutomationExit>,
195) -> Result<(), AutomationExit> {
196 let end = match &exit {
197 Ok(()) => RunEnd::completed(),
198 Err(exit) => exit.end.clone(),
199 };
200 stream.end(&end);
201 stream_written(stream)?;
202 exit
203}
204
205pub(super) fn stream_written(stream: &JsonlStream) -> Result<(), AutomationExit> {
207 stream
208 .failure()
209 .map_or(Ok(()), |failure| Err(output_error(failure)))
210}
211
212pub(super) fn output_error(failure: &str) -> AutomationExit {
214 AutomationExit::new(1, TerminalReason::OutputError, failure)
215}
216
217pub(super) fn write_failed(error: io::Error) -> AutomationExit {
219 output_error(&format!("could not write output: {error}"))
220}
221
222pub(super) async fn run(prompt_text: String, startup: Startup<'_>) -> anyhow::Result<()> {
223 let mut jsonl = (startup.output == OutputFormat::Jsonl).then(JsonlStream::stdout);
224 let deadline = startup
225 .timeout
226 .map(|timeout| tokio::time::Instant::now() + timeout);
227 let mut stops = Stops::on_signals(ShutdownSignals::install()?).or_at(deadline);
230 let reporter_result = startup
233 .output_file
234 .as_ref()
235 .map(|path| {
236 RunReporter::new(
237 path.clone(),
238 startup.agent.artifact_identity(),
239 startup.cwd.clone(),
240 &prompt_text,
241 startup.output == OutputFormat::Text,
242 )
243 })
244 .transpose();
245 let mut reporter = match reporter_result {
246 Ok(reporter) => reporter,
247 Err(error) => {
248 let exit = AutomationExit::new(1, TerminalReason::OutputError, error.to_string());
249 let exit = match &mut jsonl {
250 Some(stream) => end_failed(stream, exit),
251 None => exit,
252 };
253 return Err(exit.into());
254 }
255 };
256
257 let terminal = run_session(
258 prompt_text,
259 &startup,
260 &mut stops,
261 reporter.as_mut(),
262 jsonl.as_mut(),
263 )
264 .await;
265 if let Some(reporter) = reporter.as_mut() {
266 match &terminal {
267 RunTerminal::Finished { answer, outcome } => match outcome {
268 WireOutcome::MaxSteps { .. } => reporter.finish_stopped(),
269 _ => reporter.finish_ok(answer),
270 },
271 RunTerminal::Timeout | RunTerminal::Interrupted(_) => reporter.finish_stopped(),
272 RunTerminal::Failed { error, .. } => reporter.finish_error(error),
273 }
274 }
275 emit_and_exit_terminal(terminal, jsonl.as_mut(), reporter.is_some())
276}
277
278async fn run_session(
285 prompt_text: String,
286 startup: &Startup<'_>,
287 stops: &mut Stops,
288 reporter: Option<&mut RunReporter>,
289 jsonl: Option<&mut JsonlStream>,
290) -> RunTerminal {
291 let build = SessionBuild {
292 launch: SessionLaunch {
293 config_path: startup.config_path.clone(),
294 left_out: startup.left_out,
295 diagnostics: startup.diagnostics.clone(),
296 agent: startup.agent.clone(),
297 prompt_suffix: None,
298 host_prompt: None,
299 },
300 host: HostCapabilities::unattended(UnattendedApprovals::Alone),
301 run: RunShape {
302 role: SessionRole::Run,
303 max_steps: startup.max_steps,
304 hook_labels: Default::default(),
305 },
306 };
307 let opening = SessionOpening {
308 build,
309 process_config: startup.config,
310 host_mcp: Default::default(),
311 cwd: &startup.cwd,
312 added_dirs: startup.added_dirs.clone(),
313 };
314 let mut view = HeadlessView::new();
315 if let Some(reporter) = reporter {
316 view = view.reporting_to(reporter);
317 }
318 if let Some(stream) = jsonl {
319 view = view.streaming_jsonl(stream);
320 }
321 let herdr = &startup.herdr;
322 let open = async {
323 let runtime = SessionRuntime::open_new(
324 opening,
325 rho_sdk::SessionId::new(),
326 startup.persistence,
327 None,
328 )
329 .await?;
330 let _ = herdr.report_state(HerdrState::Working, None, None).await;
331 anyhow::Ok(runtime)
332 };
333 let end = headless_host::run_prompt(
334 stops,
335 &mut view,
336 startup.config,
337 open,
338 |runtime, view, scope, process_config| {
339 Box::pin(run_text(runtime, view, scope, prompt_text, process_config))
340 },
341 )
342 .await;
343 let _ = herdr.report_state(HerdrState::Idle, None, None).await;
344 let _ = herdr.release().await;
345 let end = match view.output_failure() {
347 Some(message) => PromptEnd::Failed(output_error(&message).into()),
348 None => end,
349 };
350 let selection = startup.agent.rho_config().unwrap_or(startup.config);
352 let terminal = RunTerminal::of(end, selection);
353 view.end_turn(terminal.turn_outcome());
354 terminal
355}
356
357async fn run_text(
361 runtime: &mut SessionRuntime,
362 view: &mut HeadlessView<'_>,
363 prompt: &PromptScope,
364 text: String,
365 process_config: &Config,
366) -> anyhow::Result<TurnOutcome> {
367 let input = UserInput::text(text);
368 let home = crate::paths::home_dir();
369 let command = {
370 let scope = CommandScope::of(runtime, home.as_deref(), process_config);
371 tokio::select! {
373 biased;
374 () = prompt.cancellation().cancelled() => return Ok(TurnOutcome::Cancelled),
375 command = session_commands::resolve(input.clone(), &scope, RUN_COMMANDS) => command,
376 }
377 };
378 let rejected =
379 |message: String| -> anyhow::Error { AutomationExit::configuration(message).into() };
380 view.prompt(&input);
381 match command.map_err(|rejected_command| rejected(rejected_command.to_string()))? {
382 PromptCommand::Turn {
383 input: model,
384 calls,
385 } => {
386 let turn = Turn {
387 display: input,
388 model,
389 calls,
390 };
391 runtime
392 .run_prompt_turn(view, prompt, turn, process_config)
393 .await
394 }
395 PromptCommand::RunAsAgent(task) => {
396 runtime
397 .rebind_agent(prompt, &task, process_config)
398 .await
399 .map_err(|error| match error.downcast::<CommandRejected>() {
400 Ok(CommandRejected(message)) => rejected(message),
401 Err(error) => error,
402 })?;
403 view.bind(runtime, process_config);
405 let turn = Turn {
407 display: input,
408 model: task.input,
409 calls: Vec::new(),
410 };
411 runtime
412 .run_prompt_turn(view, prompt, turn, process_config)
413 .await
414 }
415 PromptCommand::Compact { .. } | PromptCommand::StartWorkflow(_) => Err(rejected(
418 "could not run the command: not available in rho run".into(),
419 )),
420 }
421}
422
423fn write_text_answer(answer: &rho_sdk::RunOutcome, has_reporter: bool) -> anyhow::Result<()> {
424 let result = (|| -> io::Result<()> {
425 let mut stdout = io::stdout().lock();
426 if has_reporter {
427 writeln!(stdout, "\n[subagent run complete]")?;
428 } else {
429 writeln!(stdout, "{}", answer.text())?;
430 }
431 stdout.flush()
432 })();
433 result.map_err(|error| write_failed(error).into())
434}
435
436const TIMEOUT_MESSAGE: &str = "rho run timed out";
437
438enum RunTerminal {
441 Finished {
443 answer: rho_sdk::RunOutcome,
444 outcome: WireOutcome,
445 },
446 Timeout,
447 Interrupted(ShutdownSignal),
448 Failed {
450 error: anyhow::Error,
451 turn: TurnError,
452 },
453}
454
455impl RunTerminal {
456 fn of(end: PromptEnd, selection: &Config) -> Self {
459 match end {
460 PromptEnd::Finished(answer) => Self::Finished {
461 outcome: outcome::finished(&answer),
462 answer,
463 },
464 PromptEnd::Stopped(StopCause::Timeout) => Self::Timeout,
465 PromptEnd::Stopped(StopCause::Interrupted(signal)) => Self::Interrupted(signal),
466 PromptEnd::Stopped(StopCause::Cancelled) => {
467 unreachable!("rho run's stops have no parent cancel")
468 }
469 PromptEnd::Failed(error) => Self::Failed {
470 turn: terminal::turn_error(&error, selection),
471 error,
472 },
473 }
474 }
475
476 fn turn_outcome(&self) -> WireOutcome {
479 match self {
480 Self::Finished { outcome, .. } => outcome.clone(),
481 Self::Timeout | Self::Interrupted(_) => WireOutcome::Cancelled,
482 Self::Failed { turn, .. } => WireOutcome::Failed {
483 error: turn.clone(),
484 },
485 }
486 }
487}
488
489fn emit_and_exit_terminal(
492 terminal: RunTerminal,
493 jsonl: Option<&mut JsonlStream>,
494 has_reporter: bool,
495) -> anyhow::Result<()> {
496 let (end, exit) = match terminal {
497 RunTerminal::Finished { answer, outcome } => {
498 if jsonl.is_none() {
499 write_text_answer(&answer, has_reporter)?;
500 }
501 match terminal::outcome_exit(&outcome) {
502 Ok(()) => (RunEnd::completed(), Ok(())),
503 Err(exit) => exited(exit),
504 }
505 }
506 RunTerminal::Timeout => exited(AutomationExit::new(
507 124,
508 TerminalReason::Timeout,
509 TIMEOUT_MESSAGE,
510 )),
511 RunTerminal::Interrupted(signal) => {
512 let interrupted = AutomationInterrupted::new(signal);
513 let end = RunEnd {
514 reason: TerminalReason::Interrupted,
515 exit_code: interrupted.exit_code(),
516 message: Some(interrupted.to_string()),
517 };
518 (end, Err(interrupted.into()))
519 }
520 RunTerminal::Failed { error, turn } => {
521 let exit = terminal::failure(&error, turn);
522 if exit.end.reason == TerminalReason::ProviderError {
523 print_provider_diagnostic(&error);
524 }
525 exited(exit)
526 }
527 };
528 if let Some(stream) = jsonl {
529 stream.end(&end);
530 stream_written(stream)?;
533 }
534 exit
535}
536
537fn exited(exit: AutomationExit) -> (RunEnd, anyhow::Result<()>) {
539 (exit.end.clone(), Err(exit.into()))
540}
541
542fn print_provider_diagnostic(error: &anyhow::Error) {
549 let diagnostic = error.chain().find_map(|cause| match cause.downcast_ref() {
550 Some(rho_sdk::Error::Provider(provider)) => provider.diagnostic(),
551 _ => None,
552 });
553 if let Some(diagnostic) = diagnostic {
554 eprintln!("provider diagnostic: {diagnostic}");
555 }
556}
557
558pub(super) fn prompt_from_stdin(parts: Vec<String>, read_stdin: bool) -> anyhow::Result<String> {
559 if !read_stdin && crate::stdio::stdin_is_redirected() {
560 anyhow::bail!(
561 "stdin is redirected but --stdin was not set; pass --stdin to include piped input"
562 );
563 }
564 prompt_from_reader(parts, read_stdin, &mut io::stdin())
565}
566
567fn prompt_from_reader(
568 parts: Vec<String>,
569 read_stdin: bool,
570 stdin: &mut impl Read,
571) -> anyhow::Result<String> {
572 let mut chunks = Vec::new();
573 let inline = parts.join(" ").trim().to_string();
574 if !inline.is_empty() {
575 chunks.push(inline);
576 }
577 if read_stdin {
578 let mut buffer = String::new();
579 stdin.read_to_string(&mut buffer)?;
580 let buffer = buffer.trim().to_string();
581 if !buffer.is_empty() {
582 chunks.push(buffer);
583 }
584 }
585
586 let prompt = chunks.join("\n\n");
587 if prompt.is_empty() {
588 anyhow::bail!("rho run requires a prompt argument or --stdin");
589 }
590 Ok(prompt)
591}
592
593#[cfg(test)]
594#[path = "automation_tests.rs"]
595mod tests;