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's login where agy keeps it: its keyring item and its two token files, read and
//! written as one login (`agy_split_login`), so a switch never leaves part of the outgoing
//! account behind for agy to merge into the incoming one.

use super::{document, paths};
use crate::context::Context;
use crate::host::Os;
use crate::permit::Permit;
use crate::store::{Backend, Error, RawStore};
use document::Part;

/// The places, in the order agy reads them: the keyring item, unless agy keeps files alone
/// here, then the CLI's token file and the language server's.
pub(crate) struct AgyLogin {
    item: Option<Box<dyn RawStore>>,
    files: Vec<Box<dyn RawStore>>,
    os: Os,
    // Whether agy found its keyring wanting here before, and keeps a login it writes in files.
    marked: bool,
}

impl AgyLogin {
    pub(crate) fn of(ctx: &Context) -> AgyLogin {
        let host = ctx.host();
        AgyLogin {
            item: (!ctx.agy_files_only)
                .then(|| host.go_keyring(ctx, paths::USER))
                .flatten(),
            files: [paths::cli_file(ctx), paths::server_file(ctx)]
                .into_iter()
                .map(|path| host.file(path))
                .collect(),
            os: ctx.os,
            marked: paths::markers(ctx).iter().any(|marker| marker.exists()),
        }
    }

    /// The files a sign-in into `home` left, with no keyring: agy signs in there with
    /// `AGY_CLI_FORCE_FILE_TOKEN_STORAGE`.
    pub(crate) fn files_in(ctx: &Context, home: &std::path::Path) -> AgyLogin {
        let mut private = ctx.clone();
        private.home = home.to_path_buf();
        private.agy_files_only = true;
        AgyLogin::of(&private)
    }

    fn places(&self) -> impl Iterator<Item = &dyn RawStore> {
        self.item.iter().chain(&self.files).map(AsRef::as_ref)
    }

    fn is_item(&self, place: &dyn RawStore) -> bool {
        self.item
            .as_deref()
            .is_some_and(|item| std::ptr::addr_eq(item, place))
    }

    fn part(&self, place: &dyn RawStore, service: &str) -> Result<Part, Error> {
        let read = place.read(service)?;
        let text = match read {
            Some(stored) if self.is_item(place) => Some(document::opened(&stored)?),
            other => other,
        };
        Part::of(text.as_deref())
    }

    fn parts(&self, service: &str) -> Result<Vec<Part>, Error> {
        self.places()
            .map(|place| self.part(place, service))
            .collect()
    }

    // Whether the item can hold `login` as go-keyring keeps it: past its ceiling, agy keeps the
    // whole login in its file and clears the item (`agy_split_login`).
    fn fits(&self, item: &dyn RawStore, service: &str, login: &str) -> bool {
        item.cost(service, &document::sealed(login, self.os))
            .is_none_or(|cost| !cost.over())
    }
}

impl RawStore for AgyLogin {
    fn kind(&self) -> Backend {
        self.item.as_ref().map_or(Backend::File, |item| item.kind())
    }

    fn contains(&self, service: &str) -> Result<bool, Error> {
        Ok(document::merged(&self.parts(service)?)?.is_some())
    }

    // One place's login as it is, where only that place holds any; else the merged one.
    fn read(&self, service: &str) -> Result<Option<String>, Error> {
        let parts = self.parts(service)?;
        let held: Vec<&Part> = parts.iter().filter(|p| **p != Part::Nothing).collect();
        if let [Part::Whole(_)] = held.as_slice() {
            let (place, _) = self
                .places()
                .zip(&parts)
                .find(|(_, part)| matches!(part, Part::Whole(_)))
                .expect("the place that holds it");
            let read = place.read(service)?.expect("held a moment ago");
            return if self.is_item(place) {
                document::opened(&read).map(Some)
            } else {
                Ok(Some(read))
            };
        }
        document::merged(&parts)?
            .map(|login| serde_json::to_string(&login).map_err(|e| Error::Malformed(e.to_string())))
            .transpose()
    }

