pitboard-core 0.22.0

The engine behind Pitboard: switches Claude Code, Codex and Claude Desktop between accounts by parking and restoring their logins. Its API serves Pitboard's own front ends.
Documentation
//! Antigravity behind the provider boundary, on the facts in [`super::assumptions`].

use super::run::{self, Plant};
use super::{document, live::AgyLogin, paths};
use crate::context::Context;
use crate::host::Os;
use crate::permit::Permit;
use crate::provider::{
    Adoption, Behind, Credential, Expiry, Identity, Isolation, LiveStore, Owner, ParkSemantics,
    Provider, ProviderError, ProviderId, SignInView,
};
use crate::store::{self, Live};
use crate::usage::Snapshot;
use serde_json::Value;

#[derive(Debug, Clone, Copy)]
pub(crate) struct Agy;

fn shape(detail: &str) -> ProviderError {
    ProviderError::ShapeUnexpected {
        provider: ProviderId::Agy,
        detail: detail.to_owned(),
    }
}

impl Provider for Agy {
    fn id(&self) -> ProviderId {
        ProviderId::Agy
    }

    fn live(&self, ctx: &Context) -> Result<LiveStore, ProviderError> {
        Ok(LiveStore {
            chain: Live::of(vec![Box::new(AgyLogin::of(ctx))]),
            service: paths::service(ctx),
        })
    }

    /// The account agy stored beside its tokens, read with no request (`agy_identity`). Google
    /// names the account by its email alone here, so the email is the identity.
    fn identify(&self, _ctx: &Context, credential: &Credential) -> Result<Owner, ProviderError> {
        let email = document::email(&credential.raw)
            .ok_or_else(|| shape("it names no account: it has no id_token_email"))?;
        Ok(Owner {
            account_uuid: email.to_lowercase(),
            email: email.to_owned(),
            organization_uuid: String::new(),
        })
    }

    fn identity(&self, ctx: &Context, credential: &Credential) -> Result<Identity, ProviderError> {
        self.identify(ctx, credential).map(|owner| owner.identity())
    }

    fn name(
        &self,
        ctx: &Context,
        credential: &Credential,
        _identity: &Identity,
    ) -> Result<String, ProviderError> {
        self.identify(ctx, credential).map(|owner| owner.email)
    }

    fn identifies_by_itself(&self) -> bool {
        true
    }

    // Asked of agy itself, run with the access token alone: the login in use is the tool's own
    // to renew, where it keeps it. Pitboard sends Google nothing (`agy_usage_command`).
    fn usage(&self, ctx: &Context, credential: &Credential) -> Result<Snapshot, ProviderError> {
        let permit = crate::permit::gate(ctx).map_err(|refused| ProviderError::Unsupported {
            provider: ProviderId::Agy,
            reason: refused.to_string(),
        })?;
        run::usage(ctx, permit, &credential.raw, Plant::AccessOnly).map(|ran| ran.usage)
    }

    // A run of agy on the whole parked login, which renews it where its access token lapsed and
    // says what it has left, kept as a reading of the account's; Pitboard asks Google nothing.
    fn renew(
        &self,
        ctx: &Context,
        permit: Permit,
        credential: &Credential,
    ) -> Result<Credential, ProviderError> {
        let ran = run::usage(ctx, permit, &credential.raw, Plant::Whole)?;
        let owner = self.identify(ctx, credential)?;
        let id = crate::state::new_id(ProviderId::Agy, &owner);
        crate::usage::readings::answered(ctx, permit, &[(id, ran.usage)]);
        Ok(Credential::new(
            ProviderId::Agy,
            ran.left.unwrap_or_else(|| credential.raw.clone()),
        ))
    }

    // The item is the session's and the files the home's, so both are named.
    fn slot(&self, ctx: &Context) -> String {
        format!(
            "{}:{}|{}",
            paths::service(ctx),
            paths::USER,
            paths::gemini_dir(ctx).display()
        )
    }

    // agy takes no lock around its login (`agy_takes_no_lock`).
    fn write_lock(&self, _ctx: &Context) -> Option<std::path::PathBuf> {
        None
    }

    fn refresh_lock(&self, _ctx: &Context) -> Option<(std::path::PathBuf, std::path::PathBuf)> {
        None
    }

    // The login names its own account.
    fn own_record(&self, _ctx: &Context) -> Option<Owner> {
        None
    }

    fn after_switch(
        &self,
        _ctx: &Context,
        _: Permit,
        _incoming: &crate::state::Account,
        _outgoing: &Owner,
    ) -> Result<(), crate::error::Error> {
        Ok(())
    }

    fn program(&self, ctx: &Context) -> Option<std::path::PathBuf> {
        crate::provider::program_of(ctx, ProviderId::Agy)
    }

