Skip to main content

rho_coding_agent/app/
automation.rs

1use std::{
2    fmt,
3    io::{self, Read, Write},
4    num::NonZeroUsize,
5    path::PathBuf,
6    sync::Arc,
7    time::Duration,
8};
9
10use rho_sdk::{SessionOptions, UserInput};
11
12use {
13    crate::cli::{Command, OutputFormat},
14    crate::config::Config,
15    crate::credential_store::AppCredentialStore,
16    crate::diagnostics::RuntimeDiagnostics,
17    crate::herdr::{HerdrReporter, HerdrState},
18    crate::subagent::{RunState, RunStatus},
19    crate::tools::agent::BackgroundSubagents,
20    rho_providers::providers::build_automation_provider,
21};
22
23use super::{
24    agent_binding::BoundAgent,
25    automation_protocol::{write_event, JsonlAdapter, TerminalReason, WireEvent},
26    headless_run::{self, HeadlessRunDeps, HostInputResponder},
27    policy::AppPolicy,
28    runtime_builder::{
29        build_runtime_with_max_steps, configured_context_window, RuntimeBuildOptions,
30    },
31    sdk_config::SdkBootstrapOptions,
32    tools_prompt::{assemble_tools_and_prompt, ToolsAndPromptOptions},
33};
34
35/// Error returned after an automation run has cleaned up and selected a stable exit code.
36#[derive(Debug)]
37pub struct AutomationExit {
38    code: u8,
39    reason: TerminalReason,
40    message: String,
41}
42
43impl AutomationExit {
44    pub(super) fn new(code: u8, reason: TerminalReason, message: impl Into<String>) -> Self {
45        Self {
46            code,
47            reason,
48            message: message.into(),
49        }
50    }
51
52    /// Returns the documented process exit code for this automation result.
53    pub fn exit_code(&self) -> u8 {
54        self.code
55    }
56
57    fn reason(&self) -> TerminalReason {
58        self.reason
59    }
60}
61
62impl fmt::Display for AutomationExit {
63    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
64        formatter.write_str(&self.message)
65    }
66}
67
68impl std::error::Error for AutomationExit {}
69
70/// Error returned after an automation run handles an interrupt and completes cleanup.
71#[derive(Debug)]
72pub struct AutomationInterrupted {
73    signal: ShutdownSignal,
74}
75
76impl AutomationInterrupted {
77    fn new(signal: ShutdownSignal) -> Self {
78        Self { signal }
79    }
80
81    /// Returns the conventional process exit code for the received signal.
82    pub fn exit_code(&self) -> u8 {
83        self.signal.exit_code()
84    }
85}
86
87impl fmt::Display for AutomationInterrupted {
88    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
89        write!(formatter, "rho run interrupted by {}", self.signal)
90    }
91}
92
93impl std::error::Error for AutomationInterrupted {}
94
95#[derive(Clone, Copy, Debug)]
96enum ShutdownSignal {
97    Interrupt,
98    Terminate,
99}
100
101impl ShutdownSignal {
102    fn exit_code(self) -> u8 {
103        match self {
104            Self::Interrupt => 130,
105            Self::Terminate => 143,
106        }
107    }
108}
109
110impl fmt::Display for ShutdownSignal {
111    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
112        match self {
113            Self::Interrupt => formatter.write_str("SIGINT"),
114            Self::Terminate => formatter.write_str("SIGTERM"),
115        }
116    }
117}
118
119#[derive(Debug)]
120struct SubagentCancelled;
121
122impl fmt::Display for SubagentCancelled {
123    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
124        formatter.write_str("subagent cancellation requested")
125    }
126}
127
128impl std::error::Error for SubagentCancelled {}
129
130pub(super) struct Startup<'a> {
131    pub config: &'a Config,
132    pub config_path: PathBuf,
133    pub cwd: PathBuf,
134    pub no_system_prompt: bool,
135    pub no_tools: bool,
136    pub no_subagents: bool,
137    pub usage_purpose: &'static str,
138    pub parent_session_id: Option<rho_sdk::SessionId>,
139    pub agent: BoundAgent,
140    pub output_file: Option<PathBuf>,
141    pub output: OutputFormat,
142    pub max_steps: Option<NonZeroUsize>,
143    pub timeout: Option<Duration>,
144    pub diagnostics: RuntimeDiagnostics,
145    pub herdr: HerdrReporter,
146    pub host_input: Option<Arc<dyn HostInputResponder>>,
147}
148
149pub(super) fn prompt_for_command(command: &Option<Command>) -> anyhow::Result<Option<String>> {
150    match command {
151        Some(Command::Run { prompt, stdin, .. }) => {
152            prompt_from_stdin(prompt.clone(), *stdin).map(Some)
153        }
154        Some(
155            Command::Attach { .. }
156            | Command::Login { .. }
157            | Command::CredentialStore { .. }
158            | Command::Sessions { .. }
159            | Command::Update,
160        )
161        | None => Ok(None),
162    }
163}
164
165pub(super) fn emit_startup_failure() -> anyhow::Result<()> {
166    let mut adapter = JsonlAdapter::new();
167    let event = adapter.failed(
168        TerminalReason::ConfigurationError,
169        "configuration failed".into(),
170        None,
171    );
172    emit(event)
173}
174
175pub(super) async fn run(prompt_text: String, startup: Startup<'_>) -> anyhow::Result<()> {
176    let mut jsonl = (startup.output == OutputFormat::Jsonl).then(JsonlAdapter::new);
177    let deadline = startup
178        .timeout
179        .map(|timeout| tokio::time::Instant::now() + timeout);
180    // The reporter exists before anything that can fail, so a parent process
181    // watching the output file always sees a terminal state, including startup failures.
182    let reporter_result = startup
183        .output_file
184        .as_ref()
185        .map(|path| {
186            RunReporter::new(
187                path.clone(),
188                RunArtifactIdentity {
189                    agent_id: startup.agent.id().to_string(),
190                    agent_fingerprint: startup.agent.fingerprint().to_string(),
191                    provider: startup.config.provider.clone(),
192                    model: startup.config.model.clone(),
193                },
194                startup.cwd.clone(),
195                &prompt_text,
196                /* stream_output */ startup.output == OutputFormat::Text,
197                None,
198            )
199        })
200        .transpose();
201    let mut reporter = match reporter_result {
202        Ok(reporter) => reporter,
203        Err(error) => {
204            emit_failure(&mut jsonl, TerminalReason::OutputError, &error)?;
205            return Err(
206                AutomationExit::new(1, TerminalReason::OutputError, error.to_string()).into(),
207            );
208        }
209    };
210
211    let cancellation = rho_tools::cancellation::RunCancellation::default();
212    let (result, timed_out) = if let Some(deadline) = deadline {
213        let future = run_session_with_output(
214            prompt_text,
215            &startup,
216            reporter.as_mut(),
217            Some(cancellation.clone()),
218            jsonl.as_mut(),
219        );
220        tokio::pin!(future);
221        tokio::select! {
222            result = &mut future => (result, false),
223            () = tokio::time::sleep_until(deadline) => {
224                cancellation.cancel();
225                (future.await, true)
226            }
227        }
228    } else {
229        (
230            run_session_with_output(
231                prompt_text,
232                &startup,
233                reporter.as_mut(),
234                None,
235                jsonl.as_mut(),
236            )
237            .await,
238            false,
239        )
240    };
241    if let Some(reporter) = reporter.as_mut() {
242        let reached_step_limit = result.as_ref().is_ok_and(|outcome| {
243            outcome.stop_reason() == rho_sdk::StopReason::MaxSteps
244                && (jsonl.is_some() || startup.max_steps.is_some())
245        });
246        if reached_step_limit {
247            let stopped = Err(AutomationExit::new(
248                124,
249                TerminalReason::MaxSteps,
250                "rho run reached its model-step limit",
251            )
252            .into());
253            reporter.finish(&stopped);
254        } else {
255            reporter.finish(&result);
256        }
257    }
258
259    if timed_out {
260        emit_stopped(&mut jsonl, TerminalReason::Timeout)?;
261        return Err(AutomationExit::new(124, TerminalReason::Timeout, "rho run timed out").into());
262    }
263
264    match result {
265        Ok(answer) => {
266            let max_steps = answer.stop_reason() == rho_sdk::StopReason::MaxSteps;
267            if max_steps && (jsonl.is_some() || startup.max_steps.is_some()) {
268                if let Some(adapter) = jsonl.as_mut() {
269                    let text = (!answer.text().is_empty()).then(|| answer.text().into());
270                    let event = adapter.stopped(TerminalReason::MaxSteps, text);
271                    emit(event)?;
272                } else {
273                    write_text_answer(&answer, reporter.is_some())?;
274                }
275                return Err(AutomationExit::new(
276                    124,
277                    TerminalReason::MaxSteps,
278                    "rho run reached its model-step limit",
279                )
280                .into());
281            }
282            if let Some(adapter) = jsonl.as_mut() {
283                let event = adapter.completed(answer.text().into());
284                emit(event)?;
285            } else {
286                write_text_answer(&answer, reporter.is_some())?;
287            }
288            Ok(())
289        }
290        Err(error) => {
291            let (reason, code) = classify_error(&error);
292            if reason == TerminalReason::Interrupted {
293                emit_stopped(&mut jsonl, reason)?;
294            } else if reason != TerminalReason::OutputError {
295                emit_failure(&mut jsonl, reason, &error)?;
296            }
297            let message = terminal_error_message(reason, &error);
298            if error.is::<AutomationInterrupted>() {
299                return Err(error);
300            }
301            Err(AutomationExit::new(code, reason, message).into())
302        }
303    }
304}
305
306fn write_text_answer(answer: &rho_sdk::RunOutcome, has_reporter: bool) -> anyhow::Result<()> {
307    let result = (|| -> io::Result<()> {
308        let mut stdout = io::stdout().lock();
309        if has_reporter {
310            writeln!(stdout, "\n[subagent run complete]")?;
311        } else {
312            writeln!(stdout, "{}", answer.text())?;
313        }
314        stdout.flush()
315    })();
316    result.map_err(|error| {
317        AutomationExit::new(
318            1,
319            TerminalReason::OutputError,
320            format!("could not write output: {error}"),
321        )
322        .into()
323    })
324}
325
326pub(super) fn emit(event: WireEvent) -> anyhow::Result<()> {
327    let mut stdout = io::stdout().lock();
328    write_event(&mut stdout, &event).map_err(|error| {
329        AutomationExit::new(
330            1,
331            TerminalReason::OutputError,
332            format!("could not write JSONL output: {error}"),
333        )
334        .into()
335    })
336}
337
338fn emit_stopped(adapter: &mut Option<JsonlAdapter>, reason: TerminalReason) -> anyhow::Result<()> {
339    if let Some(adapter) = adapter.as_mut() {
340        let text = adapter.partial_text();
341        let event = adapter.stopped(reason, text);
342        emit(event)?;
343    }
344    Ok(())
345}
346
347fn emit_failure(
348    adapter: &mut Option<JsonlAdapter>,
349    reason: TerminalReason,
350    error: &anyhow::Error,
351) -> anyhow::Result<()> {
352    if let Some(adapter) = adapter.as_mut() {
353        let text = adapter.partial_text();
354        let message = terminal_error_message(reason, error);
355        let event = adapter.failed(reason, message, text);
356        emit(event)?;
357    }
358    Ok(())
359}
360
361fn terminal_error_message(reason: TerminalReason, error: &anyhow::Error) -> String {
362    match reason {
363        TerminalReason::Authentication => "authentication failed".to_string(),
364        TerminalReason::ConfigurationError => "configuration failed".to_string(),
365        TerminalReason::OutputError => "output failed".to_string(),
366        TerminalReason::OtherError => "run failed".to_string(),
367        _ => error.to_string(),
368    }
369}
370
371fn classify_error(error: &anyhow::Error) -> (TerminalReason, u8) {
372    if let Some(interrupted) = error.downcast_ref::<AutomationInterrupted>() {
373        return (TerminalReason::Interrupted, interrupted.exit_code());
374    }
375    if let Some(exit) = error.downcast_ref::<AutomationExit>() {
376        return (exit.reason(), exit.exit_code());
377    }
378    for cause in error.chain() {
379        if let Some(error) = cause.downcast_ref::<rho_sdk::Error>() {
380            return match error {
381                rho_sdk::Error::Authentication { .. } => (TerminalReason::Authentication, 1),
382                rho_sdk::Error::Provider(provider)
383                    if provider.kind() == rho_sdk::ProviderErrorKind::Authentication =>
384                {
385                    (TerminalReason::Authentication, 1)
386                }
387                rho_sdk::Error::Provider(_) => (TerminalReason::ProviderError, 1),
388                rho_sdk::Error::Tool(_) => (TerminalReason::ToolHostError, 1),
389                rho_sdk::Error::InvalidConfiguration { .. } => {
390                    (TerminalReason::ConfigurationError, 2)
391                }
392                _ => (TerminalReason::OtherError, 1),
393            };
394        }
395        if let Some(error) = cause.downcast_ref::<rho_providers::model::ModelError>() {
396            use rho_providers::model::ModelError;
397            return match error {
398                ModelError::MissingApiKey
399                | ModelError::MissingCodexAuth
400                | ModelError::MissingAnthropicApiKey
401                | ModelError::MissingGoogleApiKey
402                | ModelError::MissingGithubCopilotAuth
403                | ModelError::MissingMoonshotApiKey
404                | ModelError::MissingPoolsideApiKey
405                | ModelError::MissingOpenRouterApiKey
406                | ModelError::MissingCredentialProfile(_)
407                | ModelError::MissingKimiAuth
408                | ModelError::MissingXaiApiKey
409                | ModelError::MissingXaiAuth
410                | ModelError::Credentials(_) => (TerminalReason::Authentication, 1),
411                ModelError::UnsupportedReasoning { .. } | ModelError::UnsupportedProvider(_) => {
412                    (TerminalReason::ConfigurationError, 2)
413                }
414                _ => (TerminalReason::ProviderError, 1),
415            };
416        }
417    }
418    (TerminalReason::OtherError, 1)
419}
420
421pub(crate) async fn run_session(
422    prompt_text: String,
423    startup: &Startup<'_>,
424    reporter: Option<&mut RunReporter>,
425    cancellation: Option<rho_tools::cancellation::RunCancellation>,
426) -> anyhow::Result<rho_sdk::RunOutcome> {
427    run_session_with_output(prompt_text, startup, reporter, cancellation, None).await
428}
429
430async fn run_session_with_output(
431    prompt_text: String,
432    startup: &Startup<'_>,
433    reporter: Option<&mut RunReporter>,
434    cancellation: Option<rho_tools::cancellation::RunCancellation>,
435    mut jsonl: Option<&mut JsonlAdapter>,
436) -> anyhow::Result<rho_sdk::RunOutcome> {
437    let sdk_options = SdkBootstrapOptions::from_config(startup.config, &startup.cwd)?;
438    let credentials = rho_providers::auth::provider_credentials::ApplicationCredentialSource::new(
439        Arc::new(AppCredentialStore),
440    );
441    let provider = build_automation_provider(sdk_options.provider, &credentials)?;
442    let (tool_set, system_prompt) = assemble_tools_and_prompt(ToolsAndPromptOptions {
443        config: startup.config,
444        config_path: startup.config_path.clone(),
445        cwd: &startup.cwd,
446        no_system_prompt: startup.no_system_prompt,
447        no_tools: startup.no_tools,
448        no_subagents: startup.no_subagents,
449        // Automation keeps questionnaire capability when the agent exposes it.
450        questionnaire_enabled: true,
451        background_subagents: BackgroundSubagents::Disabled,
452        diagnostics: &startup.diagnostics,
453        agent: &startup.agent,
454    })?;
455
456    let workspace_root = sdk_options.workspace.root.clone();
457    let workspace = sdk_options.workspace.build_workspace()?;
458    let context_window = configured_context_window(startup.config);
459    let compaction = sdk_options.runtime.compaction.clone();
460    startup.diagnostics.update_compaction_config(&compaction);
461    let usage_recording = crate::usage::default_recording().await;
462    let runtime = build_runtime_with_max_steps(
463        RuntimeBuildOptions {
464            provider,
465            tools: tool_set.tools(),
466            workspace,
467            workspace_policy: AppPolicy::for_mode(startup.config.permission_mode),
468            approval_handler: None,
469            system_prompt,
470            reasoning: sdk_options.runtime.reasoning,
471            compaction,
472            context_window,
473            usage_purpose: startup.usage_purpose,
474            usage_parent_session_id: startup.parent_session_id.clone(),
475            usage_recording,
476        },
477        startup.max_steps,
478    )?;
479    let session = runtime.session(SessionOptions::default()).await?;
480    if let Some(adapter) = jsonl.as_deref_mut() {
481        adapter.set_run_context(session.id(), &workspace_root);
482    }
483    startup
484        .herdr
485        .report_state(HerdrState::Working, None, None)
486        .await;
487    let result = complete_run(
488        &session,
489        prompt_text,
490        HeadlessRunDeps {
491            reporter,
492            external_cancellation: cancellation,
493            jsonl,
494            host_input: startup.host_input.as_deref(),
495        },
496    )
497    .await;
498
499    runtime.shutdown();
500    tool_set.shutdown().await;
501    startup
502        .herdr
503        .report_state(HerdrState::Idle, None, None)
504        .await;
505    startup.herdr.release().await;
506
507    result
508}
509
510async fn complete_run(
511    session: &rho_sdk::Session,
512    prompt_text: String,
513    dependencies: HeadlessRunDeps<'_>,
514) -> anyhow::Result<rho_sdk::RunOutcome> {
515    let HeadlessRunDeps {
516        reporter,
517        external_cancellation,
518        jsonl,
519        host_input,
520    } = dependencies;
521    let mut run = session.start(UserInput::text(prompt_text)).await?;
522    let cancellation = run.cancellation_handle();
523    let external_cancellation = external_cancellation.unwrap_or_default();
524    tokio::select! {
525        outcome = headless_run::drive(&mut run, reporter, jsonl, host_input) => outcome,
526        signal = shutdown_signal() => {
527            let signal = signal?;
528            cancellation.cancel();
529            let _ = run.outcome().await;
530            Err(AutomationInterrupted::new(signal).into())
531        }
532        () = external_cancellation.cancelled() => {
533            cancellation.cancel();
534            let _ = run.outcome().await;
535            Err(SubagentCancelled.into())
536        }
537    }
538}
539
540pub(crate) use crate::run_artifacts::RunArtifactIdentity;
541
542/// Maintains the `--output-file` status contract for subagent runs and
543/// streams progress to stdout so a watching pane shows live activity.
544pub(crate) struct RunReporter {
545    sink: crate::run_artifacts::RunArtifactSink,
546    adapter: crate::tui::event_adapter::SdkEventAdapter,
547    stream_output: bool,
548}
549
550impl RunReporter {
551    pub(crate) fn new(
552        path: PathBuf,
553        identity: RunArtifactIdentity,
554        cwd: PathBuf,
555        prompt: &str,
556        stream_output: bool,
557        status_tx: Option<tokio::sync::watch::Sender<RunStatus>>,
558    ) -> anyhow::Result<Self> {
559        let sink = crate::run_artifacts::RunArtifactSink::open(path, &identity, prompt, status_tx)?;
560        Ok(Self {
561            sink,
562            adapter: crate::tui::event_adapter::SdkEventAdapter::new(cwd),
563            stream_output,
564        })
565    }
566
567    /// Resume after the executor already wrote the Starting boundary.
568    pub(crate) fn continue_from(
569        path: PathBuf,
570        started_status: RunStatus,
571        cwd: PathBuf,
572        prompt: &str,
573        stream_output: bool,
574        status_tx: Option<tokio::sync::watch::Sender<RunStatus>>,
575    ) -> anyhow::Result<Self> {
576        let sink = crate::run_artifacts::RunArtifactSink::continue_from(
577            path,
578            started_status,
579            prompt,
580            status_tx,
581        )?;
582        Ok(Self {
583            sink,
584            adapter: crate::tui::event_adapter::SdkEventAdapter::new(cwd),
585            stream_output,
586        })
587    }
588
589    pub(super) fn on_event(&mut self, event: &rho_sdk::RunEvent) {
590        use rho_sdk::RunEvent;
591
592        let attachments = crate::tui::translate_run_event(&mut self.adapter, event);
593        if !attachments.is_empty() {
594            let mut saw_text_delta = false;
595            let mut needs_immediate_publish = false;
596            for attachment in attachments {
597                match &attachment {
598                    crate::run_artifacts::AttachmentEvent::AssistantTextDelta(text)
599                        if !text.is_empty() =>
600                    {
601                        self.sink.append_last_text(text);
602                        saw_text_delta = true;
603                        self.sink.write_attachment(attachment);
604                    }
605                    _ => {
606                        needs_immediate_publish = true;
607                        self.sink.write_attachment(attachment);
608                    }
609                }
610            }
611            if needs_immediate_publish {
612                self.sink.publish();
613            } else if saw_text_delta {
614                self.sink.publish_throttled();
615            }
616        }
617        match event {
618            RunEvent::StepStarted { step } => {
619                self.sink.status.state = RunState::Running;
620                self.sink.status.turns = *step as u64;
621                self.sink.publish();
622            }
623            RunEvent::ToolStarted { name, .. } => {
624                self.sink.status.last_activity = Some(format!("tool: {name}"));
625                self.stream(&format!("\n[tool] {name}\n"));
626                self.sink.publish();
627            }
628            RunEvent::HostInputRequested { request }
629            | RunEvent::ToolHostInputRequested { request, .. } => {
630                self.sink.status.last_activity =
631                    Some(format!("waiting for questionnaire: {}", request.title()));
632                self.sink.publish();
633            }
634            RunEvent::AssistantTextDelta { text } => {
635                self.sink.status.last_activity = Some("assistant text".into());
636                self.stream(text);
637                // Attachment path already published throttled when translated.
638            }
639            RunEvent::ProviderStreamReset { .. } => {
640                self.sink.status.last_activity = Some("retrying provider response".into());
641                self.sink.status.last_text = None;
642                self.stream("\n[provider response discarded; retrying]\n");
643                self.sink.publish();
644            }
645            RunEvent::UsageUpdated { usage } => {
646                self.sink.status.input_tokens = usage.total_input_tokens();
647                self.sink.status.output_tokens = usage.output_tokens;
648            }
649            _ => {}
650        }
651    }
652
653    #[cfg(test)]
654    pub(crate) fn status(&self) -> &RunStatus {
655        &self.sink.status
656    }
657
658    pub(super) fn write(&mut self) {
659        self.sink.publish();
660    }
661
662    pub(crate) fn finish(&mut self, result: &anyhow::Result<rho_sdk::RunOutcome>) {
663        match result {
664            Ok(outcome) => {
665                let usage = outcome.usage();
666                self.sink.status.input_tokens = usage.total_input_tokens();
667                self.sink.status.output_tokens = usage.output_tokens;
668                self.sink.finish_ok(Some(outcome.text().to_string()));
669            }
670            Err(error)
671                if error.is::<AutomationInterrupted>()
672                    || error.downcast_ref::<AutomationExit>().is_some_and(|exit| {
673                        matches!(
674                            exit.reason(),
675                            TerminalReason::MaxSteps | TerminalReason::Timeout
676                        )
677                    })
678                    || error.is::<SubagentCancelled>() =>
679            {
680                self.sink.finish_stopped("stopped");
681            }
682            Err(error) => {
683                self.sink.finish_error(format!("{error:#}"));
684            }
685        }
686    }
687
688    fn stream(&self, text: &str) {
689        if !self.stream_output {
690            return;
691        }
692        let mut stdout = io::stdout().lock();
693        let _ = stdout.write_all(text.as_bytes());
694        let _ = stdout.flush();
695    }
696}
697
698#[cfg(unix)]
699async fn shutdown_signal() -> io::Result<ShutdownSignal> {
700    use tokio::signal::unix::{signal, SignalKind};
701
702    let mut interrupt = signal(SignalKind::interrupt())?;
703    let mut terminate = signal(SignalKind::terminate())?;
704    tokio::select! {
705        _ = interrupt.recv() => Ok(ShutdownSignal::Interrupt),
706        _ = terminate.recv() => Ok(ShutdownSignal::Terminate),
707    }
708}
709
710#[cfg(not(unix))]
711async fn shutdown_signal() -> io::Result<ShutdownSignal> {
712    tokio::signal::ctrl_c().await?;
713    Ok(ShutdownSignal::Interrupt)
714}
715
716fn prompt_from_stdin(parts: Vec<String>, read_stdin: bool) -> anyhow::Result<String> {
717    prompt_from_reader(parts, read_stdin, &mut io::stdin())
718}
719
720fn prompt_from_reader(
721    parts: Vec<String>,
722    read_stdin: bool,
723    stdin: &mut impl Read,
724) -> anyhow::Result<String> {
725    let mut chunks = Vec::new();
726    let inline = parts.join(" ").trim().to_string();
727    if !inline.is_empty() {
728        chunks.push(inline);
729    }
730    if read_stdin {
731        let mut buffer = String::new();
732        stdin.read_to_string(&mut buffer)?;
733        let buffer = buffer.trim().to_string();
734        if !buffer.is_empty() {
735            chunks.push(buffer);
736        }
737    }
738
739    let prompt = chunks.join("\n\n");
740    if prompt.is_empty() {
741        anyhow::bail!("rho run requires a prompt argument or --stdin");
742    }
743    Ok(prompt)
744}
745
746#[cfg(test)]
747#[path = "automation_tests.rs"]
748mod tests;