@thedevdavid/sage 0.1.8 β 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 +96 -58
- package/bin/sage.js +80 -19
- package/package.json +4 -2
- package/skill/sage/SKILL.md +51 -36
- package/src/google-auth.js +171 -0
- package/src/prompt.js +13 -0
- package/src/providers/gemini.js +328 -0
- package/src/providers/index.js +2 -0
- package/src/subscriptions/gemini.js +176 -0
- package/src/subscriptions/index.js +2 -0
package/README.md
CHANGED
|
@@ -1,36 +1,77 @@
|
|
|
1
1
|
# πΏ sage
|
|
2
2
|
|
|
3
|
-
Know your LLM
|
|
3
|
+
Know your LLM usage at a glance. Nothing else.
|
|
4
4
|
|
|
5
|
-
sage is a tiny, open-source, **local-only** toolkit that shows
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
5
|
+
sage is a tiny, open-source, **local-only** toolkit that shows what you have
|
|
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.
|
|
9
11
|
|
|
10
12
|
Four pieces, one shared local store (the website is just this product's page):
|
|
11
13
|
|
|
12
14
|
| Piece | What it is |
|
|
13
15
|
| --- | --- |
|
|
14
|
-
| **CLI** (`cli/`) | Zero-dependency CLI (
|
|
15
|
-
| **macOS app** (`sage/`) | Menu bar app
|
|
16
|
-
| **Agent skill** (`
|
|
16
|
+
| **CLI** (`cli/`) | Zero-dependency CLI (Bun or Node β₯ 18), on npm and Homebrew |
|
|
17
|
+
| **macOS app** (`sage/`) | Menu bar app, on Homebrew and GitHub releases |
|
|
18
|
+
| **Agent skill** (`skills/sage/`) | Teaches coding agents to answer usage questions via the CLI |
|
|
17
19
|
| **Website** (`site/`) | This product's single-page static site |
|
|
18
20
|
|
|
21
|
+
## Install
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
brew install thedevdavid/tap/sage # CLI
|
|
25
|
+
brew install --cask thedevdavid/tap/sage-app # macOS menu bar app
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Or without Homebrew: run the CLI straight from npm
|
|
29
|
+
(`bunx @thedevdavid/sage status`), or grab `sage.app.zip` from
|
|
30
|
+
[GitHub releases](https://github.com/thedevdavid/sage/releases/latest).
|
|
31
|
+
|
|
19
32
|
## Quick start
|
|
20
33
|
|
|
21
34
|
```bash
|
|
22
|
-
|
|
23
|
-
|
|
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
|
|
37
|
+
sage status
|
|
24
38
|
```
|
|
25
39
|
|
|
26
40
|
```
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
41
|
+
β claude Β· Max (20x)
|
|
42
|
+
Weekly ββββββββββββββββ 52% left Β· 3d 4h
|
|
43
|
+
Session (5h) ββββββββββββββββ 87% left Β· 2h 10m
|
|
44
|
+
β gemini-cli Β· Google AI Pro
|
|
45
|
+
Model limits
|
|
46
|
+
gemini-4-hydrogen ββββββββββββββββ 82% left Β· 18h 12m
|
|
47
|
+
β cursor Β· Pro
|
|
48
|
+
Monthly ββββββββββββββββ 34% left Β· 2026-08-06
|
|
49
|
+
|
|
50
|
+
API keys
|
|
51
|
+
openai $14.20 spent this cycle
|
|
52
|
+
gemini $6.85 spent this cycle Β· 1,420 reqs
|
|
53
|
+
kimi 38.44 CNY balance
|
|
54
|
+
cycle: day 12/31 Β· resets 2026-09-01 (19d left)
|
|
31
55
|
```
|
|
32
56
|
|
|
33
|
-
##
|
|
57
|
+
## Subscription tracking
|
|
58
|
+
|
|
59
|
+
Nothing to configure: sage auto-detects local sessions from Claude Desktop
|
|
60
|
+
(its encrypted `Cookies` database and Keychain safe-storage item), Claude
|
|
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.
|
|
71
|
+
An expired session shows the provider's own recovery step instead of stale
|
|
72
|
+
numbers.
|
|
73
|
+
|
|
74
|
+
## What each API provider can report
|
|
34
75
|
|
|
35
76
|
sage never invents numbers β provider APIs differ a lot:
|
|
36
77
|
|
|
@@ -39,6 +80,11 @@ sage never invents numbers β provider APIs differ a lot:
|
|
|
39
80
|
spend (`/v1/organization/costs`).
|
|
40
81
|
- **Anthropic**: regular key β validity only. Add an **admin key**
|
|
41
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.
|
|
42
88
|
|
|
43
89
|
No provider exposes your actual billing cycle via API, so sage anchors the
|
|
44
90
|
cycle to a monthly reset day you choose:
|
|
@@ -47,77 +93,69 @@ cycle to a monthly reset day you choose:
|
|
|
47
93
|
sage cycle --set-reset-day 15
|
|
48
94
|
```
|
|
49
95
|
|
|
50
|
-
## Subscription tracking
|
|
51
|
-
|
|
52
|
-
Separate from API keys, sage tracks **subscription** usage β Claude Max,
|
|
53
|
-
ChatGPT (Codex), Kimi Code, and Cursor β plan name, session/weekly/monthly
|
|
54
|
-
usage windows, and reset times:
|
|
55
|
-
|
|
56
|
-
```
|
|
57
|
-
β claude Β· Max (20x)
|
|
58
|
-
Session (5h) ββββββββββββββββ 100% left
|
|
59
|
-
Weekly ββββββββββββββββ 0% left Β· 11h 22m
|
|
60
|
-
β cursor Β· Pro
|
|
61
|
-
Monthly ββββββββββββββββ 3% left Β· 2026-08-06
|
|
62
|
-
```
|
|
63
|
-
|
|
64
|
-
Nothing to configure: sage auto-detects local sessions from Claude Desktop
|
|
65
|
-
(its encrypted `Cookies` database and Keychain safe-storage item), Claude
|
|
66
|
-
Code, Codex, Kimi Code, or Cursor. It queries the same backend endpoints those
|
|
67
|
-
tools use. Claude Desktop is preferred when it is running, so Claude Max does
|
|
68
|
-
not require a separate Claude Code login. Expiring Kimi Code access tokens are
|
|
69
|
-
refreshed through Kimi Code's existing local OAuth credential store; no tool or
|
|
70
|
-
browser is opened. Env overrides: `CLAUDE_CODE_OAUTH_TOKEN`, `CODEX_HOME`,
|
|
71
|
-
`KIMI_CODE_API_KEY`.
|
|
72
|
-
|
|
73
96
|
## CLI commands
|
|
74
97
|
|
|
75
98
|
```
|
|
76
|
-
sage status [--json] cycle + usage for
|
|
77
|
-
sage add <provider>
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
99
|
+
sage status [--json] cycle + usage for keys and subscriptions (default)
|
|
100
|
+
sage add <provider> add an API provider (openai, anthropic, gemini, kimi)
|
|
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
|
|
104
|
+
sage remove <provider> remove an API-key provider
|
|
105
|
+
sage usage [name] [--json] detailed usage for one source or all of them
|
|
106
|
+
sage cycle [--set-reset-day N] show billing cycle, or set the monthly reset day
|
|
81
107
|
sage skill install [--project] install the agent skill
|
|
108
|
+
sage help show help
|
|
109
|
+
sage version show version
|
|
82
110
|
```
|
|
83
111
|
|
|
84
112
|
`--json` output is stable and agent/script-friendly.
|
|
85
113
|
|
|
86
114
|
## Local storage
|
|
87
115
|
|
|
88
|
-
- `~/.sage/config.json` β keys
|
|
89
|
-
|
|
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.
|
|
90
120
|
- `~/.sage/cache.json` β last successful fetch per provider, so the menu bar
|
|
91
121
|
app and offline runs still show something (marked as cached).
|
|
92
122
|
|
|
93
123
|
## macOS menu bar app
|
|
94
124
|
|
|
95
125
|
```bash
|
|
96
|
-
|
|
126
|
+
brew install --cask thedevdavid/tap/sage-app
|
|
97
127
|
```
|
|
98
128
|
|
|
99
|
-
A leaf appears in your menu bar with
|
|
100
|
-
Add keys directly from the app (
|
|
101
|
-
the CLI β both share `~/.sage/`. It refreshes every 15 minutes, and the
|
|
129
|
+
A leaf appears in your menu bar with subscription windows and per-provider
|
|
130
|
+
usage. Add keys directly from the app (+ button β paste, validates on save) or
|
|
131
|
+
from the CLI β both share `~/.sage/`. It refreshes every 15 minutes, and the
|
|
102
132
|
**Refresh now** button forces an immediate pull from every detected source.
|
|
103
133
|
|
|
104
134
|
## Agent skill
|
|
105
135
|
|
|
106
136
|
```bash
|
|
107
|
-
|
|
108
|
-
|
|
137
|
+
npx skills add thedevdavid/sage # via skills.sh, into your agent's skill dir
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
Or via the CLI (same SKILL.md, copied to `~/.agents/skills/sage/`, or
|
|
141
|
+
`./.agents/skills/sage/` with `--project`):
|
|
142
|
+
|
|
143
|
+
```bash
|
|
144
|
+
sage skill install [--project]
|
|
109
145
|
```
|
|
110
146
|
|
|
111
|
-
Your coding agent then knows to run `sage status --json` when you ask
|
|
112
|
-
|
|
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.
|
|
113
150
|
|
|
114
151
|
## Development
|
|
115
152
|
|
|
116
153
|
- CLI: `bun cli/bin/sage.js --help` (Bun or Node β₯ 18, no dependencies, no build step).
|
|
117
154
|
- App: `xcodebuild -project sage.xcodeproj -scheme sage -destination 'platform=macOS' build`
|
|
118
|
-
The project is kept at object format 77 (Xcode 16+)
|
|
119
|
-
build it. If Xcode offers to upgrade the project
|
|
120
|
-
format makes the release workflow fail to open the
|
|
155
|
+
(macOS 26+, Xcode 26+). The project is kept at object format 77 (Xcode 16+)
|
|
156
|
+
so hosted CI runners can build it. If Xcode offers to upgrade the project
|
|
157
|
+
format, decline β a newer format makes the release workflow fail to open the
|
|
158
|
+
project.
|
|
121
159
|
- Site: `python3 -m http.server 8080 -d site` β one static `index.html`, no build step.
|
|
122
160
|
- Screenshots: `scripts/build-capture-window.sh` once, then
|
|
123
161
|
`build/capture-window.app/Contents/MacOS/capture-window out.png --app-name sage`
|
|
@@ -128,10 +166,10 @@ about API spend or cycle status β without ever reading your keys.
|
|
|
128
166
|
## Releasing
|
|
129
167
|
|
|
130
168
|
```bash
|
|
131
|
-
make release VERSION=0.1.
|
|
169
|
+
make release VERSION=0.1.9
|
|
132
170
|
```
|
|
133
171
|
|
|
134
|
-
That bumps `cli/package.json`, commits, tags `v0.1.
|
|
172
|
+
That bumps `cli/package.json`, commits, tags `v0.1.9` and pushes. The tag
|
|
135
173
|
triggers `.github/workflows/release.yml`, which does the rest on a macOS
|
|
136
174
|
runner: smoke-tests the CLI, builds and zips the app, creates the GitHub
|
|
137
175
|
release, publishes to npm (trusted publishing β no token stored), and commits
|
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
|
|
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
|
|
35
|
-
the desktop apps and CLIs installed on this machine β nothing
|
|
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)
|
|
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,
|
|
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
|
-
|
|
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
|
|
308
|
-
if (
|
|
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
|
-
|
|
311
|
-
|
|
312
|
-
|
|
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}
|
|
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
|
|
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));
|
|
@@ -400,8 +455,14 @@ const COMMANDS = {
|
|
|
400
455
|
|
|
401
456
|
async skill({ positional, flags }) {
|
|
402
457
|
if (positional[0] !== 'install') fail('usage: sage skill install [--project]');
|
|
403
|
-
|
|
404
|
-
|
|
458
|
+
// The npm package bundles the skill at cli/skill/; a repo checkout keeps
|
|
459
|
+
// the canonical copy at skills/ (where skills.sh discovery finds it).
|
|
460
|
+
const candidates = [
|
|
461
|
+
join(ROOT, 'skill', 'sage', 'SKILL.md'),
|
|
462
|
+
join(ROOT, '..', 'skills', 'sage', 'SKILL.md'),
|
|
463
|
+
];
|
|
464
|
+
const source = candidates.find((p) => existsSync(p));
|
|
465
|
+
if (!source) fail(`bundled skill not found (looked in ${candidates.join(', ')})`);
|
|
405
466
|
const targetDir = flags.project
|
|
406
467
|
? join(process.cwd(), '.agents', 'skills', 'sage')
|
|
407
468
|
: join(homedir(), '.agents', 'skills', 'sage');
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@thedevdavid/sage",
|
|
3
|
-
"version": "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",
|
package/skill/sage/SKILL.md
CHANGED
|
@@ -1,61 +1,76 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: sage
|
|
3
|
-
description: Check LLM API usage, spend,
|
|
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
|
|
6
|
+
# sage β LLM usage, quota & billing-cycle checks
|
|
7
7
|
|
|
8
|
-
`sage` is a local-only CLI that reports
|
|
9
|
-
|
|
10
|
-
in `~/.sage
|
|
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
|
|
16
|
-
- "Check my Kimi balance."
|
|
17
|
-
- "How much of my Claude Max / Codex / Kimi Code / Cursor subscription
|
|
18
|
-
- "When does my weekly
|
|
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
|
-
##
|
|
21
|
+
## Run the CLI
|
|
21
22
|
|
|
22
|
-
|
|
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
|
|
27
|
-
sage usage
|
|
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
|
|
32
|
+
If `sage` is not on `PATH`, run `bunx @thedevdavid/sage ...`.
|
|
32
33
|
|
|
33
|
-
|
|
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
|
-
|
|
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
|
-
|
|
45
|
-
|
|
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
|
|
59
|
+
sage add gemini --project PROJECT_ID --adc --billing-table PROJECT.DATASET.TABLE
|
|
49
60
|
```
|
|
50
61
|
|
|
51
|
-
|
|
62
|
+
## Provider capability bounds
|
|
52
63
|
|
|
53
|
-
|
|
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
|
-
|
|
61
|
-
|
|
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
|
+
}
|
package/src/providers/index.js
CHANGED
|
@@ -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
|
};
|