use std::time::Duration;
use rho_protocol::{TurnError, TurnErrorKind, TurnOutcome};
use super::{AutomationExit, TerminalReason};
use crate::{app::session_events::outcome, config::Config};
pub(super) fn turn_error(error: &anyhow::Error, model: &Config) -> TurnError {
let Some(exit) = error.downcast_ref::<AutomationExit>() else {
return outcome::turn_error(error, model);
};
let kind = match exit.end.reason {
TerminalReason::Authentication => TurnErrorKind::Authentication,
TerminalReason::ProviderError => TurnErrorKind::Provider,
TerminalReason::ToolHostError => TurnErrorKind::ToolHost,
TerminalReason::ConfigurationError => TurnErrorKind::Configuration,
TerminalReason::Completed
| TerminalReason::MaxSteps
| TerminalReason::Timeout
| TerminalReason::Interrupted
| TerminalReason::Cancelled
| TerminalReason::Detached
| TerminalReason::OutputError
| TerminalReason::OtherError => TurnErrorKind::Other,
};
TurnError {
kind,
message: exit.to_string(),
}
}
pub(super) fn failure(error: &anyhow::Error, turn: TurnError) -> AutomationExit {
if let Some(exit) = error.downcast_ref::<AutomationExit>() {
return exit.clone();
}
failed(turn)
}
pub(in crate::app) fn outcome_exit(outcome: &TurnOutcome) -> Result<(), AutomationExit> {
match outcome {
TurnOutcome::Answered { .. } => Ok(()),
TurnOutcome::MaxSteps { .. } => Err(AutomationExit::new(
124,
TerminalReason::MaxSteps,
"the turn reached its model-step limit",
)),
TurnOutcome::Cancelled => Err(AutomationExit::new(
1,
TerminalReason::Cancelled,
"the turn was cancelled",
)),
TurnOutcome::TimedOut { timeout_ms } => Err(AutomationExit::new(
124,
TerminalReason::Timeout,
format!(
"the turn timed out at its limit of {}",
humantime::format_duration(Duration::from_millis(*timeout_ms))
),
)),
TurnOutcome::Failed { error } => Err(failed(error.clone())),
_ => Err(AutomationExit::new(
1,
TerminalReason::OtherError,
"the turn ended in a way this rho does not know",
)),
}
}
fn failed(turn: TurnError) -> AutomationExit {
let TurnError { kind, message } = turn;
match kind {
TurnErrorKind::Authentication => AutomationExit::authentication(message),
TurnErrorKind::Provider => AutomationExit::new(1, TerminalReason::ProviderError, message),
TurnErrorKind::ToolHost => AutomationExit::new(1, TerminalReason::ToolHostError, message),
TurnErrorKind::Configuration => AutomationExit::configuration(message),
_ => AutomationExit::other(message),
}
}