Skip to main content

artifactize_harness/
error.rs

1//! Why an Agent review failed, as a request `errorCode`.
2
3use std::fmt;
4
5/// The `errorCode` of a request whose Agent review failed.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
7#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
8pub enum Code {
9    /// Credentials are missing, expired or rejected (HTTP 401 or 403).
10    Authentication,
11    /// A billing, credit or plan usage limit.
12    Quota,
13    /// Rate limited (HTTP 429) after the retries, or asked to wait past the deadline.
14    RateLimit,
15    /// A connection failure, an overloaded or failing server, or an interrupted stream,
16    /// after the retries.
17    Transient,
18    /// The review's `timeoutMs` deadline passed.
19    Timeout,
20    Cancelled,
21    /// `maxTokens` or `maxToolCalls` was exceeded.
22    ProviderBudgetExceeded,
23    /// No valid verdict after the one format repair.
24    InvalidResult,
25    /// The response's text degenerated into a long run of whitespace, after the retries; its
26    /// stream was stopped.
27    DegenerateOutput,
28    /// Any other provider failure: a rejected request, an unknown or different model,
29    /// an incomplete response or a malformed tool call.
30    ProviderError,
31    /// Anything else, such as unusable configuration or tools.
32    AgentError,
33}
34
35impl Code {
36    pub fn as_str(self) -> &'static str {
37        match self {
38            Self::Authentication => "AUTHENTICATION",
39            Self::Quota => "QUOTA",
40            Self::RateLimit => "RATE_LIMIT",
41            Self::Transient => "TRANSIENT",
42            Self::Timeout => "TIMEOUT",
43            Self::Cancelled => "CANCELLED",
44            Self::ProviderBudgetExceeded => "PROVIDER_BUDGET_EXCEEDED",
45            Self::InvalidResult => "INVALID_RESULT",
46            Self::DegenerateOutput => "DEGENERATE_OUTPUT",
47            Self::ProviderError => "PROVIDER_ERROR",
48            Self::AgentError => "AGENT_ERROR",
49        }
50    }
51
52    /// Failures that a turn without output may retry.
53    pub fn retryable(self) -> bool {
54        matches!(self, Self::RateLimit | Self::Transient)
55    }
56}
57
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct Failure {
60    pub code: Code,
61    pub message: String,
62    /// The provider's output failed once it had begun: it degenerated, stopped at the output
63    /// cap or broke off. The request was sound, so its turn may be sent again.
64    pub output_failed: bool,
65}
66
67impl Failure {
68    pub fn new(code: Code, message: impl Into<String>) -> Self {
69        Self {
70            code,
71            message: message.into(),
72            output_failed: false,
73        }
74    }
75
76    /// The same failure, marked as one of the provider's output.
77    pub fn of_output(self) -> Self {
78        Self {
79            output_failed: true,
80            ..self
81        }
82    }
83
84    pub fn cancelled() -> Self {
85        Self::new(Code::Cancelled, "Agent review was cancelled.")
86    }
87
88    pub fn timeout() -> Self {
89        Self::new(Code::Timeout, "Agent review timed out.")
90    }
91}
92
93/// An unclassified failure, such as a tool or configuration error.
94impl From<String> for Failure {
95    fn from(message: String) -> Self {
96        Self::new(Code::AgentError, message)
97    }
98}
99
100impl fmt::Display for Failure {
101    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
102        formatter.write_str(&self.message)
103    }
104}
105
106use artifactize_provider::llm as http;
107use serde::{Deserialize, Serialize};
108
109#[derive(Debug, Clone, Serialize, Deserialize)]
110#[serde(rename_all = "camelCase")]
111pub struct Attempt {
112    #[serde(default)]
113    pub turn: usize,
114    #[serde(default)]
115    pub attempt: usize,
116    #[serde(default)]
117    pub usage: http::Usage,
118    #[serde(skip_serializing_if = "Option::is_none")]
119    pub error: Option<String>,
120    #[serde(default, skip_serializing_if = "Option::is_none")]
121    pub error_code: Option<Code>,
122}
123
124impl From<http::Code> for Code {
125    fn from(code: http::Code) -> Self {
126        match code {
127            http::Code::Authentication => Self::Authentication,
128            http::Code::Quota => Self::Quota,
129            http::Code::RateLimit => Self::RateLimit,
130            http::Code::Transient => Self::Transient,
131            http::Code::Timeout => Self::Timeout,
132            http::Code::Cancelled => Self::Cancelled,
133            http::Code::BudgetExceeded => Self::ProviderBudgetExceeded,
134            http::Code::DegenerateOutput => Self::DegenerateOutput,
135            http::Code::ProviderError => Self::ProviderError,
136            http::Code::Configuration => Self::AgentError,
137        }
138    }
139}
140
141impl From<http::Failure> for Failure {
142    fn from(failure: http::Failure) -> Self {
143        let code = failure.code.into();
144        let message = failure_message(code, failure.message);
145        Self {
146            code,
147            message,
148            output_failed: failure.output_failed,
149        }
150    }
151}
152
153fn failure_message(code: Code, message: String) -> String {
154    match code {
155        Code::Cancelled => Failure::cancelled().message,
156        Code::Timeout => Failure::timeout().message,
157        Code::ProviderBudgetExceeded if message == http::driver::TOKEN_BUDGET => {
158            "PROVIDER_BUDGET_EXCEEDED: review exceeded its maxTokens budget.".into()
159        }
160        Code::ProviderBudgetExceeded if message == http::driver::TOOL_BUDGET => {
161            "PROVIDER_BUDGET_EXCEEDED: review exceeded its maxToolCalls budget.".into()
162        }
163        _ => message.replace("past the request deadline.", "past the review deadline."),
164    }
165}
166
167impl From<http::Attempt> for Attempt {
168    fn from(raw: http::Attempt) -> Self {
169        let code = raw.error_code.map(Code::from);
170        Self {
171            turn: raw.turn,
172            attempt: raw.attempt,
173            usage: raw.usage,
174            error: raw
175                .error
176                .map(|message| code.map_or(message.clone(), |code| failure_message(code, message))),
177            error_code: code,
178        }
179    }
180}