artifactize-core 0.27.2

The library behind artifactize: Artifacts, evals, reviews, the monitor and review models, and the shared operations every interface calls.
Documentation
//! Adapt Verify credential locations and session records to the harness and HTTP transport.

pub mod claude_agent;
pub(crate) mod delivery;
pub mod models;
#[cfg(test)]
pub(crate) mod tests;

use artifactize_provider::{auth::Location, llm as http};
use rig_core::completion::{CompletionRequest, CompletionResponse};
use serde_json::Value;
use std::path::Path;

use crate::{
    agent::error::{Code, Failure},
    auth::storage::Tokens,
    config::{Backend, HttpProvider, ModelId, Provider},
};
pub use artifactize_harness::{
    api::{Api, EndpointApi},
    error::Attempt,
};
use http::HttpRoute;
pub use http::codex;
pub use http::{TestEndpoint, Turn, active_test_endpoint, variable_endpoint, variable_endpoint_in};

pub fn base_url_variable(provider: Provider) -> Option<&'static str> {
    HttpProvider::try_from(provider)
        .ok()
        .map(http::base_url_variable)
}
pub fn test_endpoint(provider: Provider) -> Result<Option<TestEndpoint>, String> {
    match HttpProvider::try_from(provider) {
        Ok(provider) => http::test_endpoint(provider),
        Err(_) => Ok(None),
    }
}

pub(crate) fn codex_location(
    state: Option<&Path>,
    repo: Option<&Path>,
) -> Result<Location, String> {
    crate::auth::writable_credential_location(state, repo, Tokens::Codex)
}

/// Where a provider's requests go: its API, its root and its key.
pub(crate) enum Route {
    ClaudeAgent,
    Http(Box<HttpRoute>),
}

/// Resolve a native Claude route or a direct HTTP provider with its credentials.
pub(crate) fn route(
    backend: &Backend,
    state: Option<&Path>,
    repo: Option<&Path>,
    purpose: &str,
) -> Result<Route, Failure> {
    use artifactize_harness::backend::Selection;
    let direct = match backend.selection()? {
        Selection::ClaudeAgent => return Ok(Route::ClaudeAgent),
        Selection::Http(direct) => direct,
    };
    let location = crate::auth::credential_location(state, repo, Tokens::Providers);
    HttpRoute::resolve(&direct, location.as_ref().map_err(String::as_str), purpose)?
        .map(Box::new)
        .map(Route::Http)
        .ok_or_else(|| Failure::new(Code::Authentication, backend.not_registered()))
}

pub struct Client(pub(crate) http::Client);

impl Client {
    #[doc(hidden)]
    pub fn from_openai(
        model: Box<rig_core::Model<rig_core::providers::openai::responses_api::wire::Responses>>,
        key: String,
    ) -> Self {
        Self(http::Client::from_openai(model, key))
    }

    pub fn new(
        backend: &Backend,
        model: &ModelId,
        state: &Path,
        repo: &Path,
    ) -> Result<Self, Failure> {
        match route(backend, Some(state), Some(repo), "for this Agent backend")? {
            Route::Http(route) => Self::at(*route, model, state, repo),
            Route::ClaudeAgent => Err(Failure::new(
                Code::AgentError,
                "Unsupported client backend: claude-agent runs reviews through Claude Code.",
            )),
        }
    }

    pub(crate) fn at(
        route: HttpRoute,
        model: &ModelId,
        state: &Path,
        repo: &Path,
    ) -> Result<Self, Failure> {
        let location =
            if route.api() == http::Api::Codex && crate::auth::codex::auth_file().is_none() {
                codex_location(Some(state), Some(repo))
            } else {
                crate::auth::credential_location(Some(state), Some(repo), Tokens::Codex)
            };
        Ok(Self(http::Client::at(route, model, location)?))
    }

    pub fn api(&self) -> Api {
        self.0.api().into()
    }

    pub fn parameters(
        api: Api,
        reasoning: Option<&str>,
        session: &crate::types::SessionId,
    ) -> Result<Value, String> {
        artifactize_harness::api::parameters(api, reasoning, session.as_str())
    }

    pub fn output_format(api: Api, parameters: &mut Value, schema: Value) {
        artifactize_harness::api::output_format(api, parameters, schema);
    }

    pub async fn turn(
        &self,
        request: &CompletionRequest,
        turn: Turn<'_>,
        attempts: &mut Vec<Attempt>,
    ) -> Result<CompletionResponse, Failure> {
        self.turn_observed(request, turn, attempts, &mut |_| {})
            .await
    }

    pub async fn turn_observed(
        &self,
        request: &CompletionRequest,
        turn: Turn<'_>,
        attempts: &mut Vec<Attempt>,
        observe: &mut impl FnMut(crate::agent::session::Delivery),
    ) -> Result<CompletionResponse, Failure> {
        let mut transported = Vec::new();
        let result = self
            .0
            .turn_observed(request, turn, &mut transported, &mut |event| {
                observe(event.into())
            })
            .await;
        attempts.extend(transported.into_iter().map(Attempt::from));
        Ok(result?)
    }
}