    // In `dir` alone: the home moves agy's files, and `AGY_CLI_FORCE_FILE_TOKEN_STORAGE` keeps
    // its keyring item, which no home moves, out of it (`agy_files_only`). `agy` with no
    // argument and `AGY_CLI_CDE_AUTH_ACTION=login` signs in and stops, keeping the login in the
    // language server's file (`agy_sign_in`). A Gemini API key would sign in with no account.
    fn sign_in(
        &self,
        ctx: &Context,
        permit: Permit,
        dir: &std::path::Path,
    ) -> std::io::Result<std::process::Command> {
        let mut command = crate::provider::command(ctx, permit, ProviderId::Agy)?;
        let home = match ctx.os {
            Os::MacOs | Os::Linux => "HOME",
            Os::Windows => "USERPROFILE",
        };
        command
            .env(home, dir)
            .env("AGY_CLI_FORCE_FILE_TOKEN_STORAGE", "true")
            .env("AGY_CLI_CDE_AUTH_ACTION", "login")
            .env_remove("GEMINI_API_KEY")
            .current_dir(crate::switch::enroll::signin_work_dir(ctx));
        Ok(command)
    }

    fn login_from_sign_in(
        &self,
        ctx: &Context,
        dir: &std::path::Path,
    ) -> Result<Option<String>, store::Error> {
        let files = AgyLogin::files_in(ctx, dir);
        store::read_raw(&Live::of(vec![Box::new(files)]), &paths::service(ctx))
    }

    /// Everything a sign-in writes goes inside its home, so the directory is all there is.
    fn discard_signin(&self, _ctx: &Context, _: Permit, _dir: &std::path::Path) {}

    // It prints the address, then asks for the code the browser shows, and reads it from its
    // standard input (`agy_sign_in`).
    fn read_sign_in(&self, said: &str) -> SignInView {
        SignInView {
            url: crate::provider::https_address(said),
            wants_code: said.contains(document::ASKS_FOR_A_CODE),
        }
    }

    // A code it cannot exchange ends the sign-in: it reads no second one.
    fn refused_code(&self, _since: &str) -> bool {
        false
    }

    fn overridden_by(&self, _ctx: &Context) -> Vec<String> {
        Vec::new()
    }

    // A login through workforce identity federation is an organisation's, not a person's own.
    fn refuses(&self, _ctx: &Context, document: &Value, _owner: &Owner) -> Option<String> {
        ["wif_provider", "saved_wif_provider"]
            .into_iter()
            .any(|key| document[key].as_str().is_some_and(|set| !set.is_empty()))
            .then(|| {
                "Antigravity signs in here through an organisation's workforce identity \
                 federation, which is not a Google account of the person's own"
                    .to_owned()
            })
    }

    fn behind(&self, _ctx: &Context) -> Option<Behind> {
        None
    }

    // The App's language server, the IDE and every agy renew the login from memory and write
    // it back, so a switch waits for every one of them to close (`agy_holders`).
    fn held_by(&self) -> Option<crate::provider::HeldBy> {
        Some(crate::provider::HeldBy {
            holds: super::holders::holds,
            holders: super::holders::HOLDERS,
        })
    }

    fn adoption(&self, _behind: Option<&Behind>) -> Adoption {
        Adoption::NextOpen {
            app: ProviderId::Agy.name(),
        }
    }

    /// Until `/logout` is measured, a park is the only copy: agy's own sign-out may revoke
    /// the refresh token it clears (`agy_logout_revocation`), as Codex's does.
    fn park_semantics(&self) -> ParkSemantics {
        ParkSemantics::MoveOnly
    }

    fn private_signin_isolation(&self, _ctx: &Context) -> Isolation {
        Isolation::Isolated
    }

    fn slice(&self, live: &Value) -> Result<Value, ProviderError> {
        if !live.is_object() {
            return Err(shape("it is not a JSON object"));
        }
        if !document::has_token(live) {
            return Err(shape("it holds no tokens"));
        }
        Ok(live.clone())
    }

    fn plan(&self, document: &Value) -> Option<String> {
        document::plan(document)
    }

    fn splice(&self, _live: &Value, incoming: &Value) -> Result<Value, ProviderError> {
        self.slice(incoming)
    }

    fn fingerprint(&self, slice: &Value) -> String {
        document::refresh_token(slice)
            .map(store::fingerprint)
            .unwrap_or_default()
    }

