agyswap-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
agyswap/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ from importlib.metadata import PackageNotFoundError, version
2
+
3
+ try:
4
+ __version__ = version("agyswap-cli")
5
+ except PackageNotFoundError:
6
+ __version__ = "0.0.0"
agyswap/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from agyswap.cli import main
4
+
5
+ sys.exit(main())
agyswap/cli.py ADDED
@@ -0,0 +1,368 @@
1
+ """Multi-account switcher for the Antigravity CLI (agy).
2
+
3
+ agy keeps its OAuth token in the OS keyring via go-keyring
4
+ (service "gemini", user "antigravity") as a JSON blob. An account is
5
+ a stored copy of that blob; switching writes another copy back.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import fcntl
12
+ import json
13
+ import os
14
+ import subprocess
15
+ import sys
16
+ from concurrent.futures import ThreadPoolExecutor
17
+ from contextlib import contextmanager
18
+ from datetime import UTC, datetime
19
+ from pathlib import Path
20
+
21
+ from rich.console import Console
22
+ from rich.text import Text
23
+
24
+ from agyswap import __version__
25
+ from agyswap.usage import UsageError, account_usage, claims, parse_time
26
+
27
+ SERVICE = "gemini"
28
+ USERNAME = "antigravity"
29
+
30
+
31
+ class SwapError(Exception):
32
+ pass
33
+
34
+
35
+ def store_path() -> Path:
36
+ return Path(os.environ.get("AGYSWAP_HOME", Path.home() / ".agyswap")) / "accounts.json"
37
+
38
+
39
+ def load_store() -> dict:
40
+ p = store_path()
41
+ if not p.exists():
42
+ return {"accounts": {}}
43
+ return json.loads(p.read_text())
44
+
45
+
46
+ @contextmanager
47
+ def locked_store():
48
+ """Load the store under an exclusive lock; hold it for the whole read-modify-write."""
49
+ lock = store_path().with_name(".lock")
50
+ lock.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
51
+ with open(lock, "w") as f:
52
+ fcntl.flock(f, fcntl.LOCK_EX)
53
+ yield load_store()
54
+
55
+
56
+ def save_store(store: dict) -> None:
57
+ p = store_path()
58
+ p.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
59
+ tmp = p.with_suffix(".tmp")
60
+ # Refresh tokens live here: owner-only from the first byte.
61
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
62
+ with os.fdopen(fd, "w") as f:
63
+ json.dump(store, f, indent=2)
64
+ os.replace(tmp, p)
65
+
66
+
67
+ def _secret_tool(*args: str, stdin: str | None = None) -> subprocess.CompletedProcess:
68
+ # ponytail: Linux Secret Service only; macOS Keychain / Windows Credential Manager when needed.
69
+ try:
70
+ return subprocess.run(["secret-tool", *args], input=stdin, capture_output=True, text=True, timeout=30)
71
+ except FileNotFoundError:
72
+ raise SwapError("secret-tool not found. Install libsecret (e.g. `dnf install libsecret`).") from None
73
+ except subprocess.TimeoutExpired:
74
+ raise SwapError("keyring did not answer within 30s (locked?). Unlock it and try again.") from None
75
+
76
+
77
+ def read_token() -> str | None:
78
+ r = _secret_tool("lookup", "service", SERVICE, "username", USERNAME)
79
+ return r.stdout if r.returncode == 0 and r.stdout else None
80
+
81
+
82
+ def write_token(token: str) -> None:
83
+ r = _secret_tool(
84
+ "store",
85
+ f"--label=Password for '{USERNAME}' on '{SERVICE}'",
86
+ "service",
87
+ SERVICE,
88
+ "username",
89
+ USERNAME,
90
+ stdin=token,
91
+ )
92
+ if r.returncode != 0:
93
+ raise SwapError(f"Failed to write keyring: {r.stderr.strip()}")
94
+
95
+
96
+ def email_of(token: str | None) -> str | None:
97
+ return claims(token).get("email") or None
98
+
99
+
100
+ def agy_running() -> bool:
101
+ # The background updater never touches the token; any other agy process may refresh it.
102
+ r = subprocess.run(["pgrep", "-a", "-x", "agy"], capture_output=True, text=True)
103
+ return any("--bg-updater" not in line for line in r.stdout.splitlines())
104
+
105
+
106
+ def find_slot(store: dict, target: str) -> str:
107
+ accounts = store["accounts"]
108
+ if target in accounts:
109
+ return target
110
+ for slot, acc in accounts.items():
111
+ if acc["email"].lower() == target.lower():
112
+ return slot
113
+ raise SwapError(f"No account matches '{target}'. Run `agyswap list`.")
114
+
115
+
116
+ def slot_for_email(store: dict, email: str | None) -> str | None:
117
+ if not email:
118
+ return None
119
+ return next((s for s, a in store["accounts"].items() if a["email"].lower() == email.lower()), None)
120
+
121
+
122
+ def next_slot(store: dict) -> str:
123
+ return str(max(map(int, store["accounts"]), default=0) + 1)
124
+
125
+
126
+ def cmd_add(slot: int | None = None) -> str:
127
+ token = read_token()
128
+ email = email_of(token)
129
+ if not email:
130
+ raise SwapError("agy is not signed in. Run `agy`, sign in, exit, then `agyswap add`.")
131
+ with locked_store() as store:
132
+ existing = slot_for_email(store, email)
133
+ if slot is None:
134
+ slot = existing or next_slot(store)
135
+ else:
136
+ if slot < 1:
137
+ raise SwapError("--slot must be 1 or higher.")
138
+ slot = str(slot)
139
+ other = store["accounts"].get(slot)
140
+ if other and other["email"].lower() != email.lower():
141
+ raise SwapError(f"Slot {slot} holds {other['email']}. Remove it first or pick another slot.")
142
+ if existing and existing != slot:
143
+ del store["accounts"][existing] # move the account to the requested slot
144
+ store["accounts"][slot] = {"email": email, "token": token}
145
+ save_store(store)
146
+ return f"{'Updated' if existing == slot else 'Moved' if existing else 'Added'} account {slot}: {email}"
147
+
148
+
149
+ def collect_usage() -> list[dict]:
150
+ """Quota for every stored account. Refreshed tokens are saved back to the store."""
151
+ store = load_store()
152
+ live = read_token()
153
+ active = email_of(live)
154
+
155
+ def one(slot: str) -> dict:
156
+ acc = store["accounts"][slot]
157
+ # The keyring copy is the newest for the active account; never write the keyring here.
158
+ token = live if acc["email"] == active else acc["token"]
159
+ row = {"slot": slot, "email": acc["email"], "active": acc["email"] == active, "pools": [], "error": None}
160
+ try:
161
+ row["pools"], acc["token"] = account_usage(token)
162
+ except (UsageError, KeyError, ValueError) as e:
163
+ row["error"] = str(e)
164
+ except Exception as e:
165
+ # The message or traceback of an unexpected error may carry token text; keep the type only.
166
+ row["error"] = f"unexpected error: {type(e).__name__}"
167
+ return row
168
+
169
+ slots = sorted(store["accounts"], key=int)
170
+ with ThreadPoolExecutor(max_workers=8) as ex:
171
+ rows = list(ex.map(one, slots))
172
+ # The fetch ran unlocked for seconds; merge tokens into a fresh read so a
173
+ # concurrent add/remove/switch is never undone.
174
+ refreshed = {store["accounts"][r["slot"]]["email"]: store["accounts"][r["slot"]]["token"] for r in rows}
175
+ with locked_store() as current:
176
+ for acc in current["accounts"].values():
177
+ # Only take a token that is still for this account and actually newer.
178
+ new = refreshed.get(acc["email"])
179
+ if new and new != acc["token"] and email_of(new) == acc["email"] and _expiry(new) > _expiry(acc["token"]):
180
+ acc["token"] = new
181
+ if current["accounts"]:
182
+ save_store(current)
183
+ return rows
184
+
185
+
186
+ def _expiry(token: str) -> datetime:
187
+ try:
188
+ return parse_time(json.loads(token)["token"]["expiry"]) or datetime.min.replace(tzinfo=UTC)
189
+ except (KeyError, ValueError, TypeError):
190
+ return datetime.min.replace(tzinfo=UTC)
191
+
192
+
193
+ BAR = 30
194
+
195
+
196
+ def _countdown(reset: datetime | None) -> str:
197
+ if not reset:
198
+ return ""
199
+ secs = max(0, int((reset - datetime.now(UTC)).total_seconds()))
200
+ d, h, m = secs // 86400, secs % 86400 // 3600, secs % 3600 // 60
201
+ return "resets " + (f"{d}d {h}h" if d else f"{h}h {m}m")
202
+
203
+
204
+ def _color(used: float) -> str:
205
+ return "#22c55e" if used < 0.5 else "#eab308" if used < 0.8 else "#ef4444"
206
+
207
+
208
+ def account_text(row: dict) -> Text:
209
+ t = Text()
210
+ t.append(f"{row['slot']:>2} ", "bold")
211
+ t.append(row["email"], "bold")
212
+ if row["active"]:
213
+ t.append(" ● active", "bold #ffa62b")
214
+ prev_group = None
215
+ width = max([12] + [len(p.group) + 2 for p in row["pools"]])
216
+ for p in row["pools"]:
217
+ filled = round(p.used * BAR)
218
+ # Group name only on its first row; the window column stays aligned.
219
+ t.append(
220
+ f"\n {p.group if p.group != prev_group else '':<{width}}", "bold" if p.group != prev_group else "dim"
221
+ )
222
+ prev_group = p.group
223
+ t.append(f"{p.window:<8}", "dim")
224
+ t.append("━" * filled, _color(p.used))
225
+ t.append("━" * (BAR - filled), "grey35")
226
+ t.append(f" {p.used:>4.0%}", f"bold {_color(p.used)}")
227
+ if p.reset:
228
+ t.append(f" {_countdown(p.reset)}", "dim")
229
+ if row["error"]:
230
+ t.append(f"\n ✕ {row['error']}", "#ef4444")
231
+ return t
232
+
233
+
234
+ def cmd_list() -> None:
235
+ if not load_store()["accounts"]:
236
+ print("No accounts stored. Sign in to agy, then run `agyswap add`.")
237
+ return
238
+ console = Console()
239
+ for row in collect_usage():
240
+ console.print(account_text(row))
241
+ console.print()
242
+
243
+
244
+ def cmd_status() -> None:
245
+ email = email_of(read_token())
246
+ if not email:
247
+ print("Not signed in.")
248
+ return
249
+ slot = slot_for_email(load_store(), email)
250
+ print(f"{email} (account {slot})" if slot else f"{email} (not stored, run `agyswap add`)")
251
+
252
+
253
+ def cmd_switch(target: str | None = None, force: bool = False, ignore_running: bool = False) -> str:
254
+ """Switch the keyring login. `force` skips copying the live token back into its slot,
255
+ an unstored live login is still saved first."""
256
+ if agy_running() and not ignore_running:
257
+ raise SwapError(
258
+ "agy is running. Exit it first: a running agy refreshes and re-saves "
259
+ "its own token, undoing the switch. (--ignore-running to override)"
260
+ )
261
+ with locked_store() as store:
262
+ if not store["accounts"]:
263
+ raise SwapError("No accounts stored. Run `agyswap add` first.")
264
+ note = ""
265
+ live = read_token()
266
+ live_email = email_of(live)
267
+ current = slot_for_email(store, live_email)
268
+ if current:
269
+ if not force:
270
+ # Capture the live token so refreshes made by agy are not lost.
271
+ store["accounts"][current]["token"] = live
272
+ elif live_email:
273
+ # Never overwrite a login we have no copy of: store it first.
274
+ current = next_slot(store)
275
+ store["accounts"][current] = {"email": live_email, "token": live}
276
+ note = f"Saved unstored login {live_email} as account {current}. "
277
+ slots = sorted(store["accounts"], key=int)
278
+ if target is None:
279
+ target = slots[(slots.index(current) + 1) % len(slots)] if current else slots[0]
280
+ slot = find_slot(store, target)
281
+ if slot == current:
282
+ save_store(store)
283
+ return note + f"Already on account {slot}: {store['accounts'][slot]['email']}"
284
+ save_store(store) # persist synced token before overwriting the keyring
285
+ write_token(store["accounts"][slot]["token"])
286
+ return note + f"Switched to account {slot}: {store['accounts'][slot]['email']}"
287
+
288
+
289
+ def cmd_remove(target: str) -> str:
290
+ with locked_store() as store:
291
+ slot = find_slot(store, target)
292
+ email = store["accounts"].pop(slot)["email"]
293
+ save_store(store)
294
+ return f"Removed account {slot}: {email}"
295
+
296
+
297
+ def confirm_remove(target: str) -> bool:
298
+ """Ask before forgetting an account. Only prompts on a TTY."""
299
+ store = load_store()
300
+ slot = find_slot(store, target)
301
+ email = store["accounts"][slot]["email"]
302
+ if not sys.stdin.isatty():
303
+ raise SwapError("Refusing to remove without confirmation. Pass --yes to remove from a script.")
304
+ if email == email_of(read_token()):
305
+ print(f"warning: account {slot} ({email}) is currently active", file=sys.stderr)
306
+ try:
307
+ answer = input(f"Remove account {slot} ({email})? [y/N] ")
308
+ except (EOFError, KeyboardInterrupt):
309
+ print() # Ctrl-D / Ctrl-C mean "no"; keep the prompt line tidy
310
+ return False
311
+ return answer.strip().lower() in ("y", "yes")
312
+
313
+
314
+ def build_parser() -> argparse.ArgumentParser:
315
+ p = argparse.ArgumentParser(prog="agyswap", description="Multi-account switcher for the Antigravity CLI (agy)")
316
+ p.add_argument("--version", action="version", version=__version__)
317
+ sub = p.add_subparsers(dest="cmd")
318
+ sub.add_parser("tui", help="interactive dashboard (also: bare agyswap)")
319
+ add = sub.add_parser("add", help="store the account agy is signed in with")
320
+ add.add_argument("--slot", type=int, help="store into this slot number")
321
+ sub.add_parser("list", aliases=["ls"], help="list stored accounts with quota usage")
322
+ sub.add_parser("status", help="show the active account")
323
+ sw = sub.add_parser("switch", help="switch to next account, or to <num|email>")
324
+ sw.add_argument("target", nargs="?")
325
+ sw.add_argument(
326
+ "--force", action="store_true", help="switch without copying the live login's token back into its slot first"
327
+ )
328
+ sw.add_argument("--ignore-running", action="store_true", help="switch even if agy is running")
329
+ rm = sub.add_parser("remove", aliases=["rm"], help="forget a stored account")
330
+ rm.add_argument("target")
331
+ rm.add_argument("-y", "--yes", action="store_true", help="remove without asking")
332
+ return p
333
+
334
+
335
+ def main(argv: list[str] | None = None) -> int:
336
+ parser = build_parser()
337
+ args = parser.parse_args(argv)
338
+ if args.cmd is None:
339
+ if not (sys.stdin.isatty() and sys.stdout.isatty()):
340
+ parser.error("no command given — try 'agyswap --help'")
341
+ args.cmd = "tui"
342
+ try:
343
+ match args.cmd:
344
+ case "tui":
345
+ from agyswap.tui import AgySwapApp
346
+
347
+ AgySwapApp().run()
348
+ case "add":
349
+ print(cmd_add(args.slot))
350
+ case "list" | "ls":
351
+ cmd_list()
352
+ case "status":
353
+ cmd_status()
354
+ case "switch":
355
+ print(cmd_switch(args.target, args.force, args.ignore_running))
356
+ case "remove" | "rm":
357
+ if not args.yes and not confirm_remove(args.target):
358
+ print("Cancelled")
359
+ return 0
360
+ print(cmd_remove(args.target))
361
+ except SwapError as e:
362
+ print(f"error: {e}", file=sys.stderr)
363
+ return 1
364
+ return 0
365
+
366
+
367
+ if __name__ == "__main__":
368
+ sys.exit(main())
agyswap/tui.py ADDED
@@ -0,0 +1,199 @@
1
+ """Interactive dashboard: every account's quota, keyboard-driven switching."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime
6
+
7
+ from rich.markup import escape
8
+ from textual import work
9
+ from textual.app import App, ComposeResult
10
+ from textual.binding import Binding
11
+ from textual.containers import Vertical
12
+ from textual.screen import ModalScreen
13
+ from textual.theme import Theme
14
+ from textual.widgets import Footer, Label, ListItem, ListView, Static
15
+
16
+ from agyswap import cli
17
+
18
+ REFRESH_SECS = 120
19
+
20
+ PITCH_BLACK = Theme(
21
+ name="pitch-black",
22
+ primary="#0178d4",
23
+ secondary="#8a8a8a",
24
+ accent="#ffa62b",
25
+ foreground="#e5e5e5",
26
+ background="#000000",
27
+ surface="#000000",
28
+ panel="#0a0a0a",
29
+ success="#22c55e",
30
+ warning="#eab308",
31
+ error="#ef4444",
32
+ dark=True,
33
+ variables={
34
+ "block-cursor-foreground": "#e5e5e5",
35
+ "block-cursor-background": "#000000",
36
+ "block-cursor-text-style": "none",
37
+ "block-cursor-blurred-foreground": "#e5e5e5",
38
+ "block-cursor-blurred-background": "#000000",
39
+ "block-cursor-blurred-text-style": "none",
40
+ "block-hover-background": "#000000",
41
+ "footer-background": "#141414",
42
+ "footer-item-background": "#141414",
43
+ "footer-key-background": "#ffa62b",
44
+ "footer-key-foreground": "#000000",
45
+ "footer-description-foreground": "#d4d4d4",
46
+ "scrollbar": "#262626",
47
+ "scrollbar-background": "#000000",
48
+ },
49
+ )
50
+
51
+
52
+ class Confirm(ModalScreen[bool]):
53
+ BINDINGS = [Binding("y", "answer(True)", "Yes"), Binding("n,escape", "answer(False)", "No")]
54
+ DEFAULT_CSS = """
55
+ Confirm { align: center middle; background: #000000 70%; }
56
+ Confirm > Vertical { width: 64; height: auto; border: round $error; padding: 1 2; background: #000000; }
57
+ Confirm .hint { color: $text-muted; margin-top: 1; }
58
+ """
59
+
60
+ def __init__(self, question: str) -> None:
61
+ super().__init__()
62
+ self.question = question
63
+
64
+ def compose(self) -> ComposeResult:
65
+ with Vertical():
66
+ yield Label(self.question)
67
+ yield Label("[b $error]y[/] remove [b]n[/] cancel", classes="hint")
68
+
69
+ def action_answer(self, value: bool) -> None:
70
+ self.dismiss(value)
71
+
72
+
73
+ class AgySwapApp(App):
74
+ TITLE = "agyswap - Antigravity CLI Accounts Swap"
75
+ ENABLE_COMMAND_PALETTE = False
76
+ CSS = """
77
+ Screen { background: #000000; }
78
+ #title { width: 1fr; height: 3; padding: 1 2; background: #000000; text-align: center; }
79
+ Footer { background: #141414; padding: 0 2; }
80
+ FooterKey .footer-key--key, FooterKey.-compact .footer-key--key { padding: 0 1; text-style: bold; }
81
+ FooterKey .footer-key--description, FooterKey.-compact .footer-key--description { padding: 0 2 0 1; }
82
+ ListView { height: 1fr; padding: 0 1; background: #000000; }
83
+ ListView:focus { background-tint: #000000 0%; }
84
+ ListView > ListItem { height: auto; padding: 1 2; background: #000000; }
85
+ ListView > ListItem.-highlight, ListView:focus > ListItem.-highlight {
86
+ background: $primary;
87
+ color: #ffffff;
88
+ }
89
+ #status { height: 1; padding: 0 2; color: $text-muted; background: #000000; }
90
+ """
91
+ BINDINGS = [
92
+ Binding("s", "switch", "Switch"),
93
+ Binding("a", "add", "Add current"),
94
+ Binding("d", "remove", "Remove"),
95
+ Binding("r", "refresh", "Refresh"),
96
+ Binding("j", "cursor_down", show=False),
97
+ Binding("k", "cursor_up", show=False),
98
+ Binding("q", "quit", "Quit"),
99
+ ]
100
+
101
+ def compose(self) -> ComposeResult:
102
+ yield Static("[b $accent]agyswap[/] [dim]- Antigravity CLI Accounts Swap[/]", id="title")
103
+ yield ListView()
104
+ yield Static("Loading…", id="status")
105
+ yield Footer()
106
+
107
+ def on_mount(self) -> None:
108
+ self.register_theme(PITCH_BLACK)
109
+ self.theme = "pitch-black"
110
+ self.rows: list[dict] = []
111
+ self.action_refresh()
112
+ self.set_interval(REFRESH_SECS, self.action_refresh)
113
+
114
+ # --- data -------------------------------------------------------------
115
+
116
+ @work(thread=True, exclusive=True)
117
+ def action_refresh(self) -> None:
118
+ self.call_from_thread(self._status, "[dim]⟳ refreshing usage…[/]")
119
+ # Textual's crash report prints locals, and these hold tokens; show the type only. The UI
120
+ # calls stay outside the except blocks so a failing call never chains the original error.
121
+ try:
122
+ rows, err = cli.collect_usage(), None
123
+ except cli.SwapError as e:
124
+ rows, err = [], escape(str(e))
125
+ except Exception as e:
126
+ rows, err = [], f"refresh failed: {type(e).__name__}"
127
+ if err is not None:
128
+ self.call_from_thread(self._status, f"[$error]{err}[/]")
129
+ return
130
+ self.call_from_thread(self._show, rows)
131
+
132
+ def _show(self, rows: list[dict]) -> None:
133
+ lv = self.query_one(ListView)
134
+ keep = lv.index or 0
135
+ self.rows = rows
136
+ lv.clear()
137
+ for row in rows:
138
+ lv.append(ListItem(Static(cli.account_text(row))))
139
+ if rows:
140
+ lv.index = min(keep, len(rows) - 1)
141
+ n = len(rows)
142
+ self._status(
143
+ f"{n} account{'s' if n != 1 else ''} · updated {datetime.now():%H:%M}"
144
+ f" · refreshes every {REFRESH_SECS // 60} min"
145
+ )
146
+ else:
147
+ lv.append(ListItem(Static("No accounts yet.\nIn agy: /logout, sign in, exit. Then press [b]a[/b].")))
148
+ self._status("")
149
+
150
+ def _status(self, msg: str) -> None:
151
+ self.query_one("#status", Static).update(msg)
152
+
153
+ def _selected(self) -> dict | None:
154
+ idx = self.query_one(ListView).index
155
+ return self.rows[idx] if self.rows and idx is not None and idx < len(self.rows) else None
156
+
157
+ def _run(self, fn, *args) -> bool:
158
+ try:
159
+ msg, err = fn(*args), None
160
+ except cli.SwapError as e:
161
+ msg, err = None, str(e)
162
+ except Exception as e:
163
+ msg, err = None, f"failed: {type(e).__name__}"
164
+ if err is not None:
165
+ self.notify(err, severity="error", timeout=8)
166
+ return False
167
+ self.notify(msg)
168
+ return True
169
+
170
+ # --- actions ----------------------------------------------------------
171
+
172
+ def action_switch(self) -> None:
173
+ row = self._selected()
174
+ if row and self._run(cli.cmd_switch, row["slot"], False):
175
+ self.action_refresh()
176
+
177
+ def on_list_view_selected(self) -> None:
178
+ self.action_switch()
179
+
180
+ def action_add(self) -> None:
181
+ if self._run(cli.cmd_add, None):
182
+ self.action_refresh()
183
+
184
+ def action_remove(self) -> None:
185
+ row = self._selected()
186
+ if not row:
187
+ return
188
+
189
+ def done(ok: bool | None) -> None:
190
+ if ok and self._run(cli.cmd_remove, row["slot"]):
191
+ self.action_refresh()
192
+
193
+ self.push_screen(Confirm(f"Remove account {row['slot']}: [b]{row['email']}[/b]?"), done)
194
+
195
+ def action_cursor_down(self) -> None:
196
+ self.query_one(ListView).action_cursor_down()
197
+
198
+ def action_cursor_up(self) -> None:
199
+ self.query_one(ListView).action_cursor_up()
agyswap/usage.py ADDED
@@ -0,0 +1,148 @@
1
+ """Quota for an agy account, read the same way agy's /quota does (Cloud Code retrieveUserQuotaSummary)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import http.client
7
+ import json
8
+ import re
9
+ import shutil
10
+ import urllib.error
11
+ import urllib.parse
12
+ import urllib.request
13
+ from dataclasses import dataclass
14
+ from datetime import UTC, datetime, timedelta
15
+ from functools import lru_cache
16
+ from pathlib import Path
17
+
18
+ QUOTA_URL = "https://daily-cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary"
19
+ WINDOW_ORDER = {"5h": 0, "weekly": 1}
20
+ TOKEN_URL = "https://oauth2.googleapis.com/token"
21
+
22
+
23
+ class UsageError(Exception):
24
+ pass
25
+
26
+
27
+ @dataclass
28
+ class Pool:
29
+ group: str # model group sharing the quota, e.g. "Gemini", "Claude/GPT"
30
+ window: str # "5h" or "weekly"
31
+ used: float # 0..1
32
+ reset: datetime | None # None while the bucket is full: its reset keeps sliding
33
+
34
+
35
+ def _group_name(display: str) -> str:
36
+ # "Gemini Models" -> "Gemini", "Claude and GPT models" -> "Claude/GPT"
37
+ return re.sub(r"\s+models$", "", display, flags=re.I).replace(" and ", "/")
38
+
39
+
40
+ def claims(token: str | None) -> dict:
41
+ try:
42
+ payload = json.loads(token)["id_token"].split(".")[1]
43
+ return json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4)))
44
+ except (TypeError, KeyError, IndexError, ValueError):
45
+ return {}
46
+
47
+
48
+ @lru_cache(maxsize=1)
49
+ def _agy_client_secrets() -> tuple[str, ...]:
50
+ # agy is an installed-app OAuth client and ships its client secret inside the
51
+ # binary. Read it from there rather than copying Google's credential into this repo.
52
+ path = Path(shutil.which("agy") or Path.home() / ".local/bin/agy")
53
+ try:
54
+ data = path.read_bytes()
55
+ except OSError:
56
+ raise UsageError(f"agy binary not found at {path}; needed to refresh tokens") from None
57
+ return tuple(sorted({m.decode() for m in re.findall(rb"GOCSPX-[A-Za-z0-9_-]{28}", data)}))
58
+
59
+
60
+ def parse_time(s: str) -> datetime | None:
61
+ # Go writes nanoseconds; fromisoformat takes at most microseconds.
62
+ try:
63
+ return datetime.fromisoformat(re.sub(r"(\.\d{6})\d+", r"\1", s).replace("Z", "+00:00"))
64
+ except (TypeError, ValueError):
65
+ return None
66
+
67
+
68
+ def _post(url: str, data: bytes, headers: dict | None = None) -> dict:
69
+ # Cloud Code rejects the default Python-urllib agent with 403.
70
+ req = urllib.request.Request(url, data=data, headers={"User-Agent": "antigravity", **(headers or {})})
71
+ try:
72
+ with urllib.request.urlopen(req, timeout=20) as r:
73
+ return json.load(r)
74
+ except urllib.error.URLError:
75
+ raise # callers map HTTP and connect errors
76
+ except (OSError, http.client.HTTPException) as e:
77
+ # urlopen only wraps connect errors; a timeout or reset while reading comes through raw.
78
+ raise UsageError(f"network error: {type(e).__name__}") from None
79
+
80
+
81
+ def fresh_token(token: str) -> str:
82
+ """Return the token JSON with a usable access token, refreshing it if expired.
83
+
84
+ Google does not rotate the refresh token here, so the stored copy stays valid.
85
+ """
86
+ tok = json.loads(token)
87
+ now = datetime.now(UTC)
88
+ expiry = parse_time(tok["token"].get("expiry", ""))
89
+ if expiry and expiry > now + timedelta(minutes=2):
90
+ return token
91
+ client_id = claims(token).get("azp")
92
+ for secret in _agy_client_secrets():
93
+ form = urllib.parse.urlencode(
94
+ {
95
+ "client_id": client_id,
96
+ "client_secret": secret,
97
+ "refresh_token": tok["token"]["refresh_token"],
98
+ "grant_type": "refresh_token",
99
+ }
100
+ ).encode()
101
+ try:
102
+ r = _post(TOKEN_URL, form)
103
+ except urllib.error.HTTPError as e:
104
+ body = e.read()
105
+ if b"invalid_client" in body:
106
+ continue # the binary carries more than one client; try the next
107
+ if b"invalid_grant" in body:
108
+ raise UsageError("token revoked, sign in with agy again and `agyswap add`") from e
109
+ raise UsageError(f"token refresh failed (HTTP {e.code})") from e
110
+ except urllib.error.URLError as e:
111
+ raise UsageError(f"network error: {e.reason}") from e
112
+ tok["token"]["access_token"] = r["access_token"]
113
+ tok["token"]["expiry"] = (now + timedelta(seconds=r["expires_in"])).isoformat()
114
+ if "id_token" in r:
115
+ tok["id_token"] = r["id_token"]
116
+ return json.dumps(tok)
117
+ raise UsageError("no agy OAuth client secret accepted this token")
118
+
119
+
120
+ def fetch_pools(token: str) -> list[Pool]:
121
+ access = json.loads(token)["token"]["access_token"]
122
+ try:
123
+ data = _post(
124
+ QUOTA_URL,
125
+ b"{}",
126
+ {"Authorization": f"Bearer {access}", "Content-Type": "application/json"},
127
+ )
128
+ except urllib.error.HTTPError as e:
129
+ raise UsageError(f"quota request failed (HTTP {e.code})") from e
130
+ except urllib.error.URLError as e:
131
+ raise UsageError(f"network error: {e.reason}") from e
132
+ pools = []
133
+ for group in data.get("groups", []):
134
+ name = _group_name(group.get("displayName", "?"))
135
+ buckets = sorted(group.get("buckets", []), key=lambda b: WINDOW_ORDER.get(b.get("window"), 9))
136
+ for b in buckets:
137
+ frac = b.get("remainingFraction")
138
+ # An exhausted bucket has not been observed yet; treat a missing fraction as empty.
139
+ frac = frac if isinstance(frac, int | float) else 0.0
140
+ reset = None if frac >= 1 else parse_time(b.get("resetTime", ""))
141
+ pools.append(Pool(name, b.get("window", "?"), 1 - frac, reset))
142
+ return pools
143
+
144
+
145
+ def account_usage(token: str) -> tuple[list[Pool], str]:
146
+ """Pools for one account, plus the (possibly refreshed) token to store back."""
147
+ token = fresh_token(token)
148
+ return fetch_pools(token), token
@@ -0,0 +1,175 @@
1
+ Metadata-Version: 2.5
2
+ Name: agyswap-cli
3
+ Version: 0.1.0
4
+ Summary: Switch between multiple Antigravity CLI accounts, with a quota dashboard for every account
5
+ Project-URL: Homepage, https://github.com/rasvanjaya21/agyswap
6
+ Project-URL: Repository, https://github.com/rasvanjaya21/agyswap
7
+ Project-URL: Issues, https://github.com/rasvanjaya21/agyswap/issues
8
+ Author-email: rasvanjaya21 <rasvanjaya21@gmail.com>
9
+ License: MIT
10
+ License-File: LICENSE
11
+ Keywords: account-switcher,agy,antigravity,cli,gemini
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: POSIX :: Linux
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Topic :: Utilities
22
+ Requires-Python: >=3.12
23
+ Requires-Dist: rich>=15
24
+ Requires-Dist: textual<9,>=8.2.8
25
+ Description-Content-Type: text/markdown
26
+
27
+ <p align="center">
28
+ <a href="#"><img src=".github/assets/banner.webp" width="250"></a>
29
+ </p>
30
+
31
+ <p align="center">
32
+ <strong>Switch between multiple Antigravity CLI accounts, with a quota dashboard for every account.</strong>
33
+ </p>
34
+
35
+ <p align="center">
36
+ <a href="#"><img src="https://img.shields.io/badge/author-rasvanjaya21-white" alt="author-name"></a>
37
+ <a href="#"><img src="https://img.shields.io/badge/version-0.1.0-blue" alt="project-version"></a>
38
+ <a href="https://pypi.org/project/agyswap-cli/"><img src="https://img.shields.io/pypi/v/agyswap-cli?label=pip" alt="pypi-version"></a>
39
+ <a href="https://github.com/rasvanjaya21/agyswap/actions/workflows/ci.yml"><img src="https://github.com/rasvanjaya21/agyswap/actions/workflows/ci.yml/badge.svg" alt="build-status"></a>
40
+ </p>
41
+
42
+ ## Description
43
+
44
+ agyswap switches the Google account used by the Antigravity CLI (`agy`) without signing in again, and shows the quota left on every account. It does not work with the Antigravity IDE, Gemini CLI, or other Google AI products.
45
+
46
+ agy keeps its login in the OS keyring as a single OAuth token. agyswap stores a copy of each account's token, and switching writes another account's copy back to the keyring. The next `agy` you start runs as that account.
47
+
48
+ Inspired by [claude-swap](https://github.com/realiti4/claude-swap).
49
+
50
+ ## Status
51
+
52
+ **Usable on Linux.** Adding accounts, switching between them, the quota list, and the interactive dashboard all work, and switching between two real accounts without signing in again has been verified.
53
+
54
+ Not built yet: automatic switching when an account runs low, parallel sessions with different accounts, aliases, enable/disable, export/import, and macOS/Windows keyrings. `TODO.md` lists every open item.
55
+
56
+ ## Techstacks
57
+
58
+ Python 3.12+ managed with uv. The dashboard uses Textual and Rich; everything else is the standard library, plus `secret-tool` (libsecret) for the keyring.
59
+
60
+ ## Installation
61
+
62
+ ```bash
63
+ $ uv tool install agyswap-cli # or: pipx install agyswap-cli / pip install agyswap-cli
64
+ $ agyswap --help # the command is still agyswap
65
+ ```
66
+
67
+ Until the first release is on PyPI, install from GitHub instead:
68
+
69
+ ```bash
70
+ $ uv tool install git+https://github.com/rasvanjaya21/agyswap
71
+ ```
72
+
73
+ agyswap needs Linux with a Secret Service keyring (GNOME Keyring or KWallet) and `secret-tool` (`dnf install libsecret` or `apt install libsecret-tools`).
74
+
75
+ ## Configuration
76
+
77
+ | Variable | What it does |
78
+ | --- | --- |
79
+ | `AGYSWAP_HOME` | Where agyswap keeps its account store. Defaults to `~/.agyswap`. The store, `accounts.json`, holds refresh tokens and is written with mode `0600`. |
80
+
81
+ ## Usage
82
+
83
+ Unlike Claude Code, agy has no account picker. To add an account, sign out of agy, sign in with that account, then store it:
84
+
85
+ ```bash
86
+ $ agy # /logout, then sign in with account A, then exit
87
+ $ agyswap add
88
+ $ agy # /logout, then sign in with account B, then exit
89
+ $ agyswap add
90
+ ```
91
+
92
+ Signing out of agy does not revoke the token agyswap already stored.
93
+
94
+ Run `agyswap` on its own (or `agyswap tui`) for the dashboard. It shows every account's quota for both model groups (Gemini, and Claude/GPT), each with its 5-hour and weekly window and reset times, and marks the active account. Usage refreshes every 2 minutes.
95
+
96
+ | Key | Action |
97
+ | --- | --- |
98
+ | `enter` / `s` | Switch to the highlighted account |
99
+ | `a` | Add the account agy is signed in with |
100
+ | `d` | Remove the highlighted account |
101
+ | `r` | Refresh usage |
102
+ | `j` / `k` | Move |
103
+ | `q` | Quit |
104
+
105
+ The same actions are available as commands:
106
+
107
+ ```bash
108
+ $ agyswap switch # rotate to the next account
109
+ $ agyswap switch 2 # by slot
110
+ $ agyswap switch user@gmail.com # by email
111
+ $ agyswap list # quota of every account
112
+ $ agyswap status
113
+ $ agyswap remove 2 # asks first; add --yes (-y) in scripts
114
+ ```
115
+
116
+ Exit agy before you switch. A running agy reads the keyring only when it starts and saves its own token back every hour, which would undo the switch. `agyswap switch` refuses while agy is running; `--ignore-running` overrides that. `--force` switches without first copying the live login's token back into its slot.
117
+
118
+ ## Development
119
+
120
+ ```bash
121
+ $ git clone https://github.com/rasvanjaya21/agyswap && cd agyswap
122
+ $ uv sync # creates .venv with agyswap installed in editable mode
123
+ $ uv run agyswap
124
+ ```
125
+
126
+ For a manual run against your real agy login, use a throwaway store and shred it afterwards:
127
+
128
+ ```bash
129
+ $ export AGYSWAP_HOME=$(mktemp -d)
130
+ $ uv run agyswap add && uv run agyswap list
131
+ $ shred -u "$AGYSWAP_HOME/accounts.json"
132
+ ```
133
+
134
+ ## Testing
135
+
136
+ ```bash
137
+ $ uv run ruff format . # formatter
138
+ $ uv run ruff check . # linter
139
+ $ uv run pytest -q # tests
140
+ $ uv build # wheel and sdist into dist/
141
+ ```
142
+
143
+ Tests never touch the real keyring, the network, or `~/.agyswap/`. The keyring, the store, and every Google request are faked.
144
+
145
+ ## Deployment
146
+
147
+ Releases are published to PyPI by `.github/workflows/publish.yml` when a `v*` tag is pushed. The version lives only in `pyproject.toml`.
148
+
149
+ ```bash
150
+ $ uv version --bump patch
151
+ $ uv lock
152
+ $ git commit -am "chore: release v$(uv version --short)"
153
+ $ git push # wait for CI to pass
154
+ $ git tag "v$(uv version --short)" && git push origin "v$(uv version --short)"
155
+ ```
156
+
157
+ A published version cannot be replaced. To roll back, yank it on PyPI and release a patch. The one-time PyPI and GitHub setup is in `CONTRIBUTING.md`.
158
+
159
+ ## Architecture
160
+
161
+ Design decisions and the reasoning behind them live in `architecture/`, one file per workflow that produced it. `OBSERVE.md` maps how agy stores its login and reports quota, with the evidence for each fact; `SPEC.md` specifies the current version; `PLAN.md` lays out the next tasks; `REVIEW.md` holds the latest code review.
162
+
163
+ `AGENTS.md` holds the conventions and the development cycle, and is the single channel shared by every agent working here. `TODO.md` holds open findings and is deleted entry by entry as they are resolved.
164
+
165
+ ## Credit
166
+
167
+ - id: agyswap
168
+ - displayName: agyswap - Antigravity CLI Accounts Swap
169
+ - authorName: rasvanjaya21
170
+ - authorEmail: rasvanjaya21@gmail.com
171
+ - authorURL: https://github.com/rasvanjaya21
172
+
173
+ ## Member
174
+
175
+ - @rasvanjaya21 [assigned]
@@ -0,0 +1,10 @@
1
+ agyswap/__init__.py,sha256=c25PpJKLve8nNALgBZ-Fbw8ClYnzaF7MZzeGji3CL6c,163
2
+ agyswap/__main__.py,sha256=RPGbjy7lS51jzoJc3YgcEnjdiDiannE42MrFubh52Y4,59
3
+ agyswap/cli.py,sha256=_MgPJwz-0oVzI4ioJiye7wcSnWO34bT1o3OzPr0qKxI,13987
4
+ agyswap/tui.py,sha256=vjQHK4EjA7_C7vL0bxThTorfQxGYf02SZX-HgqQY5Mg,7152
5
+ agyswap/usage.py,sha256=kCRzHaleoT_9Gv9hShmyGMRRJCxeph_Vh8v1hRSu5wU,5824
6
+ agyswap_cli-0.1.0.dist-info/METADATA,sha256=6RXxvatKbpr7Sgq0UBp2zhtz7a97maldtOlqqhKJjz4,7317
7
+ agyswap_cli-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
8
+ agyswap_cli-0.1.0.dist-info/entry_points.txt,sha256=s0MjB6dQGB3a7To4_1qWAlHQ2CRiLIPLy-7IuJirDXo,45
9
+ agyswap_cli-0.1.0.dist-info/licenses/LICENSE,sha256=5NY_iM5mv3SftsUE_MFwmacUuPGH0rlOvtMdtZSxL4c,1069
10
+ agyswap_cli-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ agyswap = agyswap.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 rasvanjaya21
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.