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