    // agy states no refresh-token lifetime.
    fn expiry(&self, slice: &Value) -> Expiry {
        Expiry {
            access_expires_at: document::access_expiry(slice),
            refresh_expires_at: None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::provider::agy::login_for_a_test;

    fn credential(login: Value) -> Credential {
        Credential::new(ProviderId::Agy, login)
    }

    #[test]
    fn the_login_names_its_google_account_by_its_email_asking_nobody() {
        let ctx = Context::for_unit_test();
        let login = credential(login_for_a_test("Đạt@Example.com", "a", "r"));
        let owner = Agy.identify(&ctx, &login).unwrap();
        assert_eq!(owner.email, "Đạt@Example.com");
        assert_eq!(owner.account_uuid, "đạt@example.com");
        assert!(owner.organization_uuid.is_empty());
        assert!(Agy.identifies_by_itself());
        let mut unnamed = login_for_a_test("", "a", "r");
        unnamed["id_token_email"] = Value::Null;
        assert!(matches!(
            Agy.identify(&ctx, &credential(unnamed)),
            Err(ProviderError::ShapeUnexpected { .. })
        ));
    }

    // An email is no name for a park or a file, so the id is a handle on it.
    #[test]
    fn an_accounts_id_is_a_handle_on_its_email_never_the_email() {
        let owner = Owner {
            account_uuid: "a@example.com".into(),
            email: "a@example.com".into(),
            organization_uuid: String::new(),
        };
        let id = crate::state::new_id(ProviderId::Agy, &owner);
        assert!(id.starts_with("agy_"), "{id}");
        assert!(!id.contains('@') && !id.contains("example"), "{id}");
        assert!(id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_'));
    }

    #[test]
    fn the_whole_login_is_the_accounts_and_its_refresh_token_its_handle() {
        let login = login_for_a_test("a@example.com", "a", "refresh");
        assert_eq!(Agy.slice(&login).unwrap(), login);
        assert_eq!(Agy.fingerprint(&login), store::fingerprint("refresh"));
        assert_eq!(Agy.plan(&login).as_deref(), Some("Google AI Pro"));
        assert_eq!(
            Agy.expiry(&login).access_expires_at,
            crate::time::parse("2026-11-28T12:00:00Z")
        );
        assert!(Agy.slice(&serde_json::json!({"project_id": "p"})).is_err());
        assert!(Agy.slice(&serde_json::json!([])).is_err());
        assert_eq!(Agy.park_semantics(), ParkSemantics::MoveOnly);
    }

    #[test]
    fn a_login_through_workforce_identity_federation_is_refused() {
        let ctx = Context::for_unit_test();
        let owner = Agy
            .identify(
                &ctx,
                &credential(login_for_a_test("a@example.com", "a", "r")),
            )
            .unwrap();
        let mut federated = login_for_a_test("a@example.com", "a", "r");
        assert_eq!(Agy.refuses(&ctx, &federated, &owner), None);
        federated["wif_provider"] = serde_json::json!("locations/global/workforcePools/p");
        assert!(Agy.refuses(&ctx, &federated, &owner).is_some());
    }

    // As agy 1.5.19 prints it, colours and all.
    #[test]
    fn its_sign_in_gives_an_address_then_asks_for_the_code() {
        let address = "https://accounts.google.com/o/oauth2/v2/auth?client_id=x&prompt=consent";
        let said = format!(
            "\u{1b}[1mPlease visit the following URL to authorize the application:\u{1b}[0m\n\
             \u{1b}[36m{address}\u{1b}[0m\n"
        );
        let view = Agy.read_sign_in(&said);
        assert_eq!(view.url.as_deref(), Some(address));
        assert!(!view.wants_code);
        let view = Agy.read_sign_in(&format!("{said}Enter the authorization code: "));
        assert!(view.wants_code);
        assert!(!Agy.refused_code("Authentication failed: invalid_grant"));
    }

    #[test]
    fn a_sign_in_keeps_agys_keyring_out_and_its_files_in_the_private_home() {
        let dir = tempfile::tempdir().unwrap();
        let ctx =
            Context::for_unit_test().with_agy_program(super::super::program_for_a_test(dir.path()));
        let command = Agy.sign_in(&ctx, Permit::for_a_test(), dir.path()).unwrap();
        let env: std::collections::BTreeMap<_, _> = command
            .get_envs()
            .map(|(k, v)| (k.to_string_lossy().into_owned(), v.map(|v| v.to_owned())))
            .collect();
        let home = if cfg!(windows) { "USERPROFILE" } else { "HOME" };
        assert_eq!(env[home].as_deref(), Some(dir.path().as_os_str()));
        assert_eq!(
            env["AGY_CLI_FORCE_FILE_TOKEN_STORAGE"].as_deref(),
            Some(std::ffi::OsStr::new("true"))
        );
        assert_eq!(env["GEMINI_API_KEY"], None, "taken away");
        assert_eq!(Agy.private_signin_isolation(&ctx), Isolation::Isolated);
    }
}