Skip to main content

rho_coding_agent/app/
automation.rs

1//! `rho run`: one prompt on a saved session with no person watching, its
2//! answer written as text or its events as the versioned JSONL stream (see
3//! `automation_protocol.rs`), ending with a documented exit code.
4//!
5//! The session runs on the headless host (`headless_host.rs`); this module
6//! owns what is `rho run`'s own: reading the prompt, resolving its slash
7//! command, the terminal event, and the exit code.
8
9use 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/// Error returned after an automation run has cleaned up and selected a stable exit code.
45#[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    /// An invalid invocation or configuration: exit 2.
62    pub(super) fn configuration(message: impl Into<String>) -> Self {
63        Self::new(2, TerminalReason::ConfigurationError, message)
64    }
65
66    /// A failure signing in can fix, such as missing or refused
67    /// credentials: exit 1.
68    pub(super) fn authentication(message: impl Into<String>) -> Self {
69        Self::new(1, TerminalReason::Authentication, message)
70    }
71
72    /// Any other failure, such as not reaching the daemon: exit 1.
73    pub(super) fn other(message: impl Into<String>) -> Self {
74        Self::new(1, TerminalReason::OtherError, message)
75    }
76
77    /// Returns the documented process exit code for this automation result.
78    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/// Error returned after an automation run handles an interrupt and completes cleanup.
92#[derive(Debug)]
93pub struct AutomationInterrupted {
94    signal: ShutdownSignal,
95}
96
97impl AutomationInterrupted {
98    fn new(signal: ShutdownSignal) -> Self {
99        Self { signal }
100    }
101
102    /// Returns the conventional process exit code for the received signal.
103    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
116/// What `rho run` was launched with.
117pub(super) struct Startup<'a> {
118    pub config: &'a Config,
119    pub config_path: PathBuf,
120    pub cwd: PathBuf,
121    /// What `--no-*` flags leave out of the run's session.
122    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    /// Whether the run's session is saved; `--no-save` makes it ephemeral.
129    pub persistence: SessionPersistence,
130    pub diagnostics: RuntimeDiagnostics,
131    pub herdr: HerdrReporter,
132    /// Directories added to the workspace scope beyond `cwd`.
133    pub added_dirs: crate::added_dirs::AddedDirs,
134}
135
136/// The commands `rho run` runs. `/compact` is not among them: a run's
137/// session is new, so there is nothing to compact. A workflow would outlive
138/// the process, which exits with its prompt.
139const 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
174/// Writes the JSONL stream of a run that failed to start with `exit`: only
175/// its `run_ended`. Returns the exit, unless the stream could not be
176/// written, which is an output error.
177pub(super) fn emit_startup_failure(exit: AutomationExit) -> AutomationExit {
178    end_failed(&mut JsonlStream::stdout(), exit)
179}
180
181/// Ends `stream` as a run that failed with `exit` did, and returns the
182/// exit, unless the stream could not be written, which is an output error.
183fn end_failed(stream: &mut JsonlStream, exit: AutomationExit) -> AutomationExit {
184    end_stream(stream, Err(exit)).expect_err("a failed run ends failed")
185}
186
187/// Ends `stream` as a run that ended with `exit` did, and returns the exit,
188/// unless the stream could not be written, which is an output error.
189pub(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
202/// The output error of a stream that could not be written, if it could not.
203pub(super) fn stream_written(stream: &JsonlStream) -> Result<(), AutomationExit> {
204    stream
205        .failure()
206        .map_or(Ok(()), |failure| Err(output_error(failure)))
207}
208
209/// The exit of a run whose output failed with `failure`.
210pub(super) fn output_error(failure: &str) -> AutomationExit {
211    AutomationExit::new(1, TerminalReason::OutputError, failure)
212}
213
214/// The exit of a run whose output could not be written.
215pub(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    // Before any run state is published, so a signal during startup is held
225    // for the run to handle instead of killing the process mid-setup.
226    let mut stops = Stops::on_signals(ShutdownSignals::install()?).or_at(deadline);
227    // The reporter exists before anything that can fail, so a parent process
228    // watching the output file always sees a terminal state, including startup failures.
229    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                /* stream_output */ 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
275/// Runs the prompt on a new session saved as `rho run`'s, unless
276/// `--no-save` made it ephemeral, until it ends or `stops` stops it, and
277/// tears the session down. Returns how the prompt ended, which ends the
278/// JSONL stream's turn. Person-facing
279/// listings leave the session out, so it opens by id. It is never titled: a
280/// model call per scripted run is not worth it.
281async 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            host_prompt: None,
296        },
297        host: HostCapabilities::unattended(UnattendedApprovals::Alone),
298        run: RunShape {
299            role: SessionRole::Run,
300            max_steps: startup.max_steps,
301            hook_labels: Default::default(),
302        },
303    };
304    let opening = SessionOpening {
305        build,
306        process_config: startup.config,
307        host_mcp: Default::default(),
308        cwd: &startup.cwd,
309        added_dirs: startup.added_dirs.clone(),
310    };
311    let mut view = HeadlessView::new();
312    if let Some(reporter) = reporter {
313        view = view.reporting_to(reporter);
314    }
315    if let Some(stream) = jsonl {
316        view = view.streaming_jsonl(stream);
317    }
318    let herdr = &startup.herdr;
319    let open = async {
320        let runtime = SessionRuntime::open_new(
321            opening,
322            rho_sdk::SessionId::new(),
323            startup.persistence,
324            /*started_by*/ None,
325        )
326        .await?;
327        let _ = herdr.report_state(HerdrState::Working, None, None).await;
328        anyhow::Ok(runtime)
329    };
330    let end = headless_host::run_prompt(
331        stops,
332        &mut view,
333        startup.config,
334        open,
335        |runtime, view, scope, process_config| {
336            Box::pin(run_text(runtime, view, scope, prompt_text, process_config))
337        },
338    )
339    .await;
340    let _ = herdr.report_state(HerdrState::Idle, None, None).await;
341    let _ = herdr.release().await;
342    // A JSONL write that failed already failed the turn; the stream is gone.
343    let end = match view.output_failure() {
344        Some(message) => PromptEnd::Failed(output_error(&message).into()),
345        None => end,
346    };
347    // The bound agent may pin its own provider and auth; that is what runs.
348    let selection = startup.agent.rho_config().unwrap_or(startup.config);
349    let terminal = RunTerminal::of(end, selection);
350    view.end_turn(terminal.turn_outcome());
351    terminal
352}
353
354/// Runs `text` within `prompt`: its slash command when it starts with one
355/// `rho run` runs, else a model turn on it. A command `rho run` cannot run
356/// fails the prompt as a configuration error.
357async fn run_text(
358    runtime: &mut SessionRuntime,
359    view: &mut HeadlessView<'_>,
360    prompt: &PromptScope,
361    text: String,
362    process_config: &Config,
363) -> anyhow::Result<TurnOutcome> {
364    let input = UserInput::text(text);
365    let home = crate::paths::home_dir();
366    let command = {
367        let scope = CommandScope::of(runtime, home.as_deref(), process_config);
368        // Expansion can wait on an MCP server, so a stop drops it.
369        tokio::select! {
370            biased;
371            () = prompt.cancellation().cancelled() => return Ok(TurnOutcome::Cancelled),
372            command = session_commands::resolve(input.clone(), &scope, RUN_COMMANDS) => command,
373        }
374    };
375    let rejected =
376        |message: String| -> anyhow::Error { AutomationExit::configuration(message).into() };
377    view.prompt(&input);
378    match command.map_err(|rejected_command| rejected(rejected_command.to_string()))? {
379        PromptCommand::Turn {
380            input: model,
381            calls,
382        } => {
383            let turn = Turn {
384                display: input,
385                model,
386                calls,
387            };
388            runtime
389                .run_prompt_turn(view, prompt, turn, process_config)
390                .await
391        }
392        PromptCommand::RunAsAgent(task) => {
393            runtime
394                .rebind_agent(prompt, &task, process_config)
395                .await
396                .map_err(|error| match error.downcast::<CommandRejected>() {
397                    Ok(CommandRejected(message)) => rejected(message),
398                    Err(error) => error,
399                })?;
400            // The rebound agent has tools of its own.
401            view.bind(runtime, process_config);
402            // The command stays the shown message; the model gets the task.
403            let turn = Turn {
404                display: input,
405                model: task.input,
406                calls: Vec::new(),
407            };
408            runtime
409                .run_prompt_turn(view, prompt, turn, process_config)
410                .await
411        }
412        // `RUN_COMMANDS` runs neither `/compact` nor workflows, so the
413        // resolver rejects them first.
414        PromptCommand::Compact { .. } | PromptCommand::StartWorkflow(_) => Err(rejected(
415            "could not run the command: not available in rho run".into(),
416        )),
417    }
418}
419
420fn write_text_answer(answer: &rho_sdk::RunOutcome, has_reporter: bool) -> anyhow::Result<()> {
421    let result = (|| -> io::Result<()> {
422        let mut stdout = io::stdout().lock();
423        if has_reporter {
424            writeln!(stdout, "\n[subagent run complete]")?;
425        } else {
426            writeln!(stdout, "{}", answer.text())?;
427        }
428        stdout.flush()
429    })();
430    result.map_err(|error| write_failed(error).into())
431}
432
433const TIMEOUT_MESSAGE: &str = "rho run timed out";
434
435/// How the run's prompt ended, decided once for the JSONL stream, the
436/// status file, and the exit.
437enum RunTerminal {
438    /// The run finished: `outcome` is answered, or at its step limit.
439    Finished {
440        answer: rho_sdk::RunOutcome,
441        outcome: WireOutcome,
442    },
443    Timeout,
444    Interrupted(ShutdownSignal),
445    /// The run failed with `error`, which clients are told as `turn`.
446    Failed {
447        error: anyhow::Error,
448        turn: TurnError,
449    },
450}
451
452impl RunTerminal {
453    /// The terminal of a prompt that ended as `end`, in a session whose
454    /// model is `selection`'s.
455    fn of(end: PromptEnd, selection: &Config) -> Self {
456        match end {
457            PromptEnd::Finished(answer) => Self::Finished {
458                outcome: outcome::finished(&answer),
459                answer,
460            },
461            PromptEnd::Stopped(StopCause::Timeout) => Self::Timeout,
462            PromptEnd::Stopped(StopCause::Interrupted(signal)) => Self::Interrupted(signal),
463            PromptEnd::Stopped(StopCause::Cancelled) => {
464                unreachable!("rho run's stops have no parent cancel")
465            }
466            PromptEnd::Failed(error) => Self::Failed {
467                turn: terminal::turn_error(&error, selection),
468                error,
469            },
470        }
471    }
472
473    /// How the turn ended, as the JSONL stream's `turn_ended` says: a
474    /// timeout or signal cancelled it.
475    fn turn_outcome(&self) -> WireOutcome {
476        match self {
477            Self::Finished { outcome, .. } => outcome.clone(),
478            Self::Timeout | Self::Interrupted(_) => WireOutcome::Cancelled,
479            Self::Failed { turn, .. } => WireOutcome::Failed {
480                error: turn.clone(),
481            },
482        }
483    }
484}
485
486/// Ends the run: writes its answer as text unless it streams JSONL, ends
487/// the stream with `run_ended`, and returns the exit.
488fn emit_and_exit_terminal(
489    terminal: RunTerminal,
490    jsonl: Option<&mut JsonlStream>,
491    has_reporter: bool,
492) -> anyhow::Result<()> {
493    let (end, exit) = match terminal {
494        RunTerminal::Finished { answer, outcome } => {
495            if jsonl.is_none() {
496                write_text_answer(&answer, has_reporter)?;
497            }
498            match terminal::outcome_exit(&outcome) {
499                Ok(()) => (RunEnd::completed(), Ok(())),
500                Err(exit) => exited(exit),
501            }
502        }
503        RunTerminal::Timeout => exited(AutomationExit::new(
504            124,
505            TerminalReason::Timeout,
506            TIMEOUT_MESSAGE,
507        )),
508        RunTerminal::Interrupted(signal) => {
509            let interrupted = AutomationInterrupted::new(signal);
510            let end = RunEnd {
511                reason: TerminalReason::Interrupted,
512                exit_code: interrupted.exit_code(),
513                message: Some(interrupted.to_string()),
514            };
515            (end, Err(interrupted.into()))
516        }
517        RunTerminal::Failed { error, turn } => {
518            let exit = terminal::failure(&error, turn);
519            if exit.end.reason == TerminalReason::ProviderError {
520                print_provider_diagnostic(&error);
521            }
522            exited(exit)
523        }
524    };
525    if let Some(stream) = jsonl {
526        stream.end(&end);
527        // A stream that could not be written ends the run as an output
528        // error, whatever the run's own end.
529        stream_written(stream)?;
530    }
531    exit
532}
533
534/// The `run_ended` record and the exit of a run that ends with `exit`.
535fn exited(exit: AutomationExit) -> (RunEnd, anyhow::Result<()>) {
536    (exit.end.clone(), Err(exit.into()))
537}
538
539/// Shows the provider's own failure details to the user running `rho run`.
540///
541/// The SDK reserves diagnostics for direct display, so they go to stderr only,
542/// never into JSONL or the exit message that automation consumes.
543/// Authentication failures never reach this, because their diagnostics may
544/// echo credentials.
545fn print_provider_diagnostic(error: &anyhow::Error) {
546    let diagnostic = error.chain().find_map(|cause| match cause.downcast_ref() {
547        Some(rho_sdk::Error::Provider(provider)) => provider.diagnostic(),
548        _ => None,
549    });
550    if let Some(diagnostic) = diagnostic {
551        eprintln!("provider diagnostic: {diagnostic}");
552    }
553}
554
555pub(super) fn prompt_from_stdin(parts: Vec<String>, read_stdin: bool) -> anyhow::Result<String> {
556    if !read_stdin && crate::stdio::stdin_is_redirected() {
557        anyhow::bail!(
558            "stdin is redirected but --stdin was not set; pass --stdin to include piped input"
559        );
560    }
561    prompt_from_reader(parts, read_stdin, &mut io::stdin())
562}
563
564fn prompt_from_reader(
565    parts: Vec<String>,
566    read_stdin: bool,
567    stdin: &mut impl Read,
568) -> anyhow::Result<String> {
569    let mut chunks = Vec::new();
570    let inline = parts.join(" ").trim().to_string();
571    if !inline.is_empty() {
572        chunks.push(inline);
573    }
574    if read_stdin {
575        let mut buffer = String::new();
576        stdin.read_to_string(&mut buffer)?;
577        let buffer = buffer.trim().to_string();
578        if !buffer.is_empty() {
579            chunks.push(buffer);
580        }
581    }
582
583    let prompt = chunks.join("\n\n");
584    if prompt.is_empty() {
585        anyhow::bail!("rho run requires a prompt argument or --stdin");
586    }
587    Ok(prompt)
588}
589
590#[cfg(test)]
591#[path = "automation_tests.rs"]
592mod tests;