artifactize-harness 0.27.0

The Agent evaluation harness for Artifactize.
Documentation
//! Built-in eval/direct providers, strict HTTP backend types, and machine-configured backend names.

use serde::{Deserialize, Serialize};

use crate::error::{Code, Failure};

impl From<HttpProvider> for Provider {
    fn from(provider: HttpProvider) -> Self {
        match provider {
            HttpProvider::Codex => Self::Codex,
            HttpProvider::Openai => Self::Openai,
            HttpProvider::Anthropic => Self::Anthropic,
            HttpProvider::Gemini => Self::Gemini,
        }
    }
}

impl TryFrom<Provider> for HttpProvider {
    type Error = String;

    fn try_from(provider: Provider) -> Result<Self, Self::Error> {
        match provider {
            Provider::Codex => Ok(Self::Codex),
            Provider::Openai => Ok(Self::Openai),
            Provider::Anthropic => Ok(Self::Anthropic),
            Provider::Gemini => Ok(Self::Gemini),
            Provider::ClaudeAgent => {
                Err("claude-agent runs through its native CLI, not a direct HTTP provider.".into())
            }
        }
    }
}

pub use artifactize_provider::names::{CustomBackendName, DirectBackend, HttpProvider};

/// A built-in eval/direct provider: one artifactize reaches with a sign-in, an API key, or
/// isolated Claude Code (`claude-agent`). No external agent can join this list.
#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Hash,
    Serialize,
    Deserialize,
    clap::ValueEnum,
)]
#[serde(rename_all = "lowercase")]
pub enum Provider {
    /// The ChatGPT/Codex account (artifactize login codex).
    Codex,
    /// The user's own Claude Code and its login (claude auth login).
    #[serde(rename = "claude-agent")]
    #[value(name = "claude-agent")]
    ClaudeAgent,
    /// The OpenAI API (OPENAI_API_KEY or a saved key).
    Openai,
    /// The Anthropic API (ANTHROPIC_API_KEY or a saved key).
    Anthropic,
    /// The Gemini API (GEMINI_API_KEY or a saved key).
    Gemini,
}

impl Provider {
    /// In the order Settings → Providers lists them.
    pub const ALL: [Self; 5] = [
        Self::Codex,
        Self::ClaudeAgent,
        Self::Openai,
        Self::Anthropic,
        Self::Gemini,
    ];

    pub fn as_str(self) -> &'static str {
        match self {
            Self::Anthropic => "anthropic",
            Self::ClaudeAgent => "claude-agent",
            Self::Codex => "codex",
            Self::Gemini => "gemini",
            Self::Openai => "openai",
        }
    }

    pub fn named(name: &str) -> Option<Self> {
        Self::ALL
            .into_iter()
            .find(|provider| provider.as_str() == name)
    }
}

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

/// Backends that 0.5.0 removed; a declaration naming one fails with its replacements.
const REMOVED_BACKENDS: [&str; 2] = ["chatgpt", "claude"];

/// What an Agent profile's `backend` names: a built-in [`Provider`], or a custom provider
/// set up on the machine that runs the eval. The project only declares the name.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(transparent)]
pub struct Backend(String);

impl Backend {
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// The built-in provider this names, or `None` for a custom provider.
    pub fn builtin(&self) -> Option<Provider> {
        Provider::named(&self.0)
    }

    /// A custom HTTP registration may live on a different machine from the parser.
    pub fn validate_eval(&self) -> Result<(), String> {
        self.selection().map(|_| ())
    }

    pub fn selection(&self) -> Result<Selection, String> {
        Ok(match self.builtin() {
            Some(Provider::ClaudeAgent) => Selection::ClaudeAgent,
            Some(provider) => Selection::Http(DirectBackend::Builtin {
                provider: provider.try_into().expect("direct HTTP provider"),
            }),
            None => Selection::Http(DirectBackend::Custom {
                name: self.0.parse().map_err(|error| {
                    format!("Backend {self} is not an evaluation backend: {error}")
                })?,
            }),
        })
    }

    /// Check that a Run can admit the declared backend, without resolving credentials.
    /// Only custom HTTP names need to be checked against the local provider registrations.
    pub fn admit(
        &self,
        registered: impl FnOnce(&CustomBackendName) -> Result<bool, String>,
    ) -> Result<(), Failure> {
        match self.selection()? {
            Selection::Http(DirectBackend::Custom { name }) if !registered(&name)? => {
                Err(Failure::new(Code::Authentication, self.not_registered()))
            }
            _ => Ok(()),
        }
    }

    pub fn not_registered(&self) -> String {
        format!(
            "Backend {self} is not an evaluation backend on this machine. No provider named {self} is set up on this machine; add it in Settings → Providers or with `artifactize provider add {self}`."
        )
    }

    /// Whether this name is reserved and cannot be used for a custom HTTP provider.
    pub fn is_reserved_custom(&self) -> bool {
        artifactize_provider::names::is_reserved_custom(&self.0)
    }
}

impl From<Provider> for Backend {
    fn from(provider: Provider) -> Self {
        Self(provider.as_str().to_owned())
    }
}

impl From<HttpProvider> for Backend {
    fn from(provider: HttpProvider) -> Self {
        Self(provider.as_str().to_owned())
    }
}

impl std::str::FromStr for Backend {
    type Err = String;
    fn from_str(name: &str) -> Result<Self, Self::Err> {
        if REMOVED_BACKENDS.contains(&name) {
            return Err(format!(
                r#"backend "{name}" was removed in 0.5.0; use "openai", "anthropic" or "gemini" with an API key, "codex" with a ChatGPT/Codex sign-in, or "claude-agent" with your Claude Code login"#
            ));
        }
        // Machine-local backend names use the same identifier grammar as HTTP registrations.
        const MAX_NAME_BYTES: usize = 64;
        if name.is_empty()
            || name.len() > MAX_NAME_BYTES
            || !name.as_bytes()[0].is_ascii_alphanumeric()
            || !name
                .bytes()
                .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
        {
            return Err("backend must match [A-Za-z0-9][A-Za-z0-9_-]{0,63}.".into());
        }
        Ok(Self(name.to_owned()))
    }
}

impl<'de> Deserialize<'de> for Backend {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        String::deserialize(deserializer)?
            .parse()
            .map_err(serde::de::Error::custom)
    }
}

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

impl From<&DirectBackend> for Backend {
    fn from(direct: &DirectBackend) -> Self {
        Self(direct.as_str().to_owned())
    }
}

/// The only two ways to run an Agent eval; there is no generic agent process route.
pub enum Selection {
    ClaudeAgent,
    Http(DirectBackend),
}

#[cfg(test)]
mod tests;