artifactize-core 0.27.0

The library behind artifactize: Artifacts, evals, reviews, the monitor and review models, and the shared operations every interface calls.
Documentation
//! CLI and desktop presentation of the provider's Codex sign-in.

use std::{io::Write, path::Path};
use tokio::sync::oneshot;

use artifactize_provider::auth::codex as provider;
pub use provider::{
    AUTH_FILE_VARIABLE, AUTH_URL_VARIABLE, CALLBACK_PATH, CALLBACK_PORT, CallbackPort, FileExpiry,
    Prompt, Status, StoredExpiry, Timestamp, auth_file, auth_root,
};

use super::{credential_location, storage::Tokens, writable_credential_location};

/// Sign in interactively and save artifactize's own tokens. The sign-in URL goes to
/// stderr, also with --json.
pub async fn login(state: Option<&Path>, repo: Option<&Path>) -> Result<(), String> {
    // Refuse before reading the terminal: where the tokens go and the sign-in root.
    credential_location(state, repo, Tokens::Codex)?;
    auth_root()?;
    let terminal = crate::platform::stdin_is_terminal();
    let pasted = if terminal {
        let (send, receive) = oneshot::channel();
        // Detached: a sign-in finished in the browser leaves this read unanswered.
        std::thread::Builder::new()
            .name("codex-login-input".into())
            .spawn(move || {
                for line in std::io::stdin().lines() {
                    match line {
                        Ok(line) if line.trim().is_empty() => continue,
                        Ok(line) => {
                            let _ = send.send(line);
                        }
                        Err(_) => {}
                    }
                    break;
                }
            })
            .map_err(|error| format!("Cannot start Codex sign-in input: {error}"))?;
        Some(receive)
    } else {
        None
    };
    login_with(state, repo, pasted, true, CallbackPort::Registered, |prompt| {
        let mut err = std::io::stderr().lock();
        let _ = writeln!(err, "Open this URL to sign in with Codex:\n{}", prompt.url);
        if !prompt.callback {
            let _ = writeln!(
                err,
                "Port {CALLBACK_PORT} is in use (another sign-in, such as the Codex CLI or app, may hold it), so the browser cannot return here."
            );
        }
        if terminal {
            let _ = writeln!(
                err,
                "When the browser cannot return here, paste the full URL it was sent to (starting http://localhost:{CALLBACK_PORT}{CALLBACK_PATH}?code=) and press Enter. Find it in the browser's address bar after the failed load, or in DevTools → Network if the page keeps loading."
            );
        }
    })
    .await
}

pub async fn login_with(
    state: Option<&Path>,
    repo: Option<&Path>,
    pasted: Option<oneshot::Receiver<String>>,
    browser: bool,
    callback_port: CallbackPort,
    show: impl FnOnce(&Prompt),
) -> Result<(), String> {
    let location = writable_credential_location(state, repo, Tokens::Codex)?;
    let open = browser.then_some(crate::platform::program::open_desktop);
    provider::login_with(&location, pasted, open, callback_port, show).await
}

pub fn status(state: Option<&Path>, repo: Option<&Path>) -> Result<Status, String> {
    let location = credential_location(state, repo, Tokens::Codex);
    provider::status(location.as_ref().map_err(String::as_str))
}

pub async fn logout(state: Option<&Path>, repo: Option<&Path>) -> Result<bool, String> {
    let location = writable_credential_location(state, repo, Tokens::Codex)?;
    provider::logout(Ok(&location)).await
}

#[cfg(all(test, unix))] // Only Unix opens via an external program the fixture can replace.
mod tests;