gemini-usage-limits 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.
@@ -0,0 +1,3 @@
1
+ """gemini-usage: read your Antigravity plan rate-limit windows."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,8 @@
1
+ """Run gemini-usage with ``python -m gemini_usage``."""
2
+
3
+ import sys
4
+
5
+ from .cli import main
6
+
7
+ if __name__ == '__main__':
8
+ sys.exit(main())
gemini_usage/api.py ADDED
@@ -0,0 +1,194 @@
1
+ """Fetch Antigravity quota via the endpoint, agy, or the saved endpoint answer."""
2
+
3
+ import http.client
4
+ import json
5
+ import os
6
+ import platform
7
+ import re
8
+ import shutil
9
+ import subprocess
10
+ import sys
11
+ import tempfile
12
+ import time
13
+ import urllib.error
14
+ import urllib.request
15
+ from pathlib import Path
16
+
17
+ from .auth import LOGIN_HELP, resolve_credentials
18
+ from .report import parse_tsv, quota_text, shape
19
+
20
+ URL = 'https://daily-cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary'
21
+ PLAN_URL = 'https://daily-cloudcode-pa.googleapis.com/v1internal:loadCodeAssist'
22
+ DEFAULT_AGY_VERSION = '1.5.17'
23
+ FRESH = 300
24
+ MAX_AGE = 3600
25
+
26
+
27
+ def config_dir():
28
+ return Path(os.environ.get('GEMINI_USAGE_HOME') or Path.home() / '.gemini-usage')
29
+
30
+
31
+ def write_cache(path, data):
32
+ """Atomically replace the cache with a complete quota payload."""
33
+ path.parent.mkdir(parents=True, exist_ok=True)
34
+ tmp = tempfile.NamedTemporaryFile(mode='w', encoding='utf-8', dir=path.parent,
35
+ prefix=path.name + '.', suffix='.tmp', delete=False)
36
+ try:
37
+ with tmp:
38
+ json.dump(data, tmp)
39
+ os.replace(tmp.name, path)
40
+ finally:
41
+ Path(tmp.name).unlink(missing_ok=True)
42
+
43
+
44
+ def from_last(path, max_age):
45
+ try:
46
+ with path.open(encoding='utf-8') as stream:
47
+ age = max(0, time.time() - os.fstat(stream.fileno()).st_mtime)
48
+ if age >= max_age:
49
+ raise RuntimeError(f'last endpoint answer is {int(age // 60)} min old')
50
+ data = json.load(stream)
51
+ source = f'endpoint, {int(age // 60)} min ago' if age >= 60 else 'endpoint'
52
+ return shape(data, source)
53
+ except FileNotFoundError:
54
+ raise RuntimeError('no saved endpoint answer yet') from None
55
+ except (OSError, ValueError, RecursionError):
56
+ raise RuntimeError('could not read the saved endpoint answer') from None
57
+
58
+
59
+ def _agy_command():
60
+ return shutil.which('agy') or shutil.which(str(Path.home() / '.local/bin/agy')) or 'agy'
61
+
62
+
63
+ def _agy_version():
64
+ try:
65
+ out = subprocess.run([_agy_command(), '--version'], stdin=subprocess.DEVNULL,
66
+ capture_output=True, text=True, timeout=5)
67
+ version = out.stdout.strip()
68
+ if out.returncode == 0 and version != '0.0.0' and re.fullmatch(r'[0-9]+\.[0-9]+\.[0-9]+', version):
69
+ return version
70
+ except (OSError, ValueError, subprocess.SubprocessError):
71
+ pass
72
+ return DEFAULT_AGY_VERSION
73
+
74
+
75
+ def _headers(verbose):
76
+ os_name = {'darwin': 'darwin', 'linux': 'linux', 'win32': 'windows'}.get(sys.platform)
77
+ arch = {'aarch64': 'arm64', 'arm64': 'arm64', 'x86_64': 'amd64', 'amd64': 'amd64'}.get(
78
+ platform.machine().lower())
79
+ if os_name is None or arch is None:
80
+ raise RuntimeError('this platform has no supported Antigravity User-Agent')
81
+ token = resolve_credentials(verbose=verbose)
82
+ return {
83
+ 'Authorization': 'Bearer ' + token,
84
+ 'Content-Type': 'application/json',
85
+ 'User-Agent': f'antigravity/cli/{_agy_version()} ({os_name}/{arch})',
86
+ }
87
+
88
+
89
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
90
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
91
+ # Keep the bearer token on the original request.
92
+ return None
93
+
94
+
95
+ def _post_json(url, body, headers, timeout):
96
+ request = urllib.request.Request(url, data=json.dumps(body).encode('utf-8'),
97
+ headers=headers, method='POST')
98
+ opener = urllib.request.build_opener(_NoRedirect())
99
+ with opener.open(request, timeout=timeout) as response:
100
+ return json.load(response)
101
+
102
+
103
+ def _request(url, body, headers):
104
+ name = 'Antigravity quota endpoint' if url == URL else 'Antigravity plan endpoint'
105
+ try:
106
+ return _post_json(url, body, headers, 15)
107
+ except urllib.error.HTTPError as exc:
108
+ reason = {401: ' (access token rejected)', 403: ' (sign-in or license required)'}.get(exc.code, '')
109
+ raise RuntimeError(f'HTTP {exc.code} from the {name}{reason}') from None
110
+ except (OSError, http.client.HTTPException):
111
+ raise RuntimeError(f'could not reach the {name}') from None
112
+ except (ValueError, TypeError, RecursionError):
113
+ raise RuntimeError(f'invalid request or JSON response from the {name}') from None
114
+
115
+
116
+ def from_agy():
117
+ """Run the official client once and use its TSV answer."""
118
+ try:
119
+ command = [_agy_command(), '-p', '/usage', '--print-timeout', '60s']
120
+ with tempfile.TemporaryDirectory(prefix='gemini-usage-') as directory:
121
+ out = subprocess.run(command, stdin=subprocess.DEVNULL, cwd=directory,
122
+ capture_output=True, text=True, timeout=90)
123
+ except FileNotFoundError:
124
+ raise RuntimeError('Antigravity CLI (`agy`) was not found') from None
125
+ except subprocess.TimeoutExpired:
126
+ raise RuntimeError('Antigravity CLI usage request timed out') from None
127
+ except (OSError, ValueError, subprocess.SubprocessError):
128
+ raise RuntimeError('could not run the Antigravity CLI') from None
129
+ if out.returncode != 0:
130
+ raise RuntimeError('Antigravity CLI usage request failed')
131
+ try:
132
+ return shape(parse_tsv(out.stdout), 'agy CLI')
133
+ except ValueError:
134
+ raise RuntimeError('Antigravity CLI did not return usable quota rows') from None
135
+
136
+
137
+ def load_plan(headers=None, verbose=False):
138
+ """Fetch the tier name, keeping the rest of the response out of the report."""
139
+ try:
140
+ if headers is None:
141
+ headers = _headers(verbose)
142
+ data = _request(PLAN_URL, {'metadata': {'ideType': 'ANTIGRAVITY'}}, headers)
143
+ except RuntimeError as exc:
144
+ if verbose:
145
+ print(f'plan unavailable: {exc}', file=sys.stderr)
146
+ return None
147
+ if isinstance(data, dict):
148
+ for key in ('paidTier', 'currentTier'):
149
+ tier = data.get(key)
150
+ if isinstance(tier, dict):
151
+ name = quota_text(tier.get('name'), headers['Authorization'][len('Bearer '):])
152
+ if name:
153
+ return name
154
+ return None
155
+
156
+
157
+ def usage(config=None, verbose=False, include_plan=False):
158
+ """Return the first available source and look up the plan when requested."""
159
+ path = (config_dir() if config is None else Path(config)) / 'last-usage.json'
160
+ headers = None
161
+
162
+ def live():
163
+ nonlocal headers
164
+ request_headers = _headers(verbose)
165
+ data = _request(URL, {}, request_headers)
166
+ out = shape(data, 'endpoint', request_headers['Authorization'][len('Bearer '):])
167
+ headers = request_headers
168
+ try:
169
+ write_cache(path, out['raw'])
170
+ except OSError:
171
+ if verbose:
172
+ print('cache: could not save the endpoint answer', file=sys.stderr)
173
+ return out
174
+
175
+ reasons = []
176
+ sources = (('cache', lambda: from_last(path, FRESH)),
177
+ ('endpoint', live),
178
+ ('agy CLI', from_agy),
179
+ ('cache', lambda: from_last(path, MAX_AGE)))
180
+ for name, source in sources:
181
+ try:
182
+ out = source()
183
+ except (RuntimeError, ValueError) as exc:
184
+ if verbose and name != 'cache':
185
+ print(f'usage: {name}: {exc}', file=sys.stderr)
186
+ if str(exc) not in reasons:
187
+ reasons.append(str(exc))
188
+ else:
189
+ if verbose:
190
+ print('usage: ' + out['source'], file=sys.stderr)
191
+ if include_plan:
192
+ out['plan'] = load_plan(headers, verbose=verbose)
193
+ return out
194
+ raise RuntimeError('. '.join([*reasons, LOGIN_HELP]))
gemini_usage/auth.py ADDED
@@ -0,0 +1,56 @@
1
+ """Read Antigravity's Google OAuth access token from the system keyring."""
2
+
3
+ import base64
4
+ import json
5
+ import subprocess
6
+ import sys
7
+ import time
8
+
9
+ from .report import timestamp
10
+
11
+ KEYRING_PREFIX = "go-keyring-base64:"
12
+ LOGIN_HELP = "run `agy` once to sign in with Google"
13
+
14
+
15
+ class CredentialsNotFound(RuntimeError):
16
+ """Raised when no usable Antigravity access token can be located."""
17
+
18
+
19
+ def parse_credentials(secret):
20
+ """Extract a bearer token with more than 60 seconds left."""
21
+ try:
22
+ secret = secret.strip()
23
+ if secret.startswith(KEYRING_PREFIX):
24
+ secret = base64.b64decode(secret[len(KEYRING_PREFIX):], validate=True)
25
+ token = json.loads(secret)['token']
26
+ access_token = token['access_token']
27
+ expiry = timestamp(token['expiry']).timestamp()
28
+ if not isinstance(access_token, str) or not access_token or access_token.isspace():
29
+ raise ValueError
30
+ except (ValueError, TypeError, KeyError, AttributeError, OverflowError, RecursionError):
31
+ raise CredentialsNotFound('could not read Antigravity credentials') from None
32
+ if expiry <= time.time() + 60:
33
+ raise CredentialsNotFound('the Antigravity access token has expired or is about to expire')
34
+ return access_token
35
+
36
+
37
+ def resolve_credentials(verbose=False):
38
+ """Return the access token from Keychain or Secret Service."""
39
+ if sys.platform == 'darwin':
40
+ source = 'keychain'
41
+ command = ['security', 'find-generic-password', '-s', 'gemini', '-a', 'antigravity', '-w']
42
+ elif sys.platform == 'linux':
43
+ source = 'secret-tool'
44
+ command = ['secret-tool', 'lookup', 'service', 'gemini', 'username', 'antigravity']
45
+ else:
46
+ raise CredentialsNotFound('direct keyring access is unavailable on this platform')
47
+ try:
48
+ out = subprocess.run(command, stdin=subprocess.DEVNULL,
49
+ capture_output=True, text=True, timeout=15)
50
+ except (OSError, ValueError, subprocess.SubprocessError):
51
+ raise CredentialsNotFound(f'could not read Antigravity credentials from {source}') from None
52
+ if out.returncode != 0:
53
+ raise CredentialsNotFound(f'no Antigravity credentials found in {source}')
54
+ if verbose:
55
+ print('credentials: ' + source, file=sys.stderr)
56
+ return parse_credentials(out.stdout)
gemini_usage/cli.py ADDED
@@ -0,0 +1,62 @@
1
+ """Command-line entry point for gemini-usage."""
2
+
3
+ import argparse
4
+ import json
5
+ import sys
6
+
7
+ from . import __version__
8
+ from .api import usage
9
+ from .report import render_limits, render_plain, render_short, warning_reached
10
+
11
+
12
+ def build_parser():
13
+ p = argparse.ArgumentParser(
14
+ prog='gemini-usage',
15
+ description='Show Antigravity plan usage for the 5-hour and weekly windows.',
16
+ )
17
+ p.add_argument('--json', action='store_const', dest='format', const='json',
18
+ help='print the raw quota summary JSON (alias for --format json)')
19
+ p.add_argument('--warn', type=int, nargs='?', const=70, metavar='N',
20
+ help='exit 1 when any usage window is at or above N%% (default 70)')
21
+ p.add_argument('--warn-7d', type=int, nargs='?', const=70, metavar='N',
22
+ help='exit 1 when the Gemini 7-day window is at or above N%% (default 70)')
23
+ p.add_argument('--all', action='store_true',
24
+ help='add group descriptions and the plan (plain format)')
25
+ p.add_argument('--format', choices=('plain', 'json', 'short'),
26
+ help='output format (default: plain)')
27
+ p.add_argument('-v', '--verbose', action='store_true',
28
+ help='log credential and usage sources and the plan to stderr')
29
+ p.add_argument('-V', '--version', action='version', version='gemini-usage %s' % __version__)
30
+ p.set_defaults(format='plain')
31
+ return p
32
+
33
+
34
+ def main(argv=None):
35
+ args = build_parser().parse_args(argv)
36
+ try:
37
+ out = usage(verbose=args.verbose, include_plan=args.verbose or (args.all and args.format == 'plain'))
38
+ except RuntimeError as exc:
39
+ print('gemini-usage: ' + str(exc), file=sys.stderr)
40
+ return 1
41
+ if args.verbose and out.get('plan'):
42
+ print('plan: ' + out['plan'], file=sys.stderr)
43
+ if args.format == 'json':
44
+ json.dump(out['raw'], sys.stdout, indent=1)
45
+ print()
46
+ elif args.format == 'short':
47
+ print(render_short(out))
48
+ else:
49
+ print(render_plain(out))
50
+ if args.all:
51
+ details = render_limits(out)
52
+ if details:
53
+ print(details)
54
+ if args.warn is not None and warning_reached(out, args.warn):
55
+ return 1
56
+ if args.warn_7d is not None and warning_reached(out, args.warn_7d, weekly_only=True):
57
+ return 1
58
+ return 0
59
+
60
+
61
+ if __name__ == '__main__':
62
+ sys.exit(main())
gemini_usage/report.py ADDED
@@ -0,0 +1,179 @@
1
+ """Normalize and render Antigravity quota payloads from the API or agy."""
2
+
3
+ import re
4
+ from datetime import datetime
5
+ from decimal import Decimal
6
+
7
+ GEMINI = 'Gemini Models'
8
+ THIRD_PARTY = 'Claude and GPT models'
9
+ GROUP_LABELS = {GEMINI: 'Gemini', THIRD_PARTY: 'Claude/GPT'}
10
+ WINDOW_LABELS = {'5h': '5-hour', 'weekly': '7-day'}
11
+ TSV_WINDOWS = {'Five Hour Limit Remaining': '5h', 'Weekly Limit Remaining': 'weekly'}
12
+ NO_RESET = '1970-01-01T00:00:00Z'
13
+
14
+
15
+ def timestamp(iso):
16
+ # Python 3.9 accepts only three or six fractional digits.
17
+ iso = re.sub(r'\.(\d+)', lambda match: '.' + match[1][:6].ljust(6, '0'), iso, count=1)
18
+ stamp = datetime.fromisoformat(iso.replace('Z', '+00:00'))
19
+ if stamp.tzinfo is None:
20
+ raise ValueError('missing time zone')
21
+ return stamp
22
+
23
+
24
+ def quota_text(value, token=None):
25
+ """Keep display text clear of credentials, email addresses, and terminal controls."""
26
+ if (isinstance(value, str) and value and value.isprintable()
27
+ and '@' not in value and '%40' not in value and (not token or token not in value)):
28
+ return value
29
+ return None
30
+
31
+
32
+ def _text_fields(data, keys, token):
33
+ return {key: value for key in keys if (value := quota_text(data.get(key), token)) is not None}
34
+
35
+
36
+ def _remaining_fraction(value):
37
+ return type(value) in (int, float) and 0 <= value <= 1
38
+
39
+
40
+ def _buckets(data, token):
41
+ if not isinstance(data, list):
42
+ return []
43
+ buckets = []
44
+ for bucket in data:
45
+ if not isinstance(bucket, dict):
46
+ continue
47
+ raw = _text_fields(bucket, ('bucketId', 'displayName', 'window', 'resetTime', 'description'), token)
48
+ if type(bucket.get('disabled')) is bool:
49
+ raw['disabled'] = bucket['disabled']
50
+ if 'remainingFraction' in bucket:
51
+ fraction = bucket['remainingFraction']
52
+ # Keep nulls in JSON and ignore malformed non-null readings.
53
+ if fraction is not None and not _remaining_fraction(fraction):
54
+ continue
55
+ raw['remainingFraction'] = fraction
56
+ buckets.append(raw)
57
+ return buckets
58
+
59
+
60
+ def _quota_payload(data, token):
61
+ if not isinstance(data, dict):
62
+ raise ValueError('quota summary is not a JSON object')
63
+ raw = _text_fields(data, ('description',), token)
64
+ if isinstance(data.get('groups'), list):
65
+ raw['groups'] = []
66
+ for group in data['groups']:
67
+ if isinstance(group, dict):
68
+ clean = _text_fields(group, ('displayName', 'description'), token)
69
+ clean['buckets'] = _buckets(group.get('buckets'), token)
70
+ raw['groups'].append(clean)
71
+ if isinstance(data.get('buckets'), list):
72
+ raw['buckets'] = _buckets(data['buckets'], token)
73
+ return raw
74
+
75
+
76
+ def _windows(group):
77
+ for window, label in WINDOW_LABELS.items():
78
+ for bucket in group['buckets']:
79
+ if bucket.get('window') != window:
80
+ continue
81
+ fraction = bucket.get('remainingFraction')
82
+ if fraction is None:
83
+ fraction = 0 if bucket.get('disabled') else 1
84
+ used = float((1 - Decimal(str(fraction))) * 100)
85
+ reset = bucket.get('resetTime')
86
+ yield {'name': group['name'], 'window': window, 'label': label,
87
+ 'short': '7d' if window == 'weekly' else window,
88
+ 'utilization': used, 'resets_at': None if reset == NO_RESET else reset}
89
+
90
+
91
+ def shape(data, source, token=None):
92
+ """Normalize usage windows and retain the quota-only summary for JSON output."""
93
+ raw = _quota_payload(data, token)
94
+ groups = [dict(group, name=group.get('displayName', 'other')) for group in raw.get('groups', [])]
95
+ if raw.get('buckets'):
96
+ groups.append({'name': 'other', 'buckets': raw['buckets']})
97
+ order = {GEMINI: 0, THIRD_PARTY: 1}
98
+ groups.sort(key=lambda group: order.get(group['name'], 2))
99
+ windows = [window for group in groups for window in _windows(group)]
100
+ if not windows:
101
+ raise ValueError('quota summary has no supported usage windows')
102
+ return {'source': source, 'raw': raw, 'windows': windows, 'groups': groups}
103
+
104
+
105
+ def parse_tsv(text):
106
+ """Convert agy's percentage-remaining rows to a quota summary."""
107
+ groups = {}
108
+ for line in text.splitlines():
109
+ fields = line.split('\t')
110
+ if len(fields) != 4:
111
+ continue
112
+ name, label, remaining, reset = (part.strip() for part in fields)
113
+ window = TSV_WINDOWS.get(label)
114
+ match = re.fullmatch(r'([0-9]{1,3})%', remaining)
115
+ if not quota_text(name) or not window or not match or int(match[1]) > 100:
116
+ continue
117
+ bucket = {'displayName': label, 'window': window, 'remainingFraction': int(match[1]) / 100}
118
+ if reset and reset != NO_RESET:
119
+ try:
120
+ timestamp(reset)
121
+ except ValueError:
122
+ pass
123
+ else:
124
+ bucket['resetTime'] = reset
125
+ groups.setdefault(name, []).append(bucket)
126
+ return {'groups': [{'displayName': name, 'buckets': buckets} for name, buckets in groups.items()]}
127
+
128
+
129
+ def warning_reached(usage, threshold, weekly_only=False):
130
+ """Check all windows, or only the Gemini seven-day window."""
131
+ return any(window['utilization'] >= threshold for window in usage['windows']
132
+ if not weekly_only or (window['name'] == GEMINI and window['window'] == 'weekly'))
133
+
134
+
135
+ def when(iso):
136
+ if not iso:
137
+ return ''
138
+ try:
139
+ local = timestamp(iso).astimezone()
140
+ except (ValueError, OverflowError, OSError):
141
+ return ''
142
+ now = datetime.now().astimezone()
143
+ mins = max(0, int((local - now).total_seconds() // 60))
144
+ h, m = divmod(mins, 60)
145
+ span = f'{h}h{m:02d}m' if h else f'{m}m'
146
+ day = '' if local.date() == now.date() else local.strftime('%a ')
147
+ return f'resets {day}{local:%H:%M} (in {span})'
148
+
149
+
150
+ def pct(window):
151
+ return f"{window['utilization']:.0f}%"
152
+
153
+
154
+ def render_plain(usage):
155
+ out = []
156
+ for window in usage['windows']:
157
+ name = GROUP_LABELS.get(window['name'], window['name'])
158
+ line = f"{name} {window['label']}: {pct(window)} used"
159
+ reset = when(window['resets_at'])
160
+ out.append(line + ', ' + reset if reset else line)
161
+ if usage['source'] != 'endpoint':
162
+ out.append(f"(from the {usage['source']})")
163
+ return '\n'.join(out)
164
+
165
+
166
+ def render_short(usage):
167
+ return ' ยท '.join(
168
+ f"{GROUP_LABELS.get(window['name'], window['name'])} {window['short']} {pct(window)}"
169
+ for window in usage['windows']
170
+ )
171
+
172
+
173
+ def render_limits(usage):
174
+ """Render the group descriptions and plan when the source provides them."""
175
+ lines = [f"{GROUP_LABELS.get(group['name'], group['name'])}: {group['description']}"
176
+ for group in usage['groups'] if group.get('description')]
177
+ if usage.get('plan'):
178
+ lines.append(f"plan {usage['plan']}")
179
+ return '\n'.join(lines)
@@ -0,0 +1,231 @@
1
+ Metadata-Version: 2.4
2
+ Name: gemini-usage-limits
3
+ Version: 0.1.0
4
+ Summary: CLI for Antigravity plan usage and rate limits, with Antigravity CLI fallback and warning thresholds.
5
+ Author: gemini-usage contributors
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/javaisbetterthanpython/gemini-usage
8
+ Project-URL: Issues, https://github.com/javaisbetterthanpython/gemini-usage/issues
9
+ Keywords: gemini,google,antigravity,usage,rate-limit,weekly-usage,subscription,cli
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Utilities
16
+ Requires-Python: >=3.9
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Dynamic: license-file
20
+
21
+ <h1 align="center">๐Ÿ“Š gemini-usage</h1>
22
+
23
+ <p align="center">
24
+ <b>Your Antigravity plan limits โ€” right from your terminal.</b>
25
+ </p>
26
+
27
+ <p align="center">
28
+ <a href="https://pypi.org/project/gemini-usage-limits/"><img alt="PyPI" src="https://img.shields.io/pypi/v/gemini-usage-limits?color=blue&label=PyPI"></a>
29
+ <img alt="Python" src="https://img.shields.io/badge/python-3.9%2B-blue">
30
+ <img alt="Platforms" src="https://img.shields.io/badge/platform-macOS%20%7C%20Linux%20%7C%20Windows-lightgrey">
31
+ <img alt="Dependencies" src="https://img.shields.io/badge/dependencies-zero-brightgreen">
32
+ <img alt="License" src="https://img.shields.io/badge/license-MIT-green">
33
+ </p>
34
+
35
+ <p align="center">
36
+ <img src="https://raw.githubusercontent.com/javaisbetterthanpython/gemini-usage/main/docs/demo.gif" alt="gemini-usage demo" width="760">
37
+ </p>
38
+
39
+ ---
40
+
41
+ Antigravity shows your plan limits with its `/usage` command.
42
+ **`gemini-usage` gives you plan usage from the shell**, for scripts, hooks, and
43
+ AI agents deciding when to back off. It uses the Antigravity login already on
44
+ your machine.
45
+
46
+ The 5-hour and weekly windows cover Gemini models and Claude/GPT models in
47
+ separate groups.
48
+
49
+ **Install `gemini-usage-limits` from PyPI for the `gemini-usage` command.**
50
+
51
+ ```text
52
+ $ gemini-usage
53
+ Gemini 5-hour: 1% used, resets 21:18 (in 4h44m)
54
+ Gemini 7-day: 18% used, resets Tue 19:33 (in 146h58m)
55
+ Claude/GPT 5-hour: 0% used
56
+ Claude/GPT 7-day: 0% used
57
+ ```
58
+
59
+ ## โœจ Features
60
+
61
+ - **โฑ๏ธ Usage windows** with 5-hour and weekly percentages and local reset times for each group.
62
+ - **๐Ÿšฆ Thresholds for scripts** with `--warn [N]` for any window and `--warn-7d [N]` for the Gemini weekly window. Both exit 1 at or above N%.
63
+ - **๐Ÿ“Š Extra detail** with model group descriptions and the plan when available through `--all`.
64
+ - **๐Ÿ“œ Antigravity CLI fallback** through `agy -p /usage` when the direct endpoint path fails.
65
+ - **๐Ÿงพ Plain, JSON, or short** output for terminals and scripts.
66
+ - **๐ŸŒ Cross-platform** with keyring access on macOS and Linux and CLI fallback on Windows.
67
+ - **๐Ÿ”‹ Zero dependencies** beyond the Python 3.9+ standard library.
68
+ - **๐Ÿ”’ Local & private** with existing login credentials sent only to Google's Antigravity endpoint.
69
+
70
+ ## ๐Ÿš€ Quickstart
71
+
72
+ Install Antigravity and run `agy` once to sign in with Google.
73
+
74
+ ```bash
75
+ curl -fsSL https://antigravity.google/cli/install.sh | bash
76
+ agy
77
+ ```
78
+
79
+ After signing in, install and run the usage CLI.
80
+
81
+ ```bash
82
+ pip install gemini-usage-limits
83
+ gemini-usage
84
+ ```
85
+
86
+ ## ๐Ÿง‘โ€๐Ÿ’ป Usage
87
+
88
+ | Command | What it does |
89
+ |---|---|
90
+ | `gemini-usage` | Available usage windows and their reset times |
91
+ | `gemini-usage --json` | Raw quota-only JSON (alias for `--format json`) |
92
+ | `gemini-usage --warn [N]` | Exit 1 when any usage window reaches N% (default 70) |
93
+ | `gemini-usage --warn-7d [N]` | Exit 1 at or above N% of the Gemini 7-day window (default 70) |
94
+ | `gemini-usage --all` | Add group descriptions and the plan in plain format |
95
+ | `gemini-usage --format {plain,json,short}` | Choose output format (default plain) |
96
+ | `gemini-usage -v`, `--verbose` | Print credential and usage sources and the plan, when available, to stderr |
97
+ | `gemini-usage -V`, `--version` | Print the version |
98
+ | `gemini-usage -h`, `--help` | Show help |
99
+
100
+ Flags combine as in `gemini-usage --format short --warn 70 --warn-7d 90`.
101
+ The last of `--json` and `--format` wins. `--all` adds detail in plain format.
102
+ Group descriptions come from the quota endpoint and the plan comes from a
103
+ separate lookup.
104
+
105
+ <details>
106
+ <summary><b>๐Ÿ“Š Example ยท <code>--all</code></b></summary>
107
+
108
+ ```text
109
+ Gemini 5-hour: 1% used, resets 21:18 (in 4h44m)
110
+ Gemini 7-day: 18% used, resets Tue 19:33 (in 146h58m)
111
+ Claude/GPT 5-hour: 0% used
112
+ Claude/GPT 7-day: 0% used
113
+ Gemini: Models within this group: Gemini 4 Neon, Gemini 4 Carbon, Gemini 4 Argon, Gemini 4 Hydrogen, Gemini 3.8 Flash
114
+ Claude/GPT: Models within this group: Claude Opus 5.5, Claude Sonnet 5.5, GPT-OSS 120B
115
+ plan Google AI Pro
116
+ ```
117
+
118
+ </details>
119
+
120
+ ## ๐Ÿค– Using it from scripts and agents
121
+
122
+ ```bash
123
+ gemini-usage --warn 70 || echo "back off"
124
+ gemini-usage --warn 70 --warn-7d 90 --format short
125
+ gemini-usage --json
126
+ ```
127
+
128
+ The usual output is printed even when a threshold trips. Exit code **0** means
129
+ success, **1** means a threshold tripped or no source answered, and **2** means
130
+ an argument error. Both warning thresholds are inclusive and compare the
131
+ source percentage before rounding for display. `--warn` includes all reported
132
+ windows, and `--warn-7d` checks the Gemini weekly window when present.
133
+
134
+ ## ๐Ÿ“œ Antigravity CLI fallback
135
+
136
+ The direct request needs a current access token. When it is expired or the
137
+ endpoint path fails, the CLI runs `agy -p /usage --print-timeout 60s` once in a
138
+ temporary directory. Antigravity refreshes its own credential as needed. The
139
+ fallback uses whole percentages from its tab-separated output.
140
+
141
+ ```text
142
+ $ gemini-usage
143
+ Gemini 5-hour: 1% used, resets 21:18 (in 4h44m)
144
+ Gemini 7-day: 18% used, resets Tue 19:33 (in 146h58m)
145
+ Claude/GPT 5-hour: 0% used
146
+ Claude/GPT 7-day: 0% used
147
+ (from the agy CLI)
148
+ ```
149
+
150
+ With `--format short`, each group and window fits on one line.
151
+
152
+ ```text
153
+ Gemini 5h 1% ยท Gemini 7d 18% ยท Claude/GPT 5h 0% ยท Claude/GPT 7d 0%
154
+ ```
155
+
156
+ ## ๐Ÿค” How it works
157
+
158
+ Sources are tried in this order.
159
+
160
+ 1. `last-usage.json` if less than **5 minutes** old.
161
+ 2. One live `POST https://daily-cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary`, saved on success.
162
+ 3. One Antigravity `/usage` run.
163
+ 4. `last-usage.json` if less than **60 minutes** old.
164
+
165
+ The quota cache lives in `~/.gemini-usage`, or `GEMINI_USAGE_HOME` when set.
166
+ Cache writes are atomic. Cached answers at least a minute old show their source
167
+ and age, for example `(from the endpoint, 3 min ago)`. If all sources fail, the
168
+ distinct reasons appear on stderr with a sign-in hint.
169
+
170
+ The direct quota request has a 15-second timeout. `-v` and plain `--all` can
171
+ make one additional request for the plan using the available Antigravity login.
172
+
173
+ <details>
174
+ <summary><b>๐Ÿ” Where credentials live (per OS)</b></summary>
175
+
176
+ | OS | Credential source |
177
+ |---|---|
178
+ | macOS | Antigravity's system Keychain entry |
179
+ | Linux | Antigravity's Secret Service entry through `secret-tool`, when available |
180
+ | Windows | The signed-in Antigravity CLI via the fallback |
181
+
182
+ For the protocol and a recipe to rebuild the tool, see
183
+ **[docs/HOW_THIS_WAS_BUILT.md](docs/HOW_THIS_WAS_BUILT.md)**.
184
+ </details>
185
+
186
+ ## ๐Ÿ”’ Privacy & security
187
+
188
+ - Reads the existing Antigravity login. Antigravity handles token refresh.
189
+ - Sends the access token only to **`daily-cloudcode-pa.googleapis.com`** in direct requests.
190
+ - Keeps only quota fields in the cache and JSON output. The plan lookup extracts the tier name for display.
191
+ - Keeps tokens, request headers, and email addresses out of errors and verbose output.
192
+ - **No telemetry or third-party calls from this CLI.**
193
+
194
+ ## โš ๏ธ Good to know
195
+
196
+ - The quota endpoint is **undocumented** and its format may change.
197
+ - Both sources need a signed-in Antigravity CLI and an eligible account.
198
+ - The direct request uses Antigravity's versioned User-Agent to receive the Gemini group.
199
+ - An unused window can have no reset time. The CLI omits the reset clause for it.
200
+
201
+ ## ๐Ÿ› ๏ธ Install options
202
+
203
+ ```bash
204
+ pip install gemini-usage-limits # from PyPI
205
+ pipx install gemini-usage-limits # isolated command installation
206
+ pip install . # from a local clone
207
+ ```
208
+
209
+ Requires Python 3.9+. **The PyPI distribution is `gemini-usage-limits`. The command
210
+ and GitHub repo are `gemini-usage`, and the import package is `gemini_usage`.**
211
+
212
+ ## ๐Ÿค Contributing
213
+
214
+ Issues and PRs are welcome. After installing the local project with `pip install -e .`,
215
+ run the tests with the following command.
216
+
217
+ ```bash
218
+ pip install pytest && pytest -q
219
+ ```
220
+
221
+ Tests use temporary directories and mocked HTTP and subprocesses. They never
222
+ contact the endpoint or read real credentials.
223
+
224
+ Regenerate the demo with `python3 docs/record_demo.py` after installing
225
+ [agg](https://github.com/asciinema/agg/releases) and the DejaVu Sans Mono font.
226
+ The recorder uses illustrative quota data with HTTP and credential access
227
+ disabled. The README embeds the resulting `docs/demo.gif`.
228
+
229
+ ## ๐Ÿ“„ License
230
+
231
+ [MIT](LICENSE) โ€” do whatever you like.
@@ -0,0 +1,12 @@
1
+ gemini_usage/__init__.py,sha256=sSzlWIDTDQznBdVHnjtGDco71Y7ka1_vcelzM0lwJ7w,90
2
+ gemini_usage/__main__.py,sha256=pZLe9xO-p6o1ky8xdpGAPmS8eYCjzGVWMpZA-HFZc2c,140
3
+ gemini_usage/api.py,sha256=pmvd01W_S2SlxB_CFBoTM62Sv55FA22pYxgVX136MxI,7575
4
+ gemini_usage/auth.py,sha256=PnHsNZcBTLGJZf2M_4vs9YY5RxGFVUfOyGxdTOIGdFI,2316
5
+ gemini_usage/cli.py,sha256=Nbp-6tY_N0sIcvtUxEfl3u6RVxO7JYVnN3OJBv6MfLs,2398
6
+ gemini_usage/report.py,sha256=mLf783-IZnLoqq11DdDuzYy-hdxEwfhpssmQu_YHF_k,6887
7
+ gemini_usage_limits-0.1.0.dist-info/licenses/LICENSE,sha256=nqji0kYa7RcFIRInO_hd9JnjQ-Rhb7UiJJCM7YXgfIw,1082
8
+ gemini_usage_limits-0.1.0.dist-info/METADATA,sha256=aFOahRKkxWPW-KjwKvUgzUMEdNh_IDrkzzjhKJ984aw,9074
9
+ gemini_usage_limits-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
10
+ gemini_usage_limits-0.1.0.dist-info/entry_points.txt,sha256=ROYF7Nzl3fawu9XFQRB2juy7BWHY9XDbfgkKSTMBEl4,55
11
+ gemini_usage_limits-0.1.0.dist-info/top_level.txt,sha256=X6BPYdugOPJpteVbEaNv6XLs3gfXTrEAcYzZetvukU0,13
12
+ gemini_usage_limits-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ gemini-usage = gemini_usage.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 gemini-usage contributors
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.
@@ -0,0 +1 @@
1
+ gemini_usage