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::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
177/// Writes the JSONL stream of a run that failed to start with `exit`: only
178/// its `run_ended`. Returns the exit, unless the stream could not be
179/// written, which is an output error.
180pub(super) fn emit_startup_failure(exit: AutomationExit) -> AutomationExit {
181    end_failed(&mut JsonlStream::stdout(), exit)
182}
183
184/// Ends `stream` as a run that failed with `exit` did, and returns the
185/// exit, unless the stream could not be written, which is an output error.
186fn end_failed(stream: &mut JsonlStream, exit: AutomationExit) -> AutomationExit {
187    end_stream(stream, Err(exit)).expect_err("a failed run ends failed")
188}
189
190/// Ends `stream` as a run that ended with `exit` did, and returns the exit,
191/// unless the stream could not be written, which is an output error.
192pub(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
205/// The output error of a stream that could not be written, if it could not.
206pub(super) fn stream_written(stream: &JsonlStream) -> Result<(), AutomationExit> {
207    stream
208        .failure()
209        .map_or(Ok(()), |failure| Err(output_error(failure)))
210}
211
212/// The exit of a run whose output failed with `failure`.
213pub(super) fn output_error(failure: &str) -> AutomationExit {
214    AutomationExit::new(1, TerminalReason::OutputError, failure)
215}
216
217/// The exit of a run whose output could not be written.
218pub(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    // Before any run state is published, so a signal during startup is held
228    // for the run to handle instead of killing the process mid-setup.
229    let mut stops = Stops::on_signals(ShutdownSignals::install()?).or_at(deadline);
230    // The reporter exists before anything that can fail, so a parent process
231    // watching the output file always sees a terminal state, including startup failures.
232    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                /* stream_output */ 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
278/// Runs the prompt on a new session saved as `rho run`'s, unless
279/// `--no-save` made it ephemeral, until it ends or `stops` stops it, and
280/// tears the session down. Returns how the prompt ended, which ends the
281/// JSONL stream's turn. Person-facing
282/// listings leave the session out, so it opens by id. It is never titled: a
283/// model call per scripted run is not worth it.
284async 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            /*started_by*/ 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    // A JSONL write that failed already failed the turn; the stream is gone.
346    let end = match view.output_failure() {
347        Some(message) => PromptEnd::Failed(output_error(&message).into()),
348        None => end,
349    };
350    // The bound agent may pin its own provider and auth; that is what runs.
351    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
357/// Runs `text` within `prompt`: its slash command when it starts with one
358/// `rho run` runs, else a model turn on it. A command `rho run` cannot run
359/// fails the prompt as a configuration error.
360async 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        // Expansion can wait on an MCP server, so a stop drops it.
372        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                origin: None,
391            };
392            runtime
393                .run_prompt_turn(view, prompt, turn, process_config)
394                .await
395        }
396        PromptCommand::RunAsAgent(task) => {
397            runtime
398                .rebind_agent(prompt, &task, process_config)
399                .await
400                .map_err(|error| match error.downcast::<CommandRejected>() {
401                    Ok(CommandRejected(message)) => rejected(message),
402                    Err(error) => error,
403                })?;
404            // The rebound agent has tools of its own.
405            view.bind(runtime, process_config);
406            // The command stays the shown message; the model gets the task.
407            let turn = Turn {
408                display: input,
409                model: task.input,
410                calls: Vec::new(),
411                origin: None,
412            };
413            runtime
414                .run_prompt_turn(view, prompt, turn, process_config)
415                .await
416        }
417        // `RUN_COMMANDS` runs neither `/compact` nor workflows, so the
418        // resolver rejects them first.
419        PromptCommand::Compact { .. } | PromptCommand::StartWorkflow(_) => Err(rejected(
420            "could not run the command: not available in rho run".into(),
421        )),
422    }
423}
424
425fn write_text_answer(answer: &rho_sdk::RunOutcome, has_reporter: bool) -> anyhow::Result<()> {
426    let result = (|| -> io::Result<()> {
427        let mut stdout = io::stdout().lock();
428        if has_reporter {
429            writeln!(stdout, "\n[subagent run complete]")?;
430        } else {
431            writeln!(stdout, "{}", answer.text())?;
432        }
433        stdout.flush()
434    })();
435    result.map_err(|error| write_failed(error).into())
436}
437
438const TIMEOUT_MESSAGE: &str = "rho run timed out";
439
440/// How the run's prompt ended, decided once for the JSONL stream, the
441/// status file, and the exit.
442enum RunTerminal {
443    /// The run finished: `outcome` is answered, or at its step limit.
444    Finished {
445        answer: rho_sdk::RunOutcome,
446        outcome: WireOutcome,
447    },
448    Timeout,
449    Interrupted(ShutdownSignal),
450    /// The run failed with `error`, which clients are told as `turn`.
451    Failed {
452        error: anyhow::Error,
453        turn: TurnError,
454    },
455}
456
457impl RunTerminal {
458    /// The terminal of a prompt that ended as `end`, in a session whose
459    /// model is `selection`'s.
460    fn of(end: PromptEnd, selection: &Config) -> Self {
461        match end {
462            PromptEnd::Finished(answer) => Self::Finished {
463                outcome: outcome::finished(&answer),
464                answer,
465            },
466            PromptEnd::Stopped(StopCause::Timeout) => Self::Timeout,
467            PromptEnd::Stopped(StopCause::Interrupted(signal)) => Self::Interrupted(signal),
468            PromptEnd::Stopped(StopCause::Cancelled) => {
469                unreachable!("rho run's stops have no parent cancel")
470            }
471            PromptEnd::Failed(error) => Self::Failed {
472                turn: terminal::turn_error(&error, selection),
473                error,
474            },
475        }
476    }
477
478    /// How the turn ended, as the JSONL stream's `turn_ended` says: a
479    /// timeout or signal cancelled it.
480    fn turn_outcome(&self) -> WireOutcome {
481        match self {
482            Self::Finished { outcome, .. } => outcome.clone(),
483            Self::Timeout | Self::Interrupted(_) => WireOutcome::Cancelled,
484            Self::Failed { turn, .. } => WireOutcome::Failed {
485                error: turn.clone(),
486            },
487        }
488    }
489}
490
491/// Ends the run: writes its answer as text unless it streams JSONL, ends
492/// the stream with `run_ended`, and returns the exit.
493fn emit_and_exit_terminal(
494    terminal: RunTerminal,
495    jsonl: Option<&mut JsonlStream>,
496    has_reporter: bool,
497) -> anyhow::Result<()> {
498    let (end, exit) = match terminal {
499        RunTerminal::Finished { answer, outcome } => {
500            if jsonl.is_none() {
501                write_text_answer(&answer, has_reporter)?;
502            }
503            match terminal::outcome_exit(&outcome) {
504                Ok(()) => (RunEnd::completed(), Ok(())),
505                Err(exit) => exited(exit),
506            }
507        }
508        RunTerminal::Timeout => exited(AutomationExit::new(
509            124,
510            TerminalReason::Timeout,
511            TIMEOUT_MESSAGE,
512        )),
513        RunTerminal::Interrupted(signal) => {
514            let interrupted = AutomationInterrupted::new(signal);
515            let end = RunEnd {
516                reason: TerminalReason::Interrupted,
517                exit_code: interrupted.exit_code(),
518                message: Some(interrupted.to_string()),
519            };
520            (end, Err(interrupted.into()))
521        }
522        RunTerminal::Failed { error, turn } => {
523            let exit = terminal::failure(&error, turn);
524            if exit.end.reason == TerminalReason::ProviderError {
525                print_provider_diagnostic(&error);
526            }
527            exited(exit)
528        }
529    };
530    if let Some(stream) = jsonl {
531        stream.end(&end);
532        // A stream that could not be written ends the run as an output
533        // error, whatever the run's own end.
534        stream_written(stream)?;
535    }
536    exit
537}
538
539/// The `run_ended` record and the exit of a run that ends with `exit`.
540fn exited(exit: AutomationExit) -> (RunEnd, anyhow::Result<()>) {
541    (exit.end.clone(), Err(exit.into()))
542}
543
544/// Shows the provider's own failure details to the user running `rho run`.
545///
546/// The SDK reserves diagnostics for direct display, so they go to stderr only,
547/// never into JSONL or the exit message that automation consumes.
548/// Authentication failures never reach this, because their diagnostics may
549/// echo credentials.
550fn print_provider_diagnostic(error: &anyhow::Error) {
551    let diagnostic = error.chain().find_map(|cause| match cause.downcast_ref() {
552        Some(rho_sdk::Error::Provider(provider)) => provider.diagnostic(),
553        _ => None,
554    });
555    if let Some(diagnostic) = diagnostic {
556        eprintln!("provider diagnostic: {diagnostic}");
557    }
558}
559
560pub(super) fn prompt_from_stdin(parts: Vec<String>, read_stdin: bool) -> anyhow::Result<String> {
561    if !read_stdin && crate::stdio::stdin_is_redirected() {
562        anyhow::bail!(
563            "stdin is redirected but --stdin was not set; pass --stdin to include piped input"
564        );
565    }
566    prompt_from_reader(parts, read_stdin, &mut io::stdin())
567}
568
569fn prompt_from_reader(
570    parts: Vec<String>,
571    read_stdin: bool,
572    stdin: &mut impl Read,
573) -> anyhow::Result<String> {
574    let mut chunks = Vec::new();
575    let inline = parts.join(" ").trim().to_string();
576    if !inline.is_empty() {
577        chunks.push(inline);
578    }
579    if read_stdin {
580        let mut buffer = String::new();
581        stdin.read_to_string(&mut buffer)?;
582        let buffer = buffer.trim().to_string();
583        if !buffer.is_empty() {
584            chunks.push(buffer);
585        }
586    }
587
588    let prompt = chunks.join("\n\n");
589    if prompt.is_empty() {
590        anyhow::bail!("rho run requires a prompt argument or --stdin");
591    }
592    Ok(prompt)
593}
594
595#[cfg(test)]
596#[path = "automation_tests.rs"]
597mod tests;