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 = SessionRuntime::open_new(
320 opening,
321 rho_sdk::SessionId::new(),
322 startup.persistence,
323 None,
324 )
325 .await?;
326 let _ = herdr.report_state(HerdrState::Working, None, None).await;
327 anyhow::Ok(runtime)
328 };
329 let end = headless_host::run_prompt(
330 stops,
331 &mut view,
332 startup.config,
333 open,
334 |runtime, view, scope, process_config| {
335 Box::pin(run_text(runtime, view, scope, prompt_text, process_config))
336 },
337 )
338 .await;
339 let _ = herdr.report_state(HerdrState::Idle, None, None).await;
340 let _ = herdr.release().await;
341 let end = match view.output_failure() {
343 Some(message) => PromptEnd::Failed(output_error(&message).into()),
344 None => end,
345 };
346 let selection = startup.agent.rho_config().unwrap_or(startup.config);
348 let terminal = RunTerminal::of(end, selection);
349 view.end_turn(terminal.turn_outcome());
350 terminal
351}
352
353async fn run_text(
357 runtime: &mut SessionRuntime,
358 view: &mut HeadlessView<'_>,
359 prompt: &PromptScope,
360 text: String,
361 process_config: &Config,
362) -> anyhow::Result<TurnOutcome> {
363 let input = UserInput::text(text);
364 let home = crate::paths::home_dir();
365 let command = {
366 let scope = CommandScope::of(runtime, home.as_deref(), process_config);
367 tokio::select! {
369 biased;
370 () = prompt.cancellation().cancelled() => return Ok(TurnOutcome::Cancelled),
371 command = session_commands::resolve(input.clone(), &scope, RUN_COMMANDS) => command,
372 }
373 };
374 let rejected =
375 |message: String| -> anyhow::Error { AutomationExit::configuration(message).into() };
376 view.prompt(&input);
377 match command.map_err(|rejected_command| rejected(rejected_command.to_string()))? {
378 PromptCommand::Turn {
379 input: model,
380 calls,
381 } => {
382 let turn = Turn {
383 display: input,
384 model,
385 calls,
386 };
387 runtime
388 .run_prompt_turn(view, prompt, turn, process_config)
389 .await
390 }
391 PromptCommand::RunAsAgent(task) => {
392 runtime
393 .rebind_agent(prompt, &task, process_config)
394 .await
395 .map_err(|error| match error.downcast::<CommandRejected>() {
396 Ok(CommandRejected(message)) => rejected(message),
397 Err(error) => error,
398 })?;
399 view.bind(runtime, process_config);
401 let turn = Turn {
403 display: input,
404 model: task.input,
405 calls: Vec::new(),
406 };
407 runtime
408 .run_prompt_turn(view, prompt, turn, process_config)
409 .await
410 }
411 PromptCommand::Compact { .. } | PromptCommand::StartWorkflow(_) => Err(rejected(
414 "could not run the command: not available in rho run".into(),
415 )),
416 }
417}
418
419fn write_text_answer(answer: &rho_sdk::RunOutcome, has_reporter: bool) -> anyhow::Result<()> {
420 let result = (|| -> io::Result<()> {
421 let mut stdout = io::stdout().lock();
422 if has_reporter {
423 writeln!(stdout, "\n[subagent run complete]")?;
424 } else {
425 writeln!(stdout, "{}", answer.text())?;
426 }
427 stdout.flush()
428 })();
429 result.map_err(|error| write_failed(error).into())
430}
431
432const TIMEOUT_MESSAGE: &str = "rho run timed out";
433
434enum RunTerminal {
437 Finished {
439 answer: rho_sdk::RunOutcome,
440 outcome: WireOutcome,
441 },
442 Timeout,
443 Interrupted(ShutdownSignal),
444 Failed {
446 error: anyhow::Error,
447 turn: TurnError,
448 },
449}
450
451impl RunTerminal {
452 fn of(end: PromptEnd, selection: &Config) -> Self {
455 match end {
456 PromptEnd::Finished(answer) => Self::Finished {
457 outcome: outcome::finished(&answer),
458 answer,
459 },
460 PromptEnd::Stopped(StopCause::Timeout) => Self::Timeout,
461 PromptEnd::Stopped(StopCause::Interrupted(signal)) => Self::Interrupted(signal),
462 PromptEnd::Stopped(StopCause::Cancelled) => {
463 unreachable!("rho run's stops have no parent cancel")
464 }
465 PromptEnd::Failed(error) => Self::Failed {
466 turn: terminal::turn_error(&error, selection),
467 error,
468 },
469 }
470 }
471
472 fn turn_outcome(&self) -> WireOutcome {
475 match self {
476 Self::Finished { outcome, .. } => outcome.clone(),
477 Self::Timeout | Self::Interrupted(_) => WireOutcome::Cancelled,
478 Self::Failed { turn, .. } => WireOutcome::Failed {
479 error: turn.clone(),
480 },
481 }
482 }
483}
484
485fn emit_and_exit_terminal(
488 terminal: RunTerminal,
489 jsonl: Option<&mut JsonlStream>,
490 has_reporter: bool,
491) -> anyhow::Result<()> {
492 let (end, exit) = match terminal {
493 RunTerminal::Finished { answer, outcome } => {
494 if jsonl.is_none() {
495 write_text_answer(&answer, has_reporter)?;
496 }
497 match terminal::outcome_exit(&outcome) {
498 Ok(()) => (RunEnd::completed(), Ok(())),
499 Err(exit) => exited(exit),
500 }
501 }
502 RunTerminal::Timeout => exited(AutomationExit::new(
503 124,
504 TerminalReason::Timeout,
505 TIMEOUT_MESSAGE,
506 )),
507 RunTerminal::Interrupted(signal) => {
508 let interrupted = AutomationInterrupted::new(signal);
509 let end = RunEnd {
510 reason: TerminalReason::Interrupted,
511 exit_code: interrupted.exit_code(),
512 message: Some(interrupted.to_string()),
513 };
514 (end, Err(interrupted.into()))
515 }
516 RunTerminal::Failed { error, turn } => {
517 let exit = terminal::failure(&error, turn);
518 if exit.end.reason == TerminalReason::ProviderError {
519 print_provider_diagnostic(&error);
520 }
521 exited(exit)
522 }
523 };
524 if let Some(stream) = jsonl {
525 stream.end(&end);
526 stream_written(stream)?;
529 }
530 exit
531}
532
533fn exited(exit: AutomationExit) -> (RunEnd, anyhow::Result<()>) {
535 (exit.end.clone(), Err(exit.into()))
536}
537
538fn print_provider_diagnostic(error: &anyhow::Error) {
545 let diagnostic = error.chain().find_map(|cause| match cause.downcast_ref() {
546 Some(rho_sdk::Error::Provider(provider)) => provider.diagnostic(),
547 _ => None,
548 });
549 if let Some(diagnostic) = diagnostic {
550 eprintln!("provider diagnostic: {diagnostic}");
551 }
552}
553
554pub(super) fn prompt_from_stdin(parts: Vec<String>, read_stdin: bool) -> anyhow::Result<String> {
555 if !read_stdin && crate::stdio::stdin_is_redirected() {
556 anyhow::bail!(
557 "stdin is redirected but --stdin was not set; pass --stdin to include piped input"
558 );
559 }
560 prompt_from_reader(parts, read_stdin, &mut io::stdin())
561}
562
563fn prompt_from_reader(
564 parts: Vec<String>,
565 read_stdin: bool,
566 stdin: &mut impl Read,
567) -> anyhow::Result<String> {
568 let mut chunks = Vec::new();
569 let inline = parts.join(" ").trim().to_string();
570 if !inline.is_empty() {
571 chunks.push(inline);
572 }
573 if read_stdin {
574 let mut buffer = String::new();
575 stdin.read_to_string(&mut buffer)?;
576 let buffer = buffer.trim().to_string();
577 if !buffer.is_empty() {
578 chunks.push(buffer);
579 }
580 }
581
582 let prompt = chunks.join("\n\n");
583 if prompt.is_empty() {
584 anyhow::bail!("rho run requires a prompt argument or --stdin");
585 }
586 Ok(prompt)
587}
588
589#[cfg(test)]
590#[path = "automation_tests.rs"]
591mod tests;