    // Where the login is now, or where agy would put one; then every other part cleared, so no
    // field of the account switched away from is merged into this one. Written first, cleared
    // after, so an interruption leaves a spare copy and never none.
    fn write(&self, permit: Permit, service: &str, contents: &str) -> Result<(), Error> {
        let incoming = Part::of(Some(contents))?;
        if !matches!(incoming, Part::Whole(_)) {
            return Err(Error::Write("an Antigravity login with no tokens".into()));
        }
        let parts = self.parts(service)?;
        // Two logins in two places are none Pitboard can tell is agy's, so neither is written over.
        document::merged(&parts)?;
        let holds = |at: usize| matches!(parts[at], Part::Whole(_));
        let item_fits = self
            .item
            .as_deref()
            .is_some_and(|item| self.fits(item, service, contents));
        // The item is the first place where there is one; the two files follow it.
        let files: Vec<usize> = (usize::from(self.item.is_some())..parts.len()).collect();
        let mut targets: Vec<usize> = (0..parts.len()).filter(|&at| holds(at)).collect();
        if self.item.is_some() && !item_fits && targets.contains(&0) {
            targets.retain(|&at| at != 0);
            if targets.is_empty() {
                targets.clone_from(&files);
            }
        }
        if targets.is_empty() {
            targets = if self.item.is_some() && item_fits && !self.marked {
                vec![0]
            } else {
                files
            };
        }
        let places: Vec<&dyn RawStore> = self.places().collect();
        for &at in &targets {
            let place = places[at];
            let stored = if self.is_item(place) {
                document::sealed(contents, self.os)
            } else {
                contents.to_owned()
            };
            place.write(permit, service, &stored)?;
        }
        crate::fault::point("agy.written");
        for (at, place) in places.iter().enumerate() {
            if !targets.contains(&at) && parts[at] != Part::Nothing {
                place.delete(permit, service)?;
            }
        }
        let back = document::merged(&self.parts(service)?)?;
        let Part::Whole(wanted) = incoming else {
            unreachable!("checked above")
        };
        if back.as_ref() == Some(&wanted) {
            Ok(())
        } else {
            Err(Error::NotDurable(
                "Antigravity's keyring item and token files do not hold what was written".into(),
            ))
        }
    }

    fn delete(&self, permit: Permit, service: &str) -> Result<(), Error> {
        for place in self.places() {
            place.delete(permit, service)?;
        }
        Ok(())
    }
}

#[cfg(test)]
#[allow(
    clippy::disallowed_methods,
    reason = "a test plants agy's marker in its own scratch home, as agy writes one"
)]
mod tests {
    use super::*;
    use crate::context::ScratchMachine;
    use crate::provider::agy::login_for_a_test;
    use serde_json::{Value, json};

    const SERVICE: &str = "pitboard-citest-agy";

    fn machine(home: &std::path::Path) -> ScratchMachine {
        ScratchMachine::at(home, |ctx| ctx.with_agy_service(SERVICE))
    }

    fn text(login: &Value) -> String {
        login.to_string()
    }

    // What the item holds, opened as agy opens it.
    fn item(m: &ScratchMachine) -> Option<Value> {
        m.host
            .live()
            .peek(SERVICE)
            .map(|held| serde_json::from_str(&document::opened(&held).unwrap()).unwrap())
    }

    fn file(m: &ScratchMachine, path: std::path::PathBuf) -> Option<Value> {
        m.host
            .file_at(path)
            .peek(SERVICE)
            .map(|held| serde_json::from_str(&held).unwrap())
    }

    #[test]
    fn a_login_with_no_place_yet_goes_to_the_item_and_reads_back() {
        let home = tempfile::tempdir().unwrap();
        let m = machine(home.path());
        let store = AgyLogin::of(&m.ctx);
        let login = login_for_a_test("a@example.com", "access", "refresh");
        assert!(!store.contains(SERVICE).unwrap());
        store
            .write(Permit::for_a_test(), SERVICE, &text(&login))
            .unwrap();
        assert_eq!(item(&m), Some(login.clone()));
        assert_eq!(file(&m, paths::cli_file(&m.ctx)), None);
        assert_eq!(file(&m, paths::server_file(&m.ctx)), None);
        let read: Value = serde_json::from_str(&store.read(SERVICE).unwrap().unwrap()).unwrap();
        assert_eq!(read, login);
    }

