@thedevdavid/sage 0.2.0 → 0.3.0

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.
package/README.md CHANGED
@@ -3,10 +3,11 @@
3
3
  Know your LLM usage at a glance. Nothing else.
4
4
 
5
5
  sage is a tiny, open-source, **local-only** toolkit that shows what you have
6
- left: **subscription** usage for Claude Max, ChatGPT (Codex), Kimi Code, and
7
- Cursor — plus billing-cycle spend/balance for **OpenAI**, **Anthropic**, and
8
- **Kimi (Moonshot)** API keys. No signup, no server, no database, no telemetry —
9
- everything lives in `~/.sage/` on your machine.
6
+ left: **subscription** usage for Claude Max, ChatGPT (Codex), Gemini CLI,
7
+ Kimi Code, and Cursor — plus billing-cycle spend, quotas, and balance for
8
+ **OpenAI**, **Anthropic**, **Google Gemini**, and **Kimi (Moonshot)** APIs. No
9
+ signup, no server, no database, no telemetry — everything lives in `~/.sage/`
10
+ on your machine.
10
11
 
11
12
  Four pieces, one shared local store (the website is just this product's page):
12
13
 
@@ -20,8 +21,8 @@ Four pieces, one shared local store (the website is just this product's page):
20
21
  ## Install
21
22
 
22
23
  ```bash
23
- brew install thedevdavid/tap/sage # CLI
24
- brew install --cask thedevdavid/tap/sage # macOS menu bar app
24
+ brew install thedevdavid/tap/sage # CLI
25
+ brew install --cask thedevdavid/tap/sage-app # macOS menu bar app
25
26
  ```
26
27
 
27
28
  Or without Homebrew: run the CLI straight from npm
@@ -31,7 +32,8 @@ Or without Homebrew: run the CLI straight from npm
31
32
  ## Quick start
32
33
 
33
34
  ```bash
34
- sage add openai # or anthropic, kimi — prompts securely for your key
35
+ sage add openai # or anthropic, gemini, kimi — prompts securely for your key
36
+ sage add gemini --project MY_GCP_PROJECT --adc --billing-table BILLING_PROJECT.DATASET.TABLE
35
37
  sage status
36
38
  ```
37
39
 
@@ -39,11 +41,15 @@ sage status
39
41
  ● claude · Max (20x)
40
42
  Weekly ████████░░░░░░░░ 52% left · 3d 4h
41
43
  Session (5h) ██░░░░░░░░░░░░░░ 87% left · 2h 10m
44
+ ● gemini-cli · Google AI Pro
45
+ Model limits
46
+ gemini-4-hydrogen ███░░░░░░░░░░░░░ 82% left · 18h 12m
42
47
  ● cursor · Pro
43
48
  Monthly █████░░░░░░░░░░░ 34% left · 2026-08-06
44
49
 
45
50
  API keys
46
51
  openai $14.20 spent this cycle
52
+ gemini $6.85 spent this cycle · 1,420 reqs
47
53
  kimi 38.44 CNY balance
48
54
  cycle: day 12/31 · resets 2026-09-01 (19d left)
49
55
  ```
@@ -52,14 +58,16 @@ API keys
52
58
 
53
59
  Nothing to configure: sage auto-detects local sessions from Claude Desktop
54
60
  (its encrypted `Cookies` database and Keychain safe-storage item), Claude
55
- Code, Codex, Kimi Code, or Cursor (its `state.vscdb`), and queries the same
56
- backend endpoints those tools use. Claude Desktop's session is preferred when
57
- present, so Claude Max does not require a separate Claude Code login. Expiring
58
- Kimi Code access tokens are refreshed through Kimi Code's existing local OAuth
59
- credential store; no tool or browser is opened. Env overrides:
60
- `CLAUDE_CODE_OAUTH_TOKEN`, `CODEX_HOME`, `KIMI_CODE_API_KEY`.
61
-
62
- You get plan name, usage windows (session/weekly/monthly), and reset times.
61
+ Code, Codex, Gemini CLI (`~/.gemini/oauth_creds.json`), Kimi Code, or Cursor
62
+ (its `state.vscdb`), and queries the same backend endpoints those tools use.
63
+ Claude Desktop's session is preferred when present, so Claude Max does not
64
+ require a separate Claude Code login. Expiring Kimi Code access tokens are
65
+ refreshed through Kimi Code's existing local OAuth credential store; Gemini CLI
66
+ and Codex tokens are read-only; no tool or browser is opened. Env overrides:
67
+ `CLAUDE_CODE_OAUTH_TOKEN`, `CODEX_HOME`, `GEMINI_CLI_OAUTH_TOKEN`,
68
+ `GEMINI_CLI_HOME`, `GOOGLE_CLOUD_PROJECT`, `KIMI_CODE_API_KEY`.
69
+
70
+ You get plan name, usage windows (session/weekly/monthly/model), and reset times.
63
71
  An expired session shows the provider's own recovery step instead of stale
64
72
  numbers.
65
73
 
@@ -72,6 +80,11 @@ sage never invents numbers — provider APIs differ a lot:
72
80
  spend (`/v1/organization/costs`).
73
81
  - **Anthropic**: regular key → validity only. Add an **admin key**
74
82
  (`sk-ant-admin…`) for per-cycle spend (`/v1/organizations/cost_report`).
83
+ - **Google Gemini**: AI Studio key → validity only (`generativelanguage.googleapis.com/v1/models`
84
+ via `x-goog-api-key`). Add a GCP `--project` with `--adc` (gcloud Application
85
+ Default Credentials) or `--service-account PATH` for Cloud Monitoring
86
+ request counts and RPM/TPM/RPD quotas, and add `--billing-table project.dataset.table`
87
+ for authoritative Cloud Billing BigQuery cycle spend.
75
88
 
76
89
  No provider exposes your actual billing cycle via API, so sage anchors the
77
90
  cycle to a monthly reset day you choose:
@@ -84,8 +97,10 @@ sage cycle --set-reset-day 15
84
97
 
85
98
  ```
86
99
  sage status [--json] cycle + usage for keys and subscriptions (default)
87
- sage add <provider> add an API key (openai, anthropic, kimi)
100
+ sage add <provider> add an API provider (openai, anthropic, gemini, kimi)
88
101
  [--key K] [--admin-key K] prompts securely when flags are omitted
102
+ [--project P] [--billing-table P.D.T] [--service-account PATH] [--adc]
103
+ Google Cloud spend & quota options for gemini
89
104
  sage remove <provider> remove an API-key provider
90
105
  sage usage [name] [--json] detailed usage for one source or all of them
91
106
  sage cycle [--set-reset-day N] show billing cycle, or set the monthly reset day
@@ -98,15 +113,17 @@ sage version show version
98
113
 
99
114
  ## Local storage
100
115
 
101
- - `~/.sage/config.json` — keys + cycle reset day, written `chmod 600`. Shared by
102
- the CLI and the menu bar app (you can add keys from either).
116
+ - `~/.sage/config.json` — keys, optional GCP project/table/service-account path
117
+ settings, and cycle reset day, written `chmod 600`. Shared by the CLI and the
118
+ menu bar app (you can add providers from either). Service-account private keys
119
+ and gcloud ADC tokens remain in their original files and are never copied.
103
120
  - `~/.sage/cache.json` — last successful fetch per provider, so the menu bar
104
121
  app and offline runs still show something (marked as cached).
105
122
 
106
123
  ## macOS menu bar app
107
124
 
108
125
  ```bash
109
- brew install --cask thedevdavid/tap/sage
126
+ brew install --cask thedevdavid/tap/sage-app
110
127
  ```
111
128
 
112
129
  A leaf appears in your menu bar with subscription windows and per-provider
@@ -127,8 +144,9 @@ Or via the CLI (same SKILL.md, copied to `~/.agents/skills/sage/`, or
127
144
  sage skill install [--project]
128
145
  ```
129
146
 
130
- Your coding agent then knows to run `sage status --json` when you ask
131
- about API spend or cycle status — without ever reading your keys.
147
+ Your coding agent then knows to run `sage status --json` when you ask about
148
+ API spend, RPM/TPM/RPD quotas, balances, subscription limits, or cycle status —
149
+ without ever reading your keys.
132
150
 
133
151
  ## Development
134
152
 
package/bin/sage.js CHANGED
@@ -7,8 +7,10 @@ import { homedir } from 'node:os';
7
7
  import { loadConfig, saveConfig, loadCache, saveCache } from '../src/config.js';
8
8
  import { currentCycle } from '../src/cycle.js';
9
9
  import { PROVIDERS, PROVIDER_NAMES, isProvider } from '../src/providers/index.js';
10
+ import { validateBillingTable } from '../src/providers/gemini.js';
11
+ import { expandHome } from '../src/google-auth.js';
10
12
  import { SUBSCRIPTIONS, SUBSCRIPTION_NAMES, sortWindows } from '../src/subscriptions/index.js';
11
- import { promptSecret } from '../src/prompt.js';
13
+ import { promptSecret, promptText } from '../src/prompt.js';
12
14
 
13
15
  const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
14
16
  const VERSION = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8')).version;
@@ -19,8 +21,10 @@ Usage: sage <command> [options]
19
21
 
20
22
  Commands:
21
23
  status [--json] Cycle + usage for API keys and subscriptions (default)
22
- add <provider> Add an API key (openai, anthropic, kimi)
24
+ add <provider> Add an API provider (${PROVIDER_NAMES.join(', ')})
23
25
  [--key K] [--admin-key K] (prompts securely when flags are omitted)
26
+ [--project P] [--billing-table P.D.T] [--service-account PATH] [--adc]
27
+ (Google Cloud spend & quota options for gemini)
24
28
  remove <provider> Remove an API-key provider
25
29
  usage [name] [--json] Detailed usage for one source or all of them
26
30
  (names: ${PROVIDER_NAMES.join(', ')}, ${SUBSCRIPTION_NAMES.join(', ')})
@@ -31,9 +35,9 @@ Commands:
31
35
  version Show version
32
36
 
33
37
  API keys live in ~/.sage/config.json (chmod 600).
34
- Subscriptions (Claude Max, ChatGPT/Codex, Kimi Code) are auto-detected from
35
- the desktop apps and CLIs installed on this machine — nothing to configure.
36
- No account, no telemetry, no cloud.
38
+ Subscriptions (Claude Max, ChatGPT/Codex, Gemini CLI, Kimi Code, Cursor) are
39
+ auto-detected from the desktop apps and CLIs installed on this machine — nothing
40
+ to configure. No account, no telemetry, no cloud.
37
41
  `;
38
42
 
39
43
  function fail(message) {
@@ -139,7 +143,7 @@ async function collectStatus() {
139
143
 
140
144
  const TTY = process.stdout.isTTY;
141
145
  const ANSI = { reset: '\x1b[0m', bold: '\x1b[1m', dim: '\x1b[2m', green: '\x1b[32m', yellow: '\x1b[33m', red: '\x1b[31m' };
142
- const BRAND = { claude: 208, codex: 35, 'kimi-code': 63, cursor: 250 };
146
+ const BRAND = { claude: 208, codex: 35, 'gemini-cli': 39, 'kimi-code': 63, cursor: 250 };
143
147
  const paint = (color, text) => (TTY ? ANSI[color] + text + ANSI.reset : text);
144
148
  const paint256 = (n, text) => (TTY ? `\x1b[38;5;${n}m${text}\x1b[0m` : text);
145
149
  const bold = (text) => paint('bold', text);
@@ -160,8 +164,17 @@ function formatUsage(status) {
160
164
  if (status.error) return paint('red', `error: ${status.error}`);
161
165
  if (!status.ok) return 'invalid key';
162
166
  const u = status.usage;
163
- if (u && u.spent != null) return `$${u.spent.toFixed(2)} spent this cycle`;
167
+ if (u && u.spent != null) {
168
+ const amount = u.currency && u.currency !== 'USD'
169
+ ? `${u.spent.toFixed(2)} ${u.currency}`
170
+ : `$${u.spent.toFixed(2)}`;
171
+ const reqs = u.requests != null ? ` · ${Number(u.requests).toLocaleString('en-US')} reqs` : '';
172
+ return `${amount} spent this cycle${reqs}`;
173
+ }
164
174
  if (u && u.balance != null) return `${u.balance} ${u.currency} balance`;
175
+ if (u && u.requests != null) {
176
+ return `${Number(u.requests).toLocaleString('en-US')} reqs this cycle`;
177
+ }
165
178
  return status.note ?? 'no usage data';
166
179
  }
167
180
 
@@ -249,14 +262,15 @@ function printSubscription(name, status, labelWidth) {
249
262
  function printStatus({ cycle, api, subscriptions, configured, detected }) {
250
263
  if (configured.length === 0 && detected.length === 0) {
251
264
  console.log('No API keys configured and no subscriptions detected.');
252
- console.log('Add a key: sage add openai (or anthropic, kimi)');
253
- console.log('Subscriptions appear automatically once Claude Desktop, Claude Code, Codex, or Kimi Code is signed in.');
265
+ console.log('Add a key: sage add openai (or anthropic, gemini, kimi)');
266
+ console.log('Subscriptions appear automatically once Claude Desktop, Claude Code, Codex, Gemini CLI, Kimi Code, or Cursor is signed in.');
254
267
  return;
255
268
  }
256
269
  // One global label column so bars and dates align across providers.
257
270
  const labelWidth = Math.max(
258
271
  8,
259
272
  ...detected.flatMap((name) => (subscriptions[name]?.windows ?? []).map((w) => cleanLabel(w.label).length)),
273
+ ...configured.flatMap((name) => (api[name]?.quotas ?? []).map((q) => cleanLabel(q.label).length)),
260
274
  );
261
275
  for (const name of detected) {
262
276
  printSubscription(name, subscriptions[name], labelWidth);
@@ -265,7 +279,11 @@ function printStatus({ cycle, api, subscriptions, configured, detected }) {
265
279
  if (detected.length > 0) console.log();
266
280
  console.log(bold('API keys'));
267
281
  for (const name of configured) {
268
- console.log(` ${name.padEnd(10)} ${formatUsage(api[name])}${staleTag(api[name])}`);
282
+ const status = api[name];
283
+ console.log(` ${name.padEnd(10)} ${formatUsage(status)}${staleTag(status)}`);
284
+ if (!status?.error && status?.quotas?.length) {
285
+ printRateLimitRows(status.quotas.slice(0, 5), labelWidth);
286
+ }
269
287
  }
270
288
  console.log(dim(` cycle: day ${cycle.dayOfCycle}/${cycle.daysInCycle} · resets ${cycle.end.slice(0, 10)} (${cycle.daysLeft}d left)`));
271
289
  }
@@ -304,18 +322,51 @@ const COMMANDS = {
304
322
  const [name] = positional;
305
323
  if (!name || !isProvider(name)) fail(`unknown provider "${name ?? ''}" — use one of: ${PROVIDER_NAMES.join(', ')}`);
306
324
 
307
- const apiKey = flags.key ?? (await promptSecret(`API key for ${name}: `));
308
- if (!apiKey) fail('no API key provided');
325
+ const providerConfig = {};
326
+ if (name === 'gemini') {
327
+ const hasFlagInput = Boolean(
328
+ flags.key || flags.project || flags['billing-table'] || flags['service-account'] || flags.adc,
329
+ );
330
+ const apiKey = flags.key ?? (hasFlagInput ? '' : await promptSecret('API key for gemini (optional if using GCP ADC/service account, Enter to skip): '));
331
+ const projectId = flags.project ?? (hasFlagInput ? '' : await promptText('GCP project ID for Cloud Monitoring/BigQuery (optional, Enter to skip): '));
332
+ const billingTable = flags['billing-table'] ?? (hasFlagInput ? '' : await promptText('BigQuery billing export table project.dataset.table (optional, Enter to skip): '));
333
+ const serviceAccountPath = flags['service-account'] ?? (hasFlagInput ? '' : await promptText('Service account JSON path (optional, Enter for ADC/skip): '));
334
+ const useAdc = Boolean(flags.adc);
335
+
336
+ if (!apiKey && !projectId && !billingTable && !serviceAccountPath && !useAdc) {
337
+ fail('provide at least one of --key, --project, --billing-table, --service-account, or --adc');
338
+ }
339
+ if (billingTable) {
340
+ try {
341
+ validateBillingTable(billingTable);
342
+ } catch (err) {
343
+ fail(err.message);
344
+ }
345
+ providerConfig.billingTable = String(billingTable).trim();
346
+ }
347
+ if (serviceAccountPath) {
348
+ const resolved = expandHome(serviceAccountPath);
349
+ if (!existsSync(resolved)) fail(`service account JSON file not found: ${resolved}`);
350
+ providerConfig.serviceAccountPath = serviceAccountPath;
351
+ }
352
+ if (apiKey) providerConfig.apiKey = apiKey;
353
+ if (projectId) providerConfig.projectId = String(projectId).trim();
354
+ if (useAdc) providerConfig.useAdc = true;
355
+ } else {
356
+ const hasFlagInput = Boolean(flags.key || flags['admin-key']);
357
+ const apiKey = flags.key ?? (await promptSecret(`API key for ${name}: `));
358
+ if (!apiKey) fail('no API key provided');
359
+ providerConfig.apiKey = apiKey;
309
360
 
310
- const providerConfig = { apiKey };
311
- const adminKey = flags['admin-key'] ?? (await promptSecret(`Admin key for ${name} (optional, Enter to skip): `));
312
- if (adminKey) providerConfig.adminKey = adminKey;
361
+ const adminKey = flags['admin-key'] ?? (hasFlagInput ? '' : await promptSecret(`Admin key for ${name} (optional, Enter to skip): `));
362
+ if (adminKey) providerConfig.adminKey = adminKey;
363
+ }
313
364
 
314
365
  const config = loadConfig();
315
366
  config.providers[name] = { ...config.providers[name], ...providerConfig };
316
367
  saveConfig(config);
317
368
 
318
- console.log(`validating ${name} key...`);
369
+ console.log(`validating ${name}...`);
319
370
  try {
320
371
  const cycle = currentCycle(config.cycleResetDay);
321
372
  const status = await PROVIDERS[name].fetchStatus(config.providers[name], cycle);
@@ -326,7 +377,7 @@ const COMMANDS = {
326
377
  console.log(`${name} added · ${formatUsage(status)}`);
327
378
  } catch (err) {
328
379
  console.log(`${name} saved, but validation failed: ${err.message}`);
329
- console.log('The key is stored; `sage status` will retry.');
380
+ console.log('The configuration is stored; `sage status` will retry.');
330
381
  }
331
382
  },
332
383
 
@@ -367,6 +418,10 @@ const COMMANDS = {
367
418
  if (!isApi && !data.detected.includes(name)) fail(`${name} was not detected on this machine`);
368
419
  if (isApi) {
369
420
  console.log(`${name}: ${formatUsage(status)}`);
421
+ if (!status?.error && status?.quotas?.length) {
422
+ const width = Math.max(8, ...status.quotas.map((q) => cleanLabel(q.label).length));
423
+ printRateLimitRows(status.quotas, width);
424
+ }
370
425
  if (status?.note) console.log(dim(`note: ${status.note}`));
371
426
  } else {
372
427
  const width = Math.max(8, ...(status?.windows ?? []).map((w) => cleanLabel(w.label).length));
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@thedevdavid/sage",
3
- "version": "0.2.0",
4
- "description": "Local-only usage & billing-cycle tracker for LLM API keys and subscriptions (OpenAI, Anthropic/Claude, Kimi, Cursor).",
3
+ "version": "0.3.0",
4
+ "description": "Local-only usage & billing-cycle tracker for LLM API keys and subscriptions (OpenAI, Anthropic/Claude, Google Gemini, Kimi, Cursor).",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "sage": "bin/sage.js"
@@ -18,6 +18,8 @@
18
18
  "openai",
19
19
  "anthropic",
20
20
  "claude",
21
+ "gemini",
22
+ "google-gemini",
21
23
  "kimi",
22
24
  "moonshot",
23
25
  "api-usage",
@@ -1,61 +1,76 @@
1
1
  ---
2
2
  name: sage
3
- description: Check LLM API usage, spend, and billing cycle for OpenAI, Anthropic (Claude), and Kimi (Moonshot) via the sage CLI. Use when the user asks about API usage, current spend, remaining balance, or billing cycle status for these providers.
3
+ description: Check LLM API usage, spend, quotas, balances, billing cycles, and subscription limits via the sage CLI for OpenAI, Anthropic (Claude), Google Gemini, Kimi (Moonshot), and Cursor. Use when the user asks about API spend, RPM/TPM/RPD quotas, remaining balance, billing-cycle status, or Claude Max, Codex, Gemini CLI (Google AI Pro/Ultra), Kimi Code, or Cursor subscription windows.
4
4
  ---
5
5
 
6
- # sage — LLM usage & billing cycle checks
6
+ # sage — LLM usage, quota & billing-cycle checks
7
7
 
8
- `sage` is a local-only CLI that reports the current billing cycle and API
9
- usage/spend for OpenAI, Anthropic (Claude), and Kimi (Moonshot). All data lives
10
- in `~/.sage/`; there is no account, server, or telemetry.
8
+ `sage` is a local-only CLI that reports billing-cycle spend, quotas, balances,
9
+ and subscription limits for OpenAI, Anthropic (Claude), Google Gemini, Kimi
10
+ (Moonshot), and Cursor. All state lives in `~/.sage/` with no account, server,
11
+ or telemetry.
11
12
 
12
13
  ## When to use
13
14
 
14
- - "How much have I spent on OpenAI this month?"
15
- - "What's my Claude API usage / current cycle?"
16
- - "Check my Kimi balance."
17
- - "How much of my Claude Max / Codex / Kimi Code / Cursor subscription have I used?"
18
- - "When does my weekly limit reset?"
15
+ - "How much have I spent on OpenAI / Anthropic / Gemini this month?"
16
+ - "What are my Gemini API RPM/TPM quotas or cycle request counts?"
17
+ - "Check my Kimi balance or billing cycle reset date."
18
+ - "How much of my Claude Max / Codex / Gemini CLI (Google AI Pro/Ultra) / Kimi Code / Cursor subscription is left?"
19
+ - "When does my weekly or model quota reset?"
19
20
 
20
- ## How to use
21
+ ## Run the CLI
21
22
 
22
- Run the CLI (never read `~/.sage/config.json` yourself — it contains API keys):
23
+ Query usage through the CLI and keep `~/.sage/config.json` unread (it stores API keys):
23
24
 
24
25
  ```bash
25
26
  sage status --json # { cycle, api, subscriptions } — machine-readable
26
- sage usage openai # one API-key provider, human-readable
27
- sage usage codex # one subscription, human-readable
27
+ sage usage gemini # one API provider (openai, anthropic, gemini, kimi)
28
+ sage usage gemini-cli # one subscription (claude, codex, gemini-cli, kimi-code, cursor)
28
29
  sage cycle # cycle boundaries and days remaining
29
30
  ```
30
31
 
31
- If `sage` is not on PATH, use `bunx @thedevdavid/sage ...` instead.
32
+ If `sage` is not on `PATH`, run `bunx @thedevdavid/sage ...`.
32
33
 
33
- API-key providers live under `api` in the JSON; subscriptions (Claude Max,
34
- ChatGPT/Codex, Kimi Code — auto-detected from local desktop/CLI sessions) live
35
- under `subscriptions`, each with `plan` and `windows[]` (`label`,
36
- `usedPercent`, `resetsAt`). Sage reads local provider sessions and refreshes
37
- only the provider tokens that can be safely rotated through their existing
38
- credential stores. If Claude Desktop is present, it is preferred over the
39
- separate Claude Code credential; if a provider still shows an expired-session
40
- error, report the provider's actionable recovery message.
34
+ ### Output contract
41
35
 
42
- ## First run / missing provider
36
+ - `api` holds configured API providers (`usage.spent`, `usage.balance`,
37
+ `usage.requests`, `quotas[]`, and `note`).
38
+ - `subscriptions` holds auto-detected local desktop/CLI sessions (`plan`,
39
+ `windows[]` with `label`, `usedPercent`, `resetsAt`, optional `category`,
40
+ `limit`, `remaining`, `unit`).
41
+ - Claude Desktop is preferred over Claude Code when both exist. Codex and
42
+ Gemini CLI tokens are read-only; if a provider reports an expired-session or
43
+ project-access error, relay its exact recovery command.
44
+ - Whenever a provider includes `stale: true`, tell the user the live fetch
45
+ failed and the numbers are cached.
43
46
 
44
- If a provider is not configured, tell the user to run interactively (key entry
45
- is a hidden prompt):
47
+ ## Missing provider setup
48
+
49
+ When a provider is not configured, direct the user to run `sage add` interactively
50
+ so secrets stay hidden:
51
+
52
+ ```bash
53
+ sage add openai # or anthropic, gemini, kimi
54
+ ```
55
+
56
+ For Google Gemini spend and quotas, users can also pass GCP flags:
46
57
 
47
58
  ```bash
48
- sage add openai # or anthropic, kimi
59
+ sage add gemini --project PROJECT_ID --adc --billing-table PROJECT.DATASET.TABLE
49
60
  ```
50
61
 
51
- Notes to communicate honestly:
62
+ ## Provider capability bounds
52
63
 
53
- - OpenAI and Anthropic only expose spend data with an **admin key**; with a
54
- regular key sage reports key validity, not spend.
55
- - Kimi reports account balance (no per-cycle spend API exists).
56
- - The billing cycle is anchored to a user-set monthly reset day
57
- (`sage cycle --set-reset-day N`, default 1); no provider exposes the
58
- real billing cycle via API.
64
+ Communicate these limits honestly instead of guessing:
59
65
 
60
- If the output shows `stale`/cached data, say so — it means the fetch failed and
61
- the last known values are being shown.
66
+ - **OpenAI & Anthropic**: regular API keys report validity only; an admin key
67
+ unlocks per-cycle spend.
68
+ - **Google Gemini**: an AI Studio API key reports validity only; a GCP
69
+ `--project` with ADC (`gcloud auth application-default login`) or
70
+ `--service-account PATH` unlocks Cloud Monitoring cycle request counts and
71
+ RPM/TPM/RPD quotas; `--billing-table project.dataset.table` unlocks
72
+ authoritative Cloud Billing BigQuery cycle spend.
73
+ - **Kimi (Moonshot)**: reports account balance (no per-cycle spend API exists).
74
+ - **Billing cycle**: anchored to a user-chosen monthly reset day via
75
+ `sage cycle --set-reset-day N` (default `1`); no provider exposes your real
76
+ billing cycle over API.
@@ -0,0 +1,171 @@
1
+ import { createSign } from 'node:crypto';
2
+ import { existsSync } from 'node:fs';
3
+ import { readFile } from 'node:fs/promises';
4
+ import { homedir } from 'node:os';
5
+ import { join } from 'node:path';
6
+
7
+ export const GOOGLE_TOKEN_URL = 'https://oauth2.googleapis.com/token';
8
+ export const DEFAULT_SCOPES = [
9
+ 'https://www.googleapis.com/auth/bigquery.readonly',
10
+ 'https://www.googleapis.com/auth/monitoring.read',
11
+ ];
12
+
13
+ const TIMEOUT_MS = 10_000;
14
+
15
+ export function expandHome(filePath, home = homedir()) {
16
+ if (!filePath) return filePath;
17
+ if (filePath === '~') return home;
18
+ if (filePath.startsWith('~/')) return join(home, filePath.slice(2));
19
+ return filePath;
20
+ }
21
+
22
+ export function defaultAdcPath(home = homedir(), env = process.env) {
23
+ const gcloudDir = env.CLOUDSDK_CONFIG
24
+ ? expandHome(env.CLOUDSDK_CONFIG, home)
25
+ : join(home, '.config', 'gcloud');
26
+ return join(gcloudDir, 'application_default_credentials.json');
27
+ }
28
+
29
+ export function resolveCredentialPath({ serviceAccountPath, useAdc } = {}, env = process.env, home = homedir()) {
30
+ if (serviceAccountPath) {
31
+ const resolved = expandHome(serviceAccountPath, home);
32
+ if (!existsSync(resolved)) {
33
+ throw new Error(`Google credential file not found: ${resolved}`);
34
+ }
35
+ return { path: resolved, source: 'config' };
36
+ }
37
+ if (env.GOOGLE_APPLICATION_CREDENTIALS) {
38
+ const resolved = expandHome(env.GOOGLE_APPLICATION_CREDENTIALS, home);
39
+ if (!existsSync(resolved)) {
40
+ throw new Error(`GOOGLE_APPLICATION_CREDENTIALS file not found: ${resolved}`);
41
+ }
42
+ return { path: resolved, source: 'env' };
43
+ }
44
+ const adc = defaultAdcPath(home, env);
45
+ if (existsSync(adc)) {
46
+ return { path: adc, source: 'adc' };
47
+ }
48
+ if (useAdc) {
49
+ throw new Error(`Google ADC file not found (${adc}) — run: gcloud auth application-default login`);
50
+ }
51
+ throw new Error(
52
+ 'no Google Cloud credentials found — run `gcloud auth application-default login` or configure `--service-account PATH`',
53
+ );
54
+ }
55
+
56
+ export function parseCredentialJson(raw) {
57
+ let creds;
58
+ try {
59
+ creds = typeof raw === 'string' ? JSON.parse(raw) : raw;
60
+ } catch {
61
+ throw new Error('invalid Google credential JSON file');
62
+ }
63
+ if (!creds || typeof creds !== 'object') {
64
+ throw new Error('invalid Google credential JSON file');
65
+ }
66
+ if (creds.type === 'service_account') {
67
+ if (!creds.client_email || !creds.private_key) {
68
+ throw new Error('service account JSON is missing client_email or private_key');
69
+ }
70
+ return creds;
71
+ }
72
+ if (creds.type === 'authorized_user') {
73
+ if (!creds.client_id || !creds.client_secret || !creds.refresh_token) {
74
+ throw new Error('ADC authorized_user JSON is missing client_id, client_secret, or refresh_token');
75
+ }
76
+ return creds;
77
+ }
78
+ throw new Error(`unsupported Google credential type "${creds.type ?? 'unknown'}"`);
79
+ }
80
+
81
+ function base64urlJson(obj) {
82
+ return Buffer.from(JSON.stringify(obj), 'utf8').toString('base64url');
83
+ }
84
+
85
+ export function createServiceAccountJwt(creds, scopes = DEFAULT_SCOPES, nowSec = Math.floor(Date.now() / 1000)) {
86
+ const header = {
87
+ alg: 'RS256',
88
+ typ: 'JWT',
89
+ ...(creds.private_key_id ? { kid: creds.private_key_id } : {}),
90
+ };
91
+ const payload = {
92
+ iss: creds.client_email,
93
+ scope: scopes.join(' '),
94
+ aud: GOOGLE_TOKEN_URL,
95
+ iat: nowSec,
96
+ exp: nowSec + 3600,
97
+ };
98
+ const unsigned = `${base64urlJson(header)}.${base64urlJson(payload)}`;
99
+ const signer = createSign('RSA-SHA256');
100
+ signer.update(unsigned);
101
+ signer.end();
102
+ const signature = signer.sign(creds.private_key).toString('base64url');
103
+ return `${unsigned}.${signature}`;
104
+ }
105
+
106
+ export function buildTokenExchangeBody(creds, scopes = DEFAULT_SCOPES, nowSec = Math.floor(Date.now() / 1000)) {
107
+ if (creds.type === 'service_account') {
108
+ return new URLSearchParams({
109
+ grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
110
+ assertion: createServiceAccountJwt(creds, scopes, nowSec),
111
+ });
112
+ }
113
+ return new URLSearchParams({
114
+ grant_type: 'refresh_token',
115
+ client_id: creds.client_id,
116
+ client_secret: creds.client_secret,
117
+ refresh_token: creds.refresh_token,
118
+ });
119
+ }
120
+
121
+ export async function getGoogleAccessToken({
122
+ serviceAccountPath,
123
+ useAdc,
124
+ scopes = DEFAULT_SCOPES,
125
+ fetchImpl = fetch,
126
+ env = process.env,
127
+ home = homedir(),
128
+ nowSec = Math.floor(Date.now() / 1000),
129
+ } = {}) {
130
+ const { path } = resolveCredentialPath({ serviceAccountPath, useAdc }, env, home);
131
+ const raw = await readFile(path, 'utf8');
132
+ const creds = parseCredentialJson(raw);
133
+ const body = buildTokenExchangeBody(creds, scopes, nowSec);
134
+
135
+ const controller = new AbortController();
136
+ const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
137
+ try {
138
+ const res = await fetchImpl(GOOGLE_TOKEN_URL, {
139
+ method: 'POST',
140
+ headers: {
141
+ 'Content-Type': 'application/x-www-form-urlencoded',
142
+ Accept: 'application/json',
143
+ },
144
+ body: body.toString(),
145
+ signal: controller.signal,
146
+ });
147
+ let json = null;
148
+ try {
149
+ json = await res.json();
150
+ } catch {
151
+ // non-JSON error body
152
+ }
153
+ if (!res.ok) {
154
+ const message = json?.error_description ?? json?.error ?? `${res.status} ${res.statusText}`;
155
+ const err = new Error(`Google OAuth token exchange failed: ${message}`);
156
+ err.status = res.status;
157
+ throw err;
158
+ }
159
+ if (!json?.access_token) {
160
+ throw new Error('Google OAuth token response did not include access_token');
161
+ }
162
+ return {
163
+ accessToken: json.access_token,
164
+ quotaProjectId: creds.quota_project_id ?? null,
165
+ projectId: creds.project_id ?? creds.quota_project_id ?? null,
166
+ credentialType: creds.type,
167
+ };
168
+ } finally {
169
+ clearTimeout(timer);
170
+ }
171
+ }
package/src/prompt.js CHANGED
@@ -18,3 +18,16 @@ export function promptSecret(question) {
18
18
  });
19
19
  });
20
20
  }
21
+
22
+ // Prompt with normal echoed input (for non-secret config like GCP project IDs or paths).
23
+ // Non-interactive (piped/CI): resolves to '' immediately — use CLI flags instead.
24
+ export function promptText(question) {
25
+ if (!process.stdin.isTTY) return Promise.resolve('');
26
+ return new Promise((resolve) => {
27
+ const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: true });
28
+ rl.question(question, (answer) => {
29
+ rl.close();
30
+ resolve(answer.trim());
31
+ });
32
+ });
33
+ }
@@ -0,0 +1,328 @@
1
+ import { httpJson } from '../http.js';
2
+ import { getGoogleAccessToken } from '../google-auth.js';
3
+
4
+ const GEMINI_API_BASE = 'https://generativelanguage.googleapis.com';
5
+ const BIGQUERY_BASE = 'https://bigquery.googleapis.com/bigquery/v2';
6
+ const MONITORING_BASE = 'https://monitoring.googleapis.com/v3';
7
+ const SERVICE_NAME = 'generativelanguage.googleapis.com';
8
+
9
+ // Strict project.dataset.table validation to prevent SQL injection in BigQuery FROM clauses.
10
+ const BILLING_TABLE_RE = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_]+\.[A-Za-z0-9_-]+$/;
11
+
12
+ export function validateBillingTable(table) {
13
+ const trimmed = String(table ?? '').trim();
14
+ if (!BILLING_TABLE_RE.test(trimmed)) {
15
+ throw new Error(
16
+ `invalid BigQuery billing table "${table ?? ''}" — expected project.dataset.table`,
17
+ );
18
+ }
19
+ const [billingProject, dataset, tableName] = trimmed.split('.');
20
+ return { table: trimmed, billingProject, dataset, tableName };
21
+ }
22
+
23
+ export function buildBigQuerySpendRequest(billingTable, cycle, filterProjectId = null) {
24
+ const { table, billingProject } = validateBillingTable(billingTable);
25
+ const queryParameters = [
26
+ {
27
+ name: 'serviceId',
28
+ parameterType: { type: 'STRING' },
29
+ parameterValue: { value: SERVICE_NAME },
30
+ },
31
+ {
32
+ name: 'cycleStart',
33
+ parameterType: { type: 'TIMESTAMP' },
34
+ parameterValue: { value: cycle.start },
35
+ },
36
+ {
37
+ name: 'cycleEnd',
38
+ parameterType: { type: 'TIMESTAMP' },
39
+ parameterValue: { value: cycle.end },
40
+ },
41
+ ];
42
+ const projectClause = filterProjectId ? ' AND project.id = @projectId' : '';
43
+ if (filterProjectId) {
44
+ queryParameters.push({
45
+ name: 'projectId',
46
+ parameterType: { type: 'STRING' },
47
+ parameterValue: { value: filterProjectId },
48
+ });
49
+ }
50
+ const query = [
51
+ 'SELECT',
52
+ ' SUM(cost) + SUM(IFNULL((SELECT SUM(c.amount) FROM UNNEST(credits) c), 0)) AS net_cost,',
53
+ ' ANY_VALUE(currency) AS currency',
54
+ `FROM \`${table}\``,
55
+ "WHERE (service.id = @serviceId OR service.description LIKE '%Generative Language%' OR service.description LIKE '%Gemini API%')",
56
+ ' AND usage_start_time >= @cycleStart',
57
+ ' AND usage_start_time < @cycleEnd' + projectClause,
58
+ ].join('\n');
59
+
60
+ return {
61
+ url: `${BIGQUERY_BASE}/projects/${encodeURIComponent(billingProject)}/queries`,
62
+ body: {
63
+ query,
64
+ useLegacySql: false,
65
+ parameterMode: 'NAMED',
66
+ queryParameters,
67
+ timeoutMs: 10_000,
68
+ },
69
+ };
70
+ }
71
+
72
+ export function parseBigQuerySpend(data) {
73
+ if (data?.jobComplete === false) {
74
+ throw new Error('BigQuery billing query did not complete before timeout');
75
+ }
76
+ const row = data?.rows?.[0]?.f;
77
+ const rawCost = row?.[0]?.v;
78
+ const rawCurrency = row?.[1]?.v;
79
+ const cost = rawCost == null ? 0 : Number(rawCost);
80
+ if (!Number.isFinite(cost)) {
81
+ throw new Error(`unexpected BigQuery spend value "${rawCost}"`);
82
+ }
83
+ return {
84
+ spent: Math.round(cost * 100) / 100,
85
+ currency: typeof rawCurrency === 'string' && rawCurrency ? rawCurrency : 'USD',
86
+ };
87
+ }
88
+
89
+ function pointNumber(point) {
90
+ const v = point?.value;
91
+ if (!v) return null;
92
+ if (v.int64Value !== undefined) {
93
+ const n = Number(v.int64Value);
94
+ return Number.isFinite(n) ? n : null;
95
+ }
96
+ if (v.doubleValue !== undefined) {
97
+ const n = Number(v.doubleValue);
98
+ return Number.isFinite(n) ? n : null;
99
+ }
100
+ return null;
101
+ }
102
+
103
+ function seriesMaxValue(series) {
104
+ let max = null;
105
+ for (const point of series?.points ?? []) {
106
+ const n = pointNumber(point);
107
+ if (n !== null && (max === null || n > max)) max = n;
108
+ }
109
+ return max;
110
+ }
111
+
112
+ function quotaKey(series) {
113
+ const metric = series?.metric?.labels?.quota_metric ?? '';
114
+ const limitName = series?.metric?.labels?.limit_name ?? '';
115
+ const model = series?.metric?.labels?.base_model ?? series?.resource?.labels?.base_model ?? '';
116
+ return `${metric}|${limitName}|${model}`;
117
+ }
118
+
119
+ function inferQuotaUnit(metricName, limitName) {
120
+ const combined = `${metricName} ${limitName}`.toLowerCase();
121
+ if (combined.includes('token') && combined.includes('minute')) return 'TPM';
122
+ if (combined.includes('token') && combined.includes('day')) return 'TPD';
123
+ if (combined.includes('token')) return 'tokens';
124
+ if (combined.includes('day')) return 'RPD';
125
+ if (combined.includes('minute')) return 'RPM';
126
+ return 'requests';
127
+ }
128
+
129
+ function formatQuotaLabel(metricName, limitName, model) {
130
+ const unit = inferQuotaUnit(metricName, limitName);
131
+ if (model) return `${model} (${unit})`;
132
+ const shortMetric = String(metricName)
133
+ .replace(/^generativelanguage\.googleapis\.com\//, '')
134
+ .replace(/^generate_content_/, '')
135
+ .replace(/[_-]+/g, ' ')
136
+ .trim();
137
+ const base = shortMetric
138
+ ? shortMetric.charAt(0).toUpperCase() + shortMetric.slice(1)
139
+ : 'Gemini API';
140
+ return `${base} (${unit})`;
141
+ }
142
+
143
+ export function parseMonitoringQuotas(usageData, limitData, requestData) {
144
+ let requests = null;
145
+ for (const series of requestData?.timeSeries ?? []) {
146
+ for (const point of series?.points ?? []) {
147
+ const n = pointNumber(point);
148
+ if (n !== null) requests = (requests ?? 0) + n;
149
+ }
150
+ }
151
+ if (requests !== null) requests = Math.round(requests);
152
+
153
+ const usageByKey = new Map();
154
+ for (const series of usageData?.timeSeries ?? []) {
155
+ const max = seriesMaxValue(series);
156
+ if (max === null) continue;
157
+ const key = quotaKey(series);
158
+ const prev = usageByKey.get(key);
159
+ if (prev === undefined || max > prev) usageByKey.set(key, max);
160
+ }
161
+
162
+ const limitsByKey = new Map();
163
+ for (const series of limitData?.timeSeries ?? []) {
164
+ const max = seriesMaxValue(series);
165
+ if (max === null || max <= 0) continue;
166
+ const key = quotaKey(series);
167
+ const prev = limitsByKey.get(key);
168
+ if (!prev || max > prev.limit) {
169
+ limitsByKey.set(key, {
170
+ limit: max,
171
+ metricName: series?.metric?.labels?.quota_metric ?? '',
172
+ limitName: series?.metric?.labels?.limit_name ?? '',
173
+ model: series?.metric?.labels?.base_model ?? series?.resource?.labels?.base_model ?? '',
174
+ });
175
+ }
176
+ }
177
+
178
+ const quotas = [];
179
+ for (const [key, entry] of limitsByKey) {
180
+ const used = usageByKey.get(key) ?? 0;
181
+ const usedPercent = Math.min(100, Math.round((used / entry.limit) * 1000) / 10);
182
+ quotas.push({
183
+ label: formatQuotaLabel(entry.metricName, entry.limitName, entry.model),
184
+ usedPercent,
185
+ resetsAt: null,
186
+ category: 'rate',
187
+ limit: entry.limit,
188
+ remaining: Math.max(0, Math.round((entry.limit - used) * 10) / 10),
189
+ unit: inferQuotaUnit(entry.metricName, entry.limitName),
190
+ });
191
+ }
192
+
193
+ // Prefer actively used quotas first, then highest utilization, then alphabetical.
194
+ quotas.sort((a, b) => {
195
+ if (b.usedPercent !== a.usedPercent) return b.usedPercent - a.usedPercent;
196
+ return a.label.localeCompare(b.label);
197
+ });
198
+
199
+ return { requests, quotas };
200
+ }
201
+
202
+ function monitoringUrl(projectId, params) {
203
+ const qs = new URLSearchParams(params);
204
+ return `${MONITORING_BASE}/projects/${encodeURIComponent(projectId)}/timeSeries?${qs.toString()}`;
205
+ }
206
+
207
+ async function fetchMonitoringSummary(projectId, cycle, headers, { httpJsonImpl, now }) {
208
+ const nowMs = now();
209
+ const cycleEndMs = Math.min(nowMs, new Date(cycle.end).getTime());
210
+ const nowIso = new Date(nowMs).toISOString();
211
+ const tenMinAgoIso = new Date(nowMs - 10 * 60_000).toISOString();
212
+ const oneDayAgoIso = new Date(nowMs - 24 * 3_600_000).toISOString();
213
+
214
+ const requestUrl = monitoringUrl(projectId, {
215
+ filter: `metric.type="serviceruntime.googleapis.com/api/request_count" AND resource.labels.service="${SERVICE_NAME}"`,
216
+ 'interval.startTime': cycle.start,
217
+ 'interval.endTime': new Date(Math.max(cycleEndMs, new Date(cycle.start).getTime() + 1000)).toISOString(),
218
+ 'aggregation.alignmentPeriod': '86400s',
219
+ 'aggregation.perSeriesAligner': 'ALIGN_SUM',
220
+ 'aggregation.crossSeriesReducer': 'REDUCE_SUM',
221
+ });
222
+ const usageUrl = monitoringUrl(projectId, {
223
+ filter: `metric.type="serviceruntime.googleapis.com/quota/rate/net_usage" AND resource.type="consumer_quota" AND resource.labels.service="${SERVICE_NAME}"`,
224
+ 'interval.startTime': tenMinAgoIso,
225
+ 'interval.endTime': nowIso,
226
+ 'aggregation.alignmentPeriod': '60s',
227
+ 'aggregation.perSeriesAligner': 'ALIGN_MAX',
228
+ });
229
+ const limitUrl = monitoringUrl(projectId, {
230
+ filter: `metric.type="serviceruntime.googleapis.com/quota/limit" AND resource.type="consumer_quota" AND resource.labels.service="${SERVICE_NAME}"`,
231
+ 'interval.startTime': oneDayAgoIso,
232
+ 'interval.endTime': nowIso,
233
+ 'aggregation.alignmentPeriod': '3600s',
234
+ 'aggregation.perSeriesAligner': 'ALIGN_MAX',
235
+ });
236
+
237
+ const [usageData, limitData, requestData] = await Promise.all([
238
+ httpJsonImpl(usageUrl, { headers }).catch(() => null),
239
+ httpJsonImpl(limitUrl, { headers }).catch(() => null),
240
+ httpJsonImpl(requestUrl, { headers }),
241
+ ]);
242
+ return parseMonitoringQuotas(usageData, limitData, requestData);
243
+ }
244
+
245
+ // Google Gemini API keys validate via /v1/models (x-goog-api-key header) but
246
+ // expose no spend or guaranteed rate-limit headers. Authoritative cycle spend
247
+ // comes from GCP Cloud Billing BigQuery export, and project-level RPM/TPM/RPD
248
+ // quotas & request counts come from Cloud Monitoring via ADC or a service account.
249
+ export async function fetchStatus(
250
+ { apiKey, projectId, billingTable, serviceAccountPath, useAdc },
251
+ cycle,
252
+ { httpJsonImpl = httpJson, getTokenImpl = getGoogleAccessToken, now = Date.now } = {},
253
+ ) {
254
+ if (apiKey) {
255
+ await httpJsonImpl(`${GEMINI_API_BASE}/v1/models`, {
256
+ headers: { 'x-goog-api-key': apiKey },
257
+ });
258
+ }
259
+
260
+ const wantsGcp = Boolean(billingTable || projectId || serviceAccountPath || useAdc);
261
+ if (!wantsGcp) {
262
+ if (!apiKey) {
263
+ throw new Error('no Gemini API key or Google Cloud configuration found');
264
+ }
265
+ return {
266
+ ok: true,
267
+ usageAvailable: false,
268
+ usage: null,
269
+ quotas: [],
270
+ note: 'key valid · add --project + --adc/--service-account for quotas, or --billing-table for cycle spend',
271
+ };
272
+ }
273
+
274
+ const token = await getTokenImpl({ serviceAccountPath, useAdc });
275
+ const effectiveProject = projectId || token.projectId || null;
276
+ const gcpHeaders = {
277
+ Authorization: `Bearer ${token.accessToken}`,
278
+ Accept: 'application/json',
279
+ ...(token.quotaProjectId || effectiveProject
280
+ ? { 'x-goog-user-project': token.quotaProjectId ?? effectiveProject }
281
+ : {}),
282
+ };
283
+
284
+ if (!billingTable && !effectiveProject) {
285
+ throw new Error('GCP project ID is required for Cloud Monitoring — pass --project PROJECT_ID');
286
+ }
287
+
288
+ let spend = null;
289
+ let monitoring = { requests: null, quotas: [] };
290
+
291
+ const tasks = [];
292
+ if (billingTable) {
293
+ const req = buildBigQuerySpendRequest(billingTable, cycle, projectId || null);
294
+ tasks.push(
295
+ httpJsonImpl(req.url, { method: 'POST', headers: gcpHeaders, body: req.body }).then((data) => {
296
+ spend = parseBigQuerySpend(data);
297
+ }),
298
+ );
299
+ }
300
+ if (effectiveProject) {
301
+ tasks.push(
302
+ fetchMonitoringSummary(effectiveProject, cycle, gcpHeaders, { httpJsonImpl, now }).then((res) => {
303
+ monitoring = res;
304
+ }),
305
+ );
306
+ }
307
+ await Promise.all(tasks);
308
+
309
+ const usage = {};
310
+ if (spend) {
311
+ usage.spent = spend.spent;
312
+ usage.currency = spend.currency;
313
+ }
314
+ if (monitoring.requests !== null) {
315
+ usage.requests = monitoring.requests;
316
+ }
317
+ const hasUsage = Object.keys(usage).length > 0 || monitoring.quotas.length > 0;
318
+
319
+ return {
320
+ ok: true,
321
+ usageAvailable: hasUsage,
322
+ usage: Object.keys(usage).length > 0 ? usage : null,
323
+ quotas: monitoring.quotas,
324
+ note: spend
325
+ ? null
326
+ : 'Cloud Monitoring quotas/requests · add --billing-table project.dataset.table for cycle spend',
327
+ };
328
+ }
@@ -1,10 +1,12 @@
1
1
  import { fetchStatus as openai } from './openai.js';
2
2
  import { fetchStatus as anthropic } from './anthropic.js';
3
+ import { fetchStatus as gemini } from './gemini.js';
3
4
  import { fetchStatus as kimi } from './kimi.js';
4
5
 
5
6
  export const PROVIDERS = {
6
7
  openai: { fetchStatus: openai },
7
8
  anthropic: { fetchStatus: anthropic },
9
+ gemini: { fetchStatus: gemini },
8
10
  kimi: { fetchStatus: kimi },
9
11
  };
10
12
 
@@ -0,0 +1,176 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { httpJson } from '../http.js';
5
+ import { throwIfExpired, rethrowIfUnauthorized } from '../util.js';
6
+
7
+ const BASE = 'https://cloudcode-pa.googleapis.com';
8
+ const EXPIRED_ERROR = 'Gemini CLI session expired — run `gemini` once to refresh it';
9
+
10
+ const TIER_LABELS = new Map([
11
+ ['g1-ultra-tier', 'Google AI Ultra'],
12
+ ['google-ai-ultra', 'Google AI Ultra'],
13
+ ['ultra-tier', 'Google AI Ultra'],
14
+ ['g1-pro-tier', 'Google AI Pro'],
15
+ ['google-ai-pro', 'Google AI Pro'],
16
+ ['pro-tier', 'Google AI Pro'],
17
+ ['standard-tier', 'Standard'],
18
+ ['free-tier', 'Free'],
19
+ ]);
20
+
21
+ function normalizeExpiryMs(raw) {
22
+ const value = Number(raw);
23
+ if (!Number.isFinite(value) || value <= 0) return null;
24
+ // Gemini CLI writes expiry_date in ms; tolerate seconds too.
25
+ return value < 1e12 ? value * 1000 : value;
26
+ }
27
+
28
+ // Gemini CLI stores OAuth credentials in ~/.gemini/oauth_creds.json.
29
+ // Read-only: we never mutate Gemini CLI's refresh tokens.
30
+ export async function readGeminiCliCredentials({ env = process.env, home = homedir() } = {}) {
31
+ if (env.GEMINI_CLI_OAUTH_TOKEN) {
32
+ return { accessToken: env.GEMINI_CLI_OAUTH_TOKEN, expiresAt: null };
33
+ }
34
+ const dir = env.GEMINI_CLI_HOME ?? join(home, '.gemini');
35
+ try {
36
+ const raw = JSON.parse(await readFile(join(dir, 'oauth_creds.json'), 'utf8'));
37
+ if (raw?.access_token) {
38
+ return {
39
+ accessToken: raw.access_token,
40
+ expiresAt: normalizeExpiryMs(raw.expiry_date ?? raw.expires_at),
41
+ };
42
+ }
43
+ } catch {
44
+ // not installed / not signed in
45
+ }
46
+ return null;
47
+ }
48
+
49
+ async function readConfiguredProject({ env = process.env, home = homedir() } = {}) {
50
+ if (env.GOOGLE_CLOUD_PROJECT) return env.GOOGLE_CLOUD_PROJECT;
51
+ const dir = env.GEMINI_CLI_HOME ?? join(home, '.gemini');
52
+ try {
53
+ const settings = JSON.parse(await readFile(join(dir, 'settings.json'), 'utf8'));
54
+ return settings?.googleCloudProject ?? settings?.project ?? null;
55
+ } catch {
56
+ return null;
57
+ }
58
+ }
59
+
60
+ export function formatGeminiPlan(loadData) {
61
+ const tier = loadData?.paidTier ?? loadData?.currentTier ?? null;
62
+ const id = String(tier?.id ?? '').trim().toLowerCase();
63
+ if (id && TIER_LABELS.has(id)) return TIER_LABELS.get(id);
64
+ const name = String(tier?.name ?? '').trim();
65
+ if (name) return name;
66
+ if (!id) return null;
67
+ return id
68
+ .replace(/-tier$/, '')
69
+ .replace(/[_-]+/g, ' ')
70
+ .replace(/\b\w/g, (c) => c.toUpperCase());
71
+ }
72
+
73
+ export function parseGeminiCliQuota(loadData, quotaData) {
74
+ const buckets = quotaData?.buckets ?? [];
75
+ const byModel = new Map();
76
+
77
+ for (const bucket of buckets) {
78
+ const remaining = Number(bucket?.remainingFraction);
79
+ if (!Number.isFinite(remaining)) continue;
80
+ const clamped = Math.min(1, Math.max(0, remaining));
81
+ const usedPercent = Math.round((1 - clamped) * 1000) / 10;
82
+ const model = String(bucket?.modelId ?? bucket?.model ?? 'Gemini').trim();
83
+ const resetsAt = bucket?.resetTime ?? bucket?.reset_time ?? null;
84
+ const existing = byModel.get(model);
85
+ // If multiple buckets exist for the same model (e.g. input/output token types),
86
+ // show the tightest (highest utilization) bucket.
87
+ if (!existing || usedPercent > existing.usedPercent) {
88
+ byModel.set(model, {
89
+ label: model,
90
+ usedPercent,
91
+ resetsAt,
92
+ category: 'model',
93
+ });
94
+ }
95
+ }
96
+
97
+ return {
98
+ kind: 'subscription',
99
+ ok: true,
100
+ plan: formatGeminiPlan(loadData),
101
+ windows: [...byModel.values()],
102
+ credits: null,
103
+ note: null,
104
+ };
105
+ }
106
+
107
+ export async function available(options) {
108
+ return (await readGeminiCliCredentials(options)) !== null;
109
+ }
110
+
111
+ export async function fetchStatus({
112
+ httpJsonImpl = httpJson,
113
+ env = process.env,
114
+ home = homedir(),
115
+ } = {}) {
116
+ const creds = await readGeminiCliCredentials({ env, home });
117
+ if (!creds) throw new Error('no Gemini CLI credentials found (is Gemini CLI installed and signed in?)');
118
+ throwIfExpired(creds.expiresAt, EXPIRED_ERROR);
119
+
120
+ const configuredProject = await readConfiguredProject({ env, home });
121
+ const baseHeaders = {
122
+ Authorization: `Bearer ${creds.accessToken}`,
123
+ Accept: 'application/json',
124
+ };
125
+
126
+ let loadData = null;
127
+ try {
128
+ loadData = await httpJsonImpl(`${BASE}/v1internal:loadCodeAssist`, {
129
+ method: 'POST',
130
+ headers: {
131
+ ...baseHeaders,
132
+ ...(configuredProject ? { 'x-goog-user-project': configuredProject } : {}),
133
+ },
134
+ body: {
135
+ ...(configuredProject ? { cloudaicompanionProject: configuredProject } : {}),
136
+ metadata: { ideType: 'IDE_UNSPECIFIED', platform: 'PLATFORM_UNSPECIFIED', pluginType: 'GEMINI' },
137
+ },
138
+ });
139
+ } catch (err) {
140
+ rethrowIfUnauthorized(err, EXPIRED_ERROR);
141
+ if (err.status === 403) {
142
+ throw new Error(
143
+ 'Gemini CLI project access denied — set GOOGLE_CLOUD_PROJECT or run `gemini` once to refresh',
144
+ );
145
+ }
146
+ // Plan/project metadata is best-effort if retrieveUserQuota still works.
147
+ loadData = null;
148
+ }
149
+
150
+ const projectId =
151
+ loadData?.cloudaicompanionProject?.id ??
152
+ (typeof loadData?.cloudaicompanionProject === 'string' ? loadData.cloudaicompanionProject : null) ??
153
+ configuredProject;
154
+
155
+ let quotaData;
156
+ try {
157
+ quotaData = await httpJsonImpl(`${BASE}/v1internal:retrieveUserQuota`, {
158
+ method: 'POST',
159
+ headers: {
160
+ ...baseHeaders,
161
+ ...(projectId ? { 'x-goog-user-project': projectId } : {}),
162
+ },
163
+ body: projectId ? { project: projectId } : {},
164
+ });
165
+ } catch (err) {
166
+ rethrowIfUnauthorized(err, EXPIRED_ERROR);
167
+ if (err.status === 403) {
168
+ throw new Error(
169
+ 'Gemini CLI quota access denied — set GOOGLE_CLOUD_PROJECT or ensure cloudaicompanion.googleapis.com is enabled',
170
+ );
171
+ }
172
+ throw err;
173
+ }
174
+
175
+ return parseGeminiCliQuota(loadData, quotaData);
176
+ }
@@ -1,5 +1,6 @@
1
1
  import * as claude from './claude.js';
2
2
  import * as codex from './codex.js';
3
+ import * as gemini from './gemini.js';
3
4
  import * as kimi from './kimi.js';
4
5
  import * as cursor from './cursor.js';
5
6
 
@@ -9,6 +10,7 @@ import * as cursor from './cursor.js';
9
10
  export const SUBSCRIPTIONS = {
10
11
  claude: { fetchStatus: claude.fetchStatus, available: claude.available, minIntervalMs: 5 * 60_000 },
11
12
  codex: { fetchStatus: codex.fetchStatus, available: codex.available, minIntervalMs: 60_000 },
13
+ 'gemini-cli': { fetchStatus: gemini.fetchStatus, available: gemini.available, minIntervalMs: 5 * 60_000 },
12
14
  'kimi-code': { fetchStatus: kimi.fetchStatus, available: kimi.available, minIntervalMs: 60_000 },
13
15
  cursor: { fetchStatus: cursor.fetchStatus, available: cursor.available, minIntervalMs: 60_000 },
14
16
  };