artifactize-harness 0.27.1

The Agent evaluation harness for Artifactize.
Documentation
//! Why an Agent review failed, as a request `errorCode`.

use std::fmt;

/// The `errorCode` of a request whose Agent review failed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Code {
    /// Credentials are missing, expired or rejected (HTTP 401 or 403).
    Authentication,
    /// A billing, credit or plan usage limit.
    Quota,
    /// Rate limited (HTTP 429) after the retries, or asked to wait past the deadline.
    RateLimit,
    /// A connection failure, an overloaded or failing server, or an interrupted stream,
    /// after the retries.
    Transient,
    /// The review's `timeoutMs` deadline passed.
    Timeout,
    Cancelled,
    /// `maxTokens` or `maxToolCalls` was exceeded.
    ProviderBudgetExceeded,
    /// No valid verdict after the one format repair.
    InvalidResult,
    /// The response's text degenerated into a long run of whitespace, after the retries; its
    /// stream was stopped.
    DegenerateOutput,
    /// Any other provider failure: a rejected request, an unknown or different model,
    /// an incomplete response or a malformed tool call.
    ProviderError,
    /// Anything else, such as unusable configuration or tools.
    AgentError,
}

impl Code {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Authentication => "AUTHENTICATION",
            Self::Quota => "QUOTA",
            Self::RateLimit => "RATE_LIMIT",
            Self::Transient => "TRANSIENT",
            Self::Timeout => "TIMEOUT",
            Self::Cancelled => "CANCELLED",
            Self::ProviderBudgetExceeded => "PROVIDER_BUDGET_EXCEEDED",
            Self::InvalidResult => "INVALID_RESULT",
            Self::DegenerateOutput => "DEGENERATE_OUTPUT",
            Self::ProviderError => "PROVIDER_ERROR",
            Self::AgentError => "AGENT_ERROR",
        }
    }

    /// Failures that a turn without output may retry.
    pub fn retryable(self) -> bool {
        matches!(self, Self::RateLimit | Self::Transient)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Failure {
    pub code: Code,
    pub message: String,
    /// The provider's output failed once it had begun: it degenerated, stopped at the output
    /// cap or broke off. The request was sound, so its turn may be sent again.
    pub output_failed: bool,
}

impl Failure {
    pub fn new(code: Code, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
            output_failed: false,
        }
    }

    /// The same failure, marked as one of the provider's output.
    pub fn of_output(self) -> Self {
        Self {
            output_failed: true,
            ..self
        }
    }

    pub fn cancelled() -> Self {
        Self::new(Code::Cancelled, "Agent review was cancelled.")
    }

    pub fn timeout() -> Self {
        Self::new(Code::Timeout, "Agent review timed out.")
    }
}

/// An unclassified failure, such as a tool or configuration error.
impl From<String> for Failure {
    fn from(message: String) -> Self {
        Self::new(Code::AgentError, message)
    }
}

impl fmt::Display for Failure {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.message)
    }
}

use artifactize_provider::llm as http;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Attempt {
    #[serde(default)]
    pub turn: usize,
    #[serde(default)]
    pub attempt: usize,
    #[serde(default)]
    pub usage: http::Usage,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error_code: Option<Code>,
}

impl From<http::Code> for Code {
    fn from(code: http::Code) -> Self {
        match code {
            http::Code::Authentication => Self::Authentication,
            http::Code::Quota => Self::Quota,
            http::Code::RateLimit => Self::RateLimit,
            http::Code::Transient => Self::Transient,
            http::Code::Timeout => Self::Timeout,
            http::Code::Cancelled => Self::Cancelled,
            http::Code::BudgetExceeded => Self::ProviderBudgetExceeded,
            http::Code::DegenerateOutput => Self::DegenerateOutput,
            http::Code::ProviderError => Self::ProviderError,
            http::Code::Configuration => Self::AgentError,
        }
    }
}

impl From<http::Failure> for Failure {
    fn from(failure: http::Failure) -> Self {
        let code = failure.code.into();
        let message = failure_message(code, failure.message);
        Self {
            code,
            message,
            output_failed: failure.output_failed,
        }
    }
}

fn failure_message(code: Code, message: String) -> String {
    match code {
        Code::Cancelled => Failure::cancelled().message,
        Code::Timeout => Failure::timeout().message,
        Code::ProviderBudgetExceeded if message == http::driver::TOKEN_BUDGET => {
            "PROVIDER_BUDGET_EXCEEDED: review exceeded its maxTokens budget.".into()
        }
        Code::ProviderBudgetExceeded if message == http::driver::TOOL_BUDGET => {
            "PROVIDER_BUDGET_EXCEEDED: review exceeded its maxToolCalls budget.".into()
        }
        _ => message.replace("past the request deadline.", "past the review deadline."),
    }
}

impl From<http::Attempt> for Attempt {
    fn from(raw: http::Attempt) -> Self {
        let code = raw.error_code.map(Code::from);
        Self {
            turn: raw.turn,
            attempt: raw.attempt,
            usage: raw.usage,
            error: raw
                .error
                .map(|message| code.map_or(message.clone(), |code| failure_message(code, message))),
            error_code: code,
        }
    }
}