    // The outgoing account's project, left in a file beside its tokens in the item, would be
    // merged into the incoming login by agy.
    #[test]
    fn a_switch_writes_where_the_login_is_and_clears_every_other_part() {
        let home = tempfile::tempdir().unwrap();
        let m = machine(home.path());
        let outgoing = login_for_a_test("a@example.com", "a", "ra");
        m.host
            .live()
            .plant(SERVICE, &document::sealed(&text(&outgoing), m.ctx.os));
        m.host
            .file_at(paths::cli_file(&m.ctx))
            .plant(SERVICE, &json!({"project_id": "a-project"}).to_string());
        let store = AgyLogin::of(&m.ctx);
        let mut incoming = login_for_a_test("b@example.com", "b", "rb");
        incoming["project_id"] = json!("b-project");
        store
            .write(Permit::for_a_test(), SERVICE, &text(&incoming))
            .unwrap();
        assert_eq!(item(&m), Some(incoming.clone()));
        assert_eq!(file(&m, paths::cli_file(&m.ctx)), None);
        let read: Value = serde_json::from_str(&store.read(SERVICE).unwrap().unwrap()).unwrap();
        assert_eq!(read, incoming);
    }

    #[test]
    fn a_login_past_the_items_ceiling_goes_whole_to_the_files_and_the_item_is_cleared() {
        let home = tempfile::tempdir().unwrap();
        let m = machine(home.path());
        let outgoing = login_for_a_test("a@example.com", "a", "ra");
        m.host
            .live()
            .plant(SERVICE, &document::sealed(&text(&outgoing), m.ctx.os));
        m.host.live().takes_on_stdin(4032);
        // Past `security`'s stdin and Credential Manager's 2560 bytes alike.
        let mut incoming = login_for_a_test("b@example.com", "b", "rb");
        incoming["project_id"] = json!("p".repeat(5_000));
        AgyLogin::of(&m.ctx)
            .write(Permit::for_a_test(), SERVICE, &text(&incoming))
            .unwrap();
        assert_eq!(item(&m), None);
        assert_eq!(file(&m, paths::cli_file(&m.ctx)), Some(incoming.clone()));
        assert_eq!(file(&m, paths::server_file(&m.ctx)), Some(incoming));
    }

    #[test]
    fn where_agy_marked_its_keyring_wanting_a_new_login_goes_to_the_files() {
        let home = tempfile::tempdir().unwrap();
        let m = machine(home.path());
        let marker = &paths::markers(&m.ctx)[1];
        std::fs::create_dir_all(marker.parent().unwrap()).unwrap();
        std::fs::write(marker, "2026-11-28T12:00:00Z").unwrap();
        let login = login_for_a_test("a@example.com", "a", "ra");
        AgyLogin::of(&m.ctx)
            .write(Permit::for_a_test(), SERVICE, &text(&login))
            .unwrap();
        assert_eq!(item(&m), None);
        assert_eq!(file(&m, paths::server_file(&m.ctx)), Some(login));
    }

    #[test]
    fn where_agy_keeps_files_alone_its_item_is_never_read() {
        let home = tempfile::tempdir().unwrap();
        let m = machine(home.path());
        let mut ctx = m.ctx.clone();
        ctx.agy_files_only = true;
        let in_item = login_for_a_test("a@example.com", "a", "ra");
        m.host
            .live()
            .plant(SERVICE, &document::sealed(&text(&in_item), ctx.os));
        let store = AgyLogin::of(&ctx);
        assert!(!store.contains(SERVICE).unwrap());
        let login = login_for_a_test("b@example.com", "b", "rb");
        store
            .write(Permit::for_a_test(), SERVICE, &text(&login))
            .unwrap();
        assert_eq!(item(&m), Some(in_item), "left as it was");
        assert_eq!(file(&m, paths::cli_file(&ctx)), Some(login));
    }

    #[test]
    fn two_logins_in_two_places_are_refused_rather_than_guessed_at() {
        let home = tempfile::tempdir().unwrap();
        let m = machine(home.path());
        let (a, b) = (
            login_for_a_test("a@example.com", "a", "ra"),
            login_for_a_test("b@example.com", "b", "rb"),
        );
        m.host
            .live()
            .plant(SERVICE, &document::sealed(&text(&a), m.ctx.os));
        m.host
            .file_at(paths::server_file(&m.ctx))
            .plant(SERVICE, &text(&b));
        let store = AgyLogin::of(&m.ctx);
        assert!(matches!(store.read(SERVICE), Err(Error::Unreadable(_))));
        assert!(
            store
                .write(Permit::for_a_test(), SERVICE, &text(&a))
                .is_err()
        );
        assert_eq!(
            file(&m, paths::server_file(&m.ctx)),
            Some(b),
            "nothing changed"
        );
    }
}