@thedevdavid/sage 0.1.1
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/LICENSE +21 -0
- package/README.md +123 -0
- package/bin/sage.js +406 -0
- package/package.json +38 -0
- package/skill/sage/SKILL.md +59 -0
- package/src/config.js +43 -0
- package/src/cycle.js +41 -0
- package/src/http.js +29 -0
- package/src/prompt.js +20 -0
- package/src/providers/anthropic.js +38 -0
- package/src/providers/index.js +15 -0
- package/src/providers/kimi.js +27 -0
- package/src/providers/openai.js +40 -0
- package/src/subscriptions/claude.js +119 -0
- package/src/subscriptions/codex.js +94 -0
- package/src/subscriptions/cursor.js +68 -0
- package/src/subscriptions/index.js +29 -0
- package/src/subscriptions/kimi.js +91 -0
- package/src/util.js +26 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 David Levai
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
# πΏ sage
|
|
2
|
+
|
|
3
|
+
Know your LLM API billing cycle and usage. Nothing else.
|
|
4
|
+
|
|
5
|
+
sage is a tiny, open-source, **local-only** toolkit that shows your current
|
|
6
|
+
billing cycle and spend/balance for **OpenAI**, **Anthropic (Claude)**, and
|
|
7
|
+
**Kimi (Moonshot)** API keys. No signup, no server, no database, no telemetry β
|
|
8
|
+
everything lives in `~/.sage/` on your machine.
|
|
9
|
+
|
|
10
|
+
Three ways to use it, one shared local store:
|
|
11
|
+
|
|
12
|
+
| Piece | What it is |
|
|
13
|
+
| --- | --- |
|
|
14
|
+
| **CLI** (`cli/`) | Zero-dependency CLI (runs on Bun or Node): `bunx @thedevdavid/sage status` |
|
|
15
|
+
| **macOS app** (`sage/`) | Menu bar app built from the included Xcode project |
|
|
16
|
+
| **Agent skill** (`cli/skill/sage/`) | Teaches coding agents to answer usage questions via the CLI |
|
|
17
|
+
| **Website** (`site/`) | This product's single-page static site |
|
|
18
|
+
|
|
19
|
+
## Quick start
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
bunx @thedevdavid/sage add openai # or anthropic, kimi β prompts securely for your key
|
|
23
|
+
bunx @thedevdavid/sage status
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
```
|
|
27
|
+
cycle: day 12/31 Β· resets 2026-09-01 (19d left)
|
|
28
|
+
openai $14.20 spent this cycle
|
|
29
|
+
anthropic key valid Β· admin key needed for spend
|
|
30
|
+
kimi 38.44 CNY balance
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## What each provider can report
|
|
34
|
+
|
|
35
|
+
sage never invents numbers β provider APIs differ a lot:
|
|
36
|
+
|
|
37
|
+
- **Kimi (Moonshot)**: account balance via `/v1/users/me/balance` with a regular key.
|
|
38
|
+
- **OpenAI**: regular key β validity only. Add an **admin key** for per-cycle
|
|
39
|
+
spend (`/v1/organization/costs`).
|
|
40
|
+
- **Anthropic**: regular key β validity only. Add an **admin key**
|
|
41
|
+
(`sk-ant-adminβ¦`) for per-cycle spend (`/v1/organizations/cost_report`).
|
|
42
|
+
|
|
43
|
+
No provider exposes your actual billing cycle via API, so sage anchors the
|
|
44
|
+
cycle to a monthly reset day you choose:
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
sage cycle --set-reset-day 15
|
|
48
|
+
```
|
|
49
|
+
|
|
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: if the Claude Code, Codex, or Kimi Code CLI β or the
|
|
65
|
+
Cursor editor β is signed in on the machine, sage auto-detects its local
|
|
66
|
+
credentials (`~/.claude` Keychain item, `~/.codex/auth.json`,
|
|
67
|
+
`~/.kimi-code/credentials/kimi-code.json`, Cursor's `state.vscdb`) and queries
|
|
68
|
+
the same backend endpoints those tools use. It is strictly read-only β sage
|
|
69
|
+
never refreshes tokens (rotation would race the tools). If a session expires,
|
|
70
|
+
sage tells you to open the respective tool once to refresh it. Env overrides:
|
|
71
|
+
`CLAUDE_CODE_OAUTH_TOKEN`, `CODEX_HOME`, `KIMI_CODE_API_KEY`.
|
|
72
|
+
|
|
73
|
+
## CLI commands
|
|
74
|
+
|
|
75
|
+
```
|
|
76
|
+
sage status [--json] cycle + usage for all providers
|
|
77
|
+
sage add <provider> [--key K] [--admin-key K]
|
|
78
|
+
sage remove <provider>
|
|
79
|
+
sage usage [provider] [--json]
|
|
80
|
+
sage cycle [--set-reset-day N]
|
|
81
|
+
sage skill install [--project] install the agent skill
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
`--json` output is stable and agent/script-friendly.
|
|
85
|
+
|
|
86
|
+
## Local storage
|
|
87
|
+
|
|
88
|
+
- `~/.sage/config.json` β keys + cycle reset day, written `chmod 600`. Shared by
|
|
89
|
+
the CLI and the menu bar app (you can add keys from either).
|
|
90
|
+
- `~/.sage/cache.json` β last successful fetch per provider, so the menu bar
|
|
91
|
+
app and offline runs still show something (marked as cached).
|
|
92
|
+
- The web tool stores the same data in your browser's `localStorage` instead
|
|
93
|
+
(`sage:config` / `sage:cache`) β it never touches the filesystem.
|
|
94
|
+
|
|
95
|
+
## macOS menu bar app
|
|
96
|
+
|
|
97
|
+
```bash
|
|
98
|
+
open sage.xcodeproj # build & run (macOS 26+, Xcode 26+)
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
A leaf appears in your menu bar with cycle progress and per-provider usage.
|
|
102
|
+
Add keys directly from the app ("Add key" β paste, validates on save) or from
|
|
103
|
+
the CLI β both share `~/.sage/`. It refreshes every 15 minutes.
|
|
104
|
+
|
|
105
|
+
## Agent skill
|
|
106
|
+
|
|
107
|
+
```bash
|
|
108
|
+
bunx @thedevdavid/sage skill install # β ~/.agents/skills/sage/SKILL.md
|
|
109
|
+
bunx @thedevdavid/sage skill install --project # β ./.agents/skills/sage/SKILL.md
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
Your coding agent then knows to run `sage status --json` when you ask
|
|
113
|
+
about API spend or cycle status β without ever reading your keys.
|
|
114
|
+
|
|
115
|
+
## Development
|
|
116
|
+
|
|
117
|
+
- CLI: `bun cli/bin/sage.js --help` (Bun or Node β₯ 18, no dependencies, no build step).
|
|
118
|
+
- App: `xcodebuild -project sage.xcodeproj -scheme sage -destination 'platform=macOS' build`
|
|
119
|
+
- Site: `python3 -m http.server 8080 -d site` β one static `index.html`, no build step.
|
|
120
|
+
|
|
121
|
+
## License
|
|
122
|
+
|
|
123
|
+
MIT
|
package/bin/sage.js
ADDED
|
@@ -0,0 +1,406 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFileSync, copyFileSync, mkdirSync, existsSync } from 'node:fs';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { dirname, join } from 'node:path';
|
|
5
|
+
import { homedir } from 'node:os';
|
|
6
|
+
|
|
7
|
+
import { loadConfig, saveConfig, loadCache, saveCache } from '../src/config.js';
|
|
8
|
+
import { currentCycle } from '../src/cycle.js';
|
|
9
|
+
import { PROVIDERS, PROVIDER_NAMES, isProvider } from '../src/providers/index.js';
|
|
10
|
+
import { SUBSCRIPTIONS, SUBSCRIPTION_NAMES, sortWindows } from '../src/subscriptions/index.js';
|
|
11
|
+
import { promptSecret } from '../src/prompt.js';
|
|
12
|
+
|
|
13
|
+
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
|
|
14
|
+
const VERSION = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8')).version;
|
|
15
|
+
|
|
16
|
+
const HELP = `sage β local-only usage & billing-cycle tracker for LLM API keys and subscriptions
|
|
17
|
+
|
|
18
|
+
Usage: sage <command> [options]
|
|
19
|
+
|
|
20
|
+
Commands:
|
|
21
|
+
status [--json] Cycle + usage for API keys and subscriptions (default)
|
|
22
|
+
add <provider> Add an API key (openai, anthropic, kimi)
|
|
23
|
+
[--key K] [--admin-key K] (prompts securely when flags are omitted)
|
|
24
|
+
remove <provider> Remove an API-key provider
|
|
25
|
+
usage [name] [--json] Detailed usage for one source or all of them
|
|
26
|
+
(names: ${PROVIDER_NAMES.join(', ')}, ${SUBSCRIPTION_NAMES.join(', ')})
|
|
27
|
+
cycle [--set-reset-day N] Show billing cycle, or set the monthly reset day
|
|
28
|
+
skill install [--project] Install the sage agent skill (~/.agents/skills,
|
|
29
|
+
or ./.agents/skills with --project)
|
|
30
|
+
help Show this help
|
|
31
|
+
version Show version
|
|
32
|
+
|
|
33
|
+
API keys live in ~/.sage/config.json (chmod 600).
|
|
34
|
+
Subscriptions (Claude Max, ChatGPT/Codex, Kimi Code) are auto-detected from
|
|
35
|
+
the CLIs installed on this machine β read-only, nothing to configure.
|
|
36
|
+
No account, no telemetry, no cloud.
|
|
37
|
+
`;
|
|
38
|
+
|
|
39
|
+
function fail(message) {
|
|
40
|
+
console.error(`error: ${message}`);
|
|
41
|
+
process.exit(1);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function parseFlags(args) {
|
|
45
|
+
const flags = {};
|
|
46
|
+
const positional = [];
|
|
47
|
+
for (let i = 0; i < args.length; i++) {
|
|
48
|
+
const arg = args[i];
|
|
49
|
+
if (arg.startsWith('--')) {
|
|
50
|
+
const name = arg.slice(2);
|
|
51
|
+
const next = args[i + 1];
|
|
52
|
+
if (next !== undefined && !next.startsWith('--')) {
|
|
53
|
+
flags[name] = next;
|
|
54
|
+
i++;
|
|
55
|
+
} else {
|
|
56
|
+
flags[name] = true;
|
|
57
|
+
}
|
|
58
|
+
} else {
|
|
59
|
+
positional.push(arg);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return { flags, positional };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// --- API-key providers ---
|
|
66
|
+
|
|
67
|
+
async function collectApiStatus(config, cycle, cache) {
|
|
68
|
+
const names = PROVIDER_NAMES.filter((n) => config.providers[n]);
|
|
69
|
+
const results = {};
|
|
70
|
+
await Promise.all(
|
|
71
|
+
names.map(async (name) => {
|
|
72
|
+
try {
|
|
73
|
+
const status = await PROVIDERS[name].fetchStatus(config.providers[name], cycle);
|
|
74
|
+
status.fetchedAt = new Date().toISOString();
|
|
75
|
+
cache.api[name] = status;
|
|
76
|
+
results[name] = status;
|
|
77
|
+
} catch (err) {
|
|
78
|
+
const cached = cache.api[name];
|
|
79
|
+
results[name] = cached
|
|
80
|
+
? { ...cached, stale: true, error: err.message }
|
|
81
|
+
: { ok: false, usageAvailable: false, usage: null, note: null, error: err.message };
|
|
82
|
+
}
|
|
83
|
+
}),
|
|
84
|
+
);
|
|
85
|
+
return { results, configured: names };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// --- Subscriptions (auto-detected from local CLI credentials) ---
|
|
89
|
+
|
|
90
|
+
async function collectSubscriptionStatus(cache) {
|
|
91
|
+
const detected = [];
|
|
92
|
+
for (const name of SUBSCRIPTION_NAMES) {
|
|
93
|
+
try {
|
|
94
|
+
if (await SUBSCRIPTIONS[name].available()) detected.push(name);
|
|
95
|
+
} catch {
|
|
96
|
+
// detection failure = not available
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const results = {};
|
|
101
|
+
await Promise.all(
|
|
102
|
+
detected.map(async (name) => {
|
|
103
|
+
const sub = SUBSCRIPTIONS[name];
|
|
104
|
+
const cached = cache.subscriptions[name];
|
|
105
|
+
const age = cached?.fetchedAt ? Date.now() - new Date(cached.fetchedAt).getTime() : Infinity;
|
|
106
|
+
if (cached && age < sub.minIntervalMs) {
|
|
107
|
+
results[name] = { ...cached, windows: sortWindows(cached.windows) };
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
try {
|
|
111
|
+
const status = await sub.fetchStatus();
|
|
112
|
+
status.fetchedAt = new Date().toISOString();
|
|
113
|
+
status.windows = sortWindows(status.windows);
|
|
114
|
+
cache.subscriptions[name] = status;
|
|
115
|
+
results[name] = status;
|
|
116
|
+
} catch (err) {
|
|
117
|
+
results[name] = cached
|
|
118
|
+
? { ...cached, windows: sortWindows(cached.windows), stale: true, error: err.message }
|
|
119
|
+
: { kind: 'subscription', ok: false, plan: null, windows: [], credits: null, note: null, error: err.message };
|
|
120
|
+
}
|
|
121
|
+
}),
|
|
122
|
+
);
|
|
123
|
+
return { results, detected };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function collectStatus() {
|
|
127
|
+
const config = loadConfig();
|
|
128
|
+
const cycle = currentCycle(config.cycleResetDay);
|
|
129
|
+
const cache = loadCache();
|
|
130
|
+
const [api, subs] = await Promise.all([
|
|
131
|
+
collectApiStatus(config, cycle, cache),
|
|
132
|
+
collectSubscriptionStatus(cache),
|
|
133
|
+
]);
|
|
134
|
+
saveCache(cache);
|
|
135
|
+
return { cycle, api: api.results, subscriptions: subs.results, configured: api.configured, detected: subs.detected };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// --- formatting ---
|
|
139
|
+
|
|
140
|
+
const TTY = process.stdout.isTTY;
|
|
141
|
+
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 };
|
|
143
|
+
const paint = (color, text) => (TTY ? ANSI[color] + text + ANSI.reset : text);
|
|
144
|
+
const paint256 = (n, text) => (TTY ? `\x1b[38;5;${n}m${text}\x1b[0m` : text);
|
|
145
|
+
const bold = (text) => paint('bold', text);
|
|
146
|
+
const dim = (text) => paint('dim', text);
|
|
147
|
+
const staleTag = (status) => (status?.stale ? ` ${paint('yellow', 'Β· cached')}` : '');
|
|
148
|
+
|
|
149
|
+
// What matters at a glance: how much room is LEFT.
|
|
150
|
+
function usageBar(usedPercent, width = 16) {
|
|
151
|
+
const used = Math.min(100, Math.max(0, Number(usedPercent) || 0));
|
|
152
|
+
const left = 100 - used;
|
|
153
|
+
const filled = Math.round((used / 100) * width);
|
|
154
|
+
const color = left <= 10 ? 'red' : left <= 35 ? 'yellow' : 'green';
|
|
155
|
+
return paint(color, 'β'.repeat(filled) + 'β'.repeat(width - filled));
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function formatUsage(status) {
|
|
159
|
+
if (!status) return 'no data yet β run `sage status` online once';
|
|
160
|
+
if (status.error) return paint('red', `error: ${status.error}`);
|
|
161
|
+
if (!status.ok) return 'invalid key';
|
|
162
|
+
const u = status.usage;
|
|
163
|
+
if (u && u.spent != null) return `$${u.spent.toFixed(2)} spent this cycle`;
|
|
164
|
+
if (u && u.balance != null) return `${u.balance} ${u.currency} balance`;
|
|
165
|
+
return status.note ?? 'no usage data';
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function formatReset(resetsAt) {
|
|
169
|
+
if (!resetsAt) return '';
|
|
170
|
+
const date = new Date(resetsAt);
|
|
171
|
+
const diffMs = date.getTime() - Date.now();
|
|
172
|
+
if (diffMs <= 0) return 'resets soon';
|
|
173
|
+
const hours = Math.floor(diffMs / 3_600_000);
|
|
174
|
+
const minutes = Math.round((diffMs % 3_600_000) / 60_000);
|
|
175
|
+
if (hours >= 48) return date.toISOString().slice(0, 10);
|
|
176
|
+
if (hours >= 1) return `${hours}h ${minutes}m`;
|
|
177
|
+
return `${minutes}m`;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function cleanLabel(label) {
|
|
181
|
+
return String(label).replace('(all models)', '').trim();
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function printSubscription(name, status, labelWidth) {
|
|
185
|
+
const brand = BRAND[name] ?? 15;
|
|
186
|
+
const cached = status?.stale ? ` ${paint('yellow', 'Β· cached')}` : '';
|
|
187
|
+
console.log(`${paint256(brand, 'β')} ${paint256(brand, bold(name))}${status?.plan ? dim(` Β· ${status.plan}`) : ''}${cached}`);
|
|
188
|
+
if (!status) {
|
|
189
|
+
console.log(` ${dim('no data yet')}`);
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
// An error (e.g. expired session) always wins over stale cached numbers β
|
|
193
|
+
// showing old percentages reads as live data.
|
|
194
|
+
if (status.error) {
|
|
195
|
+
console.log(` ${paint('red', status.error)}`);
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
const windows = status.windows ?? [];
|
|
199
|
+
for (const w of windows) {
|
|
200
|
+
const left = Math.max(0, Math.round(100 - (Number(w.usedPercent) || 0)));
|
|
201
|
+
const reset = formatReset(w.resetsAt);
|
|
202
|
+
console.log(
|
|
203
|
+
` ${cleanLabel(w.label).padEnd(labelWidth)} ${usageBar(w.usedPercent)} ${String(left + '% left').padStart(8)}${reset ? dim(` Β· ${reset}`) : ''}`,
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
if (status.credits?.balance != null) console.log(` ${'credits'.padEnd(12)} $${status.credits.balance}`);
|
|
207
|
+
if (status.credits?.used != null) {
|
|
208
|
+
console.log(` ${'extra usage'.padEnd(12)} $${status.credits.used}${status.credits.limit != null ? `/$${status.credits.limit}` : ''}`);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function printStatus({ cycle, api, subscriptions, configured, detected }) {
|
|
213
|
+
if (configured.length === 0 && detected.length === 0) {
|
|
214
|
+
console.log('No API keys configured and no subscriptions detected.');
|
|
215
|
+
console.log('Add a key: sage add openai (or anthropic, kimi)');
|
|
216
|
+
console.log('Subscriptions appear automatically once Claude Code, Codex, or Kimi Code is signed in.');
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
// One global label column so bars and dates align across providers.
|
|
220
|
+
const labelWidth = Math.max(
|
|
221
|
+
8,
|
|
222
|
+
...detected.flatMap((name) => (subscriptions[name]?.windows ?? []).map((w) => cleanLabel(w.label).length)),
|
|
223
|
+
);
|
|
224
|
+
for (const name of detected) {
|
|
225
|
+
printSubscription(name, subscriptions[name], labelWidth);
|
|
226
|
+
}
|
|
227
|
+
if (configured.length > 0) {
|
|
228
|
+
if (detected.length > 0) console.log();
|
|
229
|
+
console.log(bold('API keys'));
|
|
230
|
+
for (const name of configured) {
|
|
231
|
+
console.log(` ${name.padEnd(10)} ${formatUsage(api[name])}${staleTag(api[name])}`);
|
|
232
|
+
}
|
|
233
|
+
console.log(dim(` cycle: day ${cycle.dayOfCycle}/${cycle.daysInCycle} Β· resets ${cycle.end.slice(0, 10)} (${cycle.daysLeft}d left)`));
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// Minimal spinner so live fetches feel instant (TTY only).
|
|
238
|
+
function startSpinner(text = 'fetching usage') {
|
|
239
|
+
if (!TTY) return () => {};
|
|
240
|
+
const frames = ['β ', 'β ', 'β Ή', 'β Έ', 'β Ό', 'β ΄', 'β ¦', 'β §', 'β ', 'β '];
|
|
241
|
+
let i = 0;
|
|
242
|
+
const id = setInterval(() => {
|
|
243
|
+
process.stderr.write(`\r${dim(frames[i++ % frames.length] + ' ' + text + 'β¦')}`);
|
|
244
|
+
}, 80);
|
|
245
|
+
return () => {
|
|
246
|
+
clearInterval(id);
|
|
247
|
+
process.stderr.write(`\r${' '.repeat(text.length + 6)}\r`);
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function printJson(payload) {
|
|
252
|
+
console.log(JSON.stringify(payload, null, 2));
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
const ALL_NAMES = [...PROVIDER_NAMES, ...SUBSCRIPTION_NAMES];
|
|
256
|
+
|
|
257
|
+
const COMMANDS = {
|
|
258
|
+
async status({ flags }) {
|
|
259
|
+
const stop = flags.json ? () => {} : startSpinner();
|
|
260
|
+
const data = await collectStatus();
|
|
261
|
+
stop();
|
|
262
|
+
if (flags.json) printJson({ cycle: data.cycle, api: data.api, subscriptions: data.subscriptions });
|
|
263
|
+
else printStatus(data);
|
|
264
|
+
},
|
|
265
|
+
|
|
266
|
+
async add({ positional, flags }) {
|
|
267
|
+
const [name] = positional;
|
|
268
|
+
if (!name || !isProvider(name)) fail(`unknown provider "${name ?? ''}" β use one of: ${PROVIDER_NAMES.join(', ')}`);
|
|
269
|
+
|
|
270
|
+
const apiKey = flags.key ?? (await promptSecret(`API key for ${name}: `));
|
|
271
|
+
if (!apiKey) fail('no API key provided');
|
|
272
|
+
|
|
273
|
+
const providerConfig = { apiKey };
|
|
274
|
+
const adminKey = flags['admin-key'] ?? (await promptSecret(`Admin key for ${name} (optional, Enter to skip): `));
|
|
275
|
+
if (adminKey) providerConfig.adminKey = adminKey;
|
|
276
|
+
|
|
277
|
+
const config = loadConfig();
|
|
278
|
+
config.providers[name] = { ...config.providers[name], ...providerConfig };
|
|
279
|
+
saveConfig(config);
|
|
280
|
+
|
|
281
|
+
console.log(`validating ${name} key...`);
|
|
282
|
+
try {
|
|
283
|
+
const cycle = currentCycle(config.cycleResetDay);
|
|
284
|
+
const status = await PROVIDERS[name].fetchStatus(config.providers[name], cycle);
|
|
285
|
+
const cache = loadCache();
|
|
286
|
+
status.fetchedAt = new Date().toISOString();
|
|
287
|
+
cache.api[name] = status;
|
|
288
|
+
saveCache(cache);
|
|
289
|
+
console.log(`${name} added Β· ${formatUsage(status)}`);
|
|
290
|
+
} catch (err) {
|
|
291
|
+
console.log(`${name} saved, but validation failed: ${err.message}`);
|
|
292
|
+
console.log('The key is stored; `sage status` will retry.');
|
|
293
|
+
}
|
|
294
|
+
},
|
|
295
|
+
|
|
296
|
+
async remove({ positional }) {
|
|
297
|
+
const [name] = positional;
|
|
298
|
+
if (!name || !isProvider(name)) fail(`unknown provider "${name ?? ''}" β use one of: ${PROVIDER_NAMES.join(', ')}`);
|
|
299
|
+
const config = loadConfig();
|
|
300
|
+
if (!config.providers[name]) fail(`${name} is not configured`);
|
|
301
|
+
delete config.providers[name];
|
|
302
|
+
saveConfig(config);
|
|
303
|
+
const cache = loadCache();
|
|
304
|
+
delete cache.api[name];
|
|
305
|
+
saveCache(cache);
|
|
306
|
+
console.log(`${name} removed`);
|
|
307
|
+
},
|
|
308
|
+
|
|
309
|
+
async usage({ positional, flags }) {
|
|
310
|
+
const [name] = positional;
|
|
311
|
+
if (name && !ALL_NAMES.includes(name)) {
|
|
312
|
+
fail(`unknown source "${name}" β use one of: ${ALL_NAMES.join(', ')}`);
|
|
313
|
+
}
|
|
314
|
+
const stop = flags.json ? () => {} : startSpinner();
|
|
315
|
+
const data = await collectStatus();
|
|
316
|
+
stop();
|
|
317
|
+
if (flags.json) {
|
|
318
|
+
if (!name) {
|
|
319
|
+
printJson({ cycle: data.cycle, api: data.api, subscriptions: data.subscriptions });
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
const status = data.api[name] ?? data.subscriptions[name] ?? null;
|
|
323
|
+
printJson({ cycle: data.cycle, [name]: status });
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
if (name) {
|
|
327
|
+
const isApi = isProvider(name);
|
|
328
|
+
const status = data.api[name] ?? data.subscriptions[name];
|
|
329
|
+
if (isApi && !data.configured.includes(name)) fail(`${name} is not configured β run: sage add ${name}`);
|
|
330
|
+
if (!isApi && !data.detected.includes(name)) fail(`${name} was not detected on this machine`);
|
|
331
|
+
if (isApi) {
|
|
332
|
+
console.log(`${name}: ${formatUsage(status)}`);
|
|
333
|
+
if (status?.note) console.log(dim(`note: ${status.note}`));
|
|
334
|
+
} else {
|
|
335
|
+
const width = Math.max(8, ...(status?.windows ?? []).map((w) => cleanLabel(w.label).length));
|
|
336
|
+
printSubscription(name, status, width);
|
|
337
|
+
}
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
printStatus(data);
|
|
341
|
+
},
|
|
342
|
+
|
|
343
|
+
async cycle({ flags }) {
|
|
344
|
+
const config = loadConfig();
|
|
345
|
+
if (flags['set-reset-day'] !== undefined) {
|
|
346
|
+
const day = Number(flags['set-reset-day']);
|
|
347
|
+
if (!Number.isInteger(day) || day < 1 || day > 31) fail('reset day must be an integer between 1 and 31');
|
|
348
|
+
config.cycleResetDay = day;
|
|
349
|
+
saveConfig(config);
|
|
350
|
+
console.log(`cycle reset day set to ${day}`);
|
|
351
|
+
return;
|
|
352
|
+
}
|
|
353
|
+
const cycle = currentCycle(config.cycleResetDay);
|
|
354
|
+
if (flags.json) {
|
|
355
|
+
printJson(cycle);
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
console.log(`reset day: ${cycle.resetDay} of each month`);
|
|
359
|
+
console.log(`cycle start: ${cycle.start.slice(0, 10)}`);
|
|
360
|
+
console.log(`cycle end: ${cycle.end.slice(0, 10)}`);
|
|
361
|
+
console.log(`today: day ${cycle.dayOfCycle} of ${cycle.daysInCycle} (${cycle.daysLeft} days left)`);
|
|
362
|
+
},
|
|
363
|
+
|
|
364
|
+
async skill({ positional, flags }) {
|
|
365
|
+
if (positional[0] !== 'install') fail('usage: sage skill install [--project]');
|
|
366
|
+
const source = join(ROOT, 'skill', 'sage', 'SKILL.md');
|
|
367
|
+
if (!existsSync(source)) fail(`bundled skill not found at ${source}`);
|
|
368
|
+
const targetDir = flags.project
|
|
369
|
+
? join(process.cwd(), '.agents', 'skills', 'sage')
|
|
370
|
+
: join(homedir(), '.agents', 'skills', 'sage');
|
|
371
|
+
mkdirSync(targetDir, { recursive: true });
|
|
372
|
+
copyFileSync(source, join(targetDir, 'SKILL.md'));
|
|
373
|
+
console.log(`agent skill installed to ${join(targetDir, 'SKILL.md')}`);
|
|
374
|
+
},
|
|
375
|
+
|
|
376
|
+
async help() {
|
|
377
|
+
process.stdout.write(HELP);
|
|
378
|
+
},
|
|
379
|
+
|
|
380
|
+
async version() {
|
|
381
|
+
console.log(VERSION);
|
|
382
|
+
},
|
|
383
|
+
};
|
|
384
|
+
|
|
385
|
+
async function main() {
|
|
386
|
+
const args = process.argv.slice(2);
|
|
387
|
+
if (args.includes('--help') || args.includes('-h')) {
|
|
388
|
+
process.stdout.write(HELP);
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
if (args.includes('--version') || args.includes('-v')) {
|
|
392
|
+
console.log(VERSION);
|
|
393
|
+
return;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
const [command = 'status', ...rest] = args;
|
|
397
|
+
const handler = COMMANDS[command];
|
|
398
|
+
if (!handler) {
|
|
399
|
+
process.stdout.write(HELP);
|
|
400
|
+
if (command !== 'status') process.exitCode = 1;
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
await handler(parseFlags(rest));
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
main().catch((err) => fail(err.message));
|
package/package.json
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@thedevdavid/sage",
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Local-only usage & billing-cycle tracker for LLM API keys and subscriptions (OpenAI, Anthropic/Claude, Kimi, Cursor).",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"sage": "./bin/sage.js"
|
|
8
|
+
},
|
|
9
|
+
"engines": {
|
|
10
|
+
"node": ">=18"
|
|
11
|
+
},
|
|
12
|
+
"files": [
|
|
13
|
+
"bin",
|
|
14
|
+
"src",
|
|
15
|
+
"skill"
|
|
16
|
+
],
|
|
17
|
+
"keywords": [
|
|
18
|
+
"openai",
|
|
19
|
+
"anthropic",
|
|
20
|
+
"claude",
|
|
21
|
+
"kimi",
|
|
22
|
+
"moonshot",
|
|
23
|
+
"api-usage",
|
|
24
|
+
"billing",
|
|
25
|
+
"cli"
|
|
26
|
+
],
|
|
27
|
+
"license": "MIT",
|
|
28
|
+
"repository": {
|
|
29
|
+
"type": "git",
|
|
30
|
+
"url": "git+https://github.com/thedevdavid/sage.git",
|
|
31
|
+
"directory": "cli"
|
|
32
|
+
},
|
|
33
|
+
"homepage": "https://thedevdavid.github.io/sage/",
|
|
34
|
+
"bugs": "https://github.com/thedevdavid/sage/issues",
|
|
35
|
+
"publishConfig": {
|
|
36
|
+
"access": "public"
|
|
37
|
+
}
|
|
38
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
---
|
|
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.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# sage β LLM usage & billing cycle checks
|
|
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.
|
|
11
|
+
|
|
12
|
+
## When to use
|
|
13
|
+
|
|
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?"
|
|
19
|
+
|
|
20
|
+
## How to use
|
|
21
|
+
|
|
22
|
+
Run the CLI (never read `~/.sage/config.json` yourself β it contains API keys):
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
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
|
|
28
|
+
sage cycle # cycle boundaries and days remaining
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
If `sage` is not on PATH, use `bunx @thedevdavid/sage ...` instead.
|
|
32
|
+
|
|
33
|
+
API-key providers live under `api` in the JSON; subscriptions (Claude Max,
|
|
34
|
+
ChatGPT/Codex, Kimi Code β auto-detected from local CLI credentials) live
|
|
35
|
+
under `subscriptions`, each with `plan` and `windows[]` (`label`,
|
|
36
|
+
`usedPercent`, `resetsAt`). If a subscription shows an "expired session"
|
|
37
|
+
error, tell the user to open the respective CLI once to refresh it β sage is
|
|
38
|
+
read-only and never refreshes tokens itself.
|
|
39
|
+
|
|
40
|
+
## First run / missing provider
|
|
41
|
+
|
|
42
|
+
If a provider is not configured, tell the user to run interactively (key entry
|
|
43
|
+
is a hidden prompt):
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
sage add openai # or anthropic, kimi
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Notes to communicate honestly:
|
|
50
|
+
|
|
51
|
+
- OpenAI and Anthropic only expose spend data with an **admin key**; with a
|
|
52
|
+
regular key sage reports key validity, not spend.
|
|
53
|
+
- Kimi reports account balance (no per-cycle spend API exists).
|
|
54
|
+
- The billing cycle is anchored to a user-set monthly reset day
|
|
55
|
+
(`sage cycle --set-reset-day N`, default 1); no provider exposes the
|
|
56
|
+
real billing cycle via API.
|
|
57
|
+
|
|
58
|
+
If the output shows `stale`/cached data, say so β it means the fetch failed and
|
|
59
|
+
the last known values are being shown.
|
package/src/config.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync } from 'node:fs';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
|
|
5
|
+
const SAGE_DIR = join(homedir(), '.sage');
|
|
6
|
+
const CONFIG_PATH = join(SAGE_DIR, 'config.json');
|
|
7
|
+
const CACHE_PATH = join(SAGE_DIR, 'cache.json');
|
|
8
|
+
|
|
9
|
+
const DEFAULTS = { cycleResetDay: 1, providers: {} };
|
|
10
|
+
|
|
11
|
+
export function loadConfig() {
|
|
12
|
+
if (!existsSync(CONFIG_PATH)) return structuredClone(DEFAULTS);
|
|
13
|
+
try {
|
|
14
|
+
return { ...structuredClone(DEFAULTS), ...JSON.parse(readFileSync(CONFIG_PATH, 'utf8')) };
|
|
15
|
+
} catch {
|
|
16
|
+
return structuredClone(DEFAULTS);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function saveConfig(config) {
|
|
21
|
+
mkdirSync(SAGE_DIR, { recursive: true, mode: 0o700 });
|
|
22
|
+
writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2) + '\n', { mode: 0o600 });
|
|
23
|
+
chmodSync(CONFIG_PATH, 0o600);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function loadCache() {
|
|
27
|
+
if (!existsSync(CACHE_PATH)) return { api: {}, subscriptions: {} };
|
|
28
|
+
try {
|
|
29
|
+
const raw = JSON.parse(readFileSync(CACHE_PATH, 'utf8'));
|
|
30
|
+
if (raw && (raw.api || raw.subscriptions)) {
|
|
31
|
+
return { api: raw.api ?? {}, subscriptions: raw.subscriptions ?? {} };
|
|
32
|
+
}
|
|
33
|
+
// migrate the pre-subscriptions flat shape ({ openai: ..., kimi: ... })
|
|
34
|
+
return { api: raw ?? {}, subscriptions: {} };
|
|
35
|
+
} catch {
|
|
36
|
+
return { api: {}, subscriptions: {} };
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function saveCache(cache) {
|
|
41
|
+
mkdirSync(SAGE_DIR, { recursive: true, mode: 0o700 });
|
|
42
|
+
writeFileSync(CACHE_PATH, JSON.stringify(cache, null, 2) + '\n', { mode: 0o600 });
|
|
43
|
+
}
|
package/src/cycle.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// Billing-cycle math anchored on a monthly reset day (1-31).
|
|
2
|
+
// No provider exposes the billing cycle via API, so the user picks the reset
|
|
3
|
+
// day (default: 1st of the month) and everything is computed locally.
|
|
4
|
+
|
|
5
|
+
function startOfDay(d) {
|
|
6
|
+
return new Date(d.getFullYear(), d.getMonth(), d.getDate());
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
function daysInMonth(year, month) {
|
|
10
|
+
return new Date(year, month + 1, 0).getDate();
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
// The reset date within a given month; clamps e.g. resetDay 31 to Feb 28/29.
|
|
14
|
+
function resetDate(year, month, resetDay) {
|
|
15
|
+
return new Date(year, month, Math.min(resetDay, daysInMonth(year, month)));
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const DAY_MS = 86_400_000;
|
|
19
|
+
|
|
20
|
+
export function currentCycle(resetDay = 1, now = new Date()) {
|
|
21
|
+
const today = startOfDay(now);
|
|
22
|
+
let start = resetDate(today.getFullYear(), today.getMonth(), resetDay);
|
|
23
|
+
if (today < start) {
|
|
24
|
+
const prevMonth = new Date(today.getFullYear(), today.getMonth() - 1, 1);
|
|
25
|
+
start = resetDate(prevMonth.getFullYear(), prevMonth.getMonth(), resetDay);
|
|
26
|
+
}
|
|
27
|
+
const nextMonth = new Date(start.getFullYear(), start.getMonth() + 1, 1);
|
|
28
|
+
const end = resetDate(nextMonth.getFullYear(), nextMonth.getMonth(), resetDay);
|
|
29
|
+
|
|
30
|
+
const daysInCycle = Math.round((end - start) / DAY_MS);
|
|
31
|
+
const dayOfCycle = Math.round((today - start) / DAY_MS) + 1;
|
|
32
|
+
|
|
33
|
+
return {
|
|
34
|
+
resetDay,
|
|
35
|
+
start: start.toISOString(),
|
|
36
|
+
end: end.toISOString(),
|
|
37
|
+
daysInCycle,
|
|
38
|
+
dayOfCycle,
|
|
39
|
+
daysLeft: daysInCycle - dayOfCycle,
|
|
40
|
+
};
|
|
41
|
+
}
|
package/src/http.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
const TIMEOUT_MS = 10_000;
|
|
2
|
+
|
|
3
|
+
export async function httpJson(url, { headers = {}, method = 'GET', body = undefined } = {}) {
|
|
4
|
+
const controller = new AbortController();
|
|
5
|
+
const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
|
|
6
|
+
try {
|
|
7
|
+
const res = await fetch(url, {
|
|
8
|
+
method,
|
|
9
|
+
headers: body !== undefined ? { 'Content-Type': 'application/json', ...headers } : headers,
|
|
10
|
+
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
11
|
+
signal: controller.signal,
|
|
12
|
+
});
|
|
13
|
+
let json = null;
|
|
14
|
+
try {
|
|
15
|
+
json = await res.json();
|
|
16
|
+
} catch {
|
|
17
|
+
// non-JSON body; leave null
|
|
18
|
+
}
|
|
19
|
+
if (!res.ok) {
|
|
20
|
+
const message = json?.error?.message ?? json?.error ?? `${res.status} ${res.statusText}`;
|
|
21
|
+
const err = new Error(typeof message === 'string' ? message : JSON.stringify(message));
|
|
22
|
+
err.status = res.status;
|
|
23
|
+
throw err;
|
|
24
|
+
}
|
|
25
|
+
return json;
|
|
26
|
+
} finally {
|
|
27
|
+
clearTimeout(timer);
|
|
28
|
+
}
|
|
29
|
+
}
|
package/src/prompt.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { createInterface } from 'node:readline';
|
|
2
|
+
|
|
3
|
+
// Prompt without echoing input (for API keys).
|
|
4
|
+
// Non-interactive (piped/CI): resolves to '' immediately β use --key flags instead.
|
|
5
|
+
export function promptSecret(question) {
|
|
6
|
+
if (!process.stdin.isTTY) return Promise.resolve('');
|
|
7
|
+
return new Promise((resolve) => {
|
|
8
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: true });
|
|
9
|
+
const originalWrite = rl._writeToOutput;
|
|
10
|
+
rl._writeToOutput = function (chunk) {
|
|
11
|
+
if (chunk.includes(question)) originalWrite.call(rl, chunk);
|
|
12
|
+
else originalWrite.call(rl, '*');
|
|
13
|
+
};
|
|
14
|
+
rl.question(question, (answer) => {
|
|
15
|
+
rl.close();
|
|
16
|
+
process.stdout.write('\n');
|
|
17
|
+
resolve(answer.trim());
|
|
18
|
+
});
|
|
19
|
+
});
|
|
20
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { httpJson } from '../http.js';
|
|
2
|
+
import { sumBuckets } from '../util.js';
|
|
3
|
+
|
|
4
|
+
const BASE = 'https://api.anthropic.com';
|
|
5
|
+
const VERSION = '2023-06-01';
|
|
6
|
+
|
|
7
|
+
// Anthropic exposes cost data via the Admin API (/v1/organizations/*), which
|
|
8
|
+
// requires an admin key (sk-ant-admin...). A regular key can only be validated.
|
|
9
|
+
export async function fetchStatus({ apiKey, adminKey }, cycle) {
|
|
10
|
+
const auth = (key) => ({ 'x-api-key': key, 'anthropic-version': VERSION });
|
|
11
|
+
|
|
12
|
+
if (apiKey) {
|
|
13
|
+
await httpJson(`${BASE}/v1/models`, { headers: auth(apiKey) });
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
if (!adminKey) {
|
|
17
|
+
return {
|
|
18
|
+
ok: true,
|
|
19
|
+
usageAvailable: false,
|
|
20
|
+
usage: null,
|
|
21
|
+
note: 'key valid Β· add an admin key to see spend (console.anthropic.com β settings β admin keys)',
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const startingAt = encodeURIComponent(cycle.start);
|
|
26
|
+
const endingAt = encodeURIComponent(cycle.end);
|
|
27
|
+
const data = await httpJson(
|
|
28
|
+
`${BASE}/v1/organizations/cost_report?starting_at=${startingAt}&ending_at=${endingAt}`,
|
|
29
|
+
{ headers: auth(adminKey) },
|
|
30
|
+
);
|
|
31
|
+
|
|
32
|
+
return {
|
|
33
|
+
ok: true,
|
|
34
|
+
usageAvailable: true,
|
|
35
|
+
usage: { spent: sumBuckets(data, (r) => r?.cost_usd), currency: 'USD' },
|
|
36
|
+
note: null,
|
|
37
|
+
};
|
|
38
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { fetchStatus as openai } from './openai.js';
|
|
2
|
+
import { fetchStatus as anthropic } from './anthropic.js';
|
|
3
|
+
import { fetchStatus as kimi } from './kimi.js';
|
|
4
|
+
|
|
5
|
+
export const PROVIDERS = {
|
|
6
|
+
openai: { fetchStatus: openai },
|
|
7
|
+
anthropic: { fetchStatus: anthropic },
|
|
8
|
+
kimi: { fetchStatus: kimi },
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
export const PROVIDER_NAMES = Object.keys(PROVIDERS);
|
|
12
|
+
|
|
13
|
+
export function isProvider(name) {
|
|
14
|
+
return Object.hasOwn(PROVIDERS, name);
|
|
15
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { httpJson } from '../http.js';
|
|
2
|
+
|
|
3
|
+
const BASE = 'https://api.moonshot.ai';
|
|
4
|
+
|
|
5
|
+
// Kimi/Moonshot exposes balance directly with a regular API key.
|
|
6
|
+
export async function fetchStatus({ apiKey }) {
|
|
7
|
+
const data = await httpJson(`${BASE}/v1/users/me/balance`, {
|
|
8
|
+
headers: { Authorization: `Bearer ${apiKey}` },
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
const inner = data?.data ?? data;
|
|
12
|
+
const available = Number(inner?.available_balance);
|
|
13
|
+
const voucher = Number(inner?.voucher_balance);
|
|
14
|
+
const cash = Number(inner?.cash_balance);
|
|
15
|
+
|
|
16
|
+
return {
|
|
17
|
+
ok: true,
|
|
18
|
+
usageAvailable: true,
|
|
19
|
+
usage: {
|
|
20
|
+
balance: Number.isFinite(available) ? Math.round(available * 100) / 100 : null,
|
|
21
|
+
voucherBalance: Number.isFinite(voucher) ? Math.round(voucher * 100) / 100 : null,
|
|
22
|
+
cashBalance: Number.isFinite(cash) ? Math.round(cash * 100) / 100 : null,
|
|
23
|
+
currency: inner?.currency ?? 'CNY',
|
|
24
|
+
},
|
|
25
|
+
note: 'balance-based Β· no per-cycle spend API',
|
|
26
|
+
};
|
|
27
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { httpJson } from '../http.js';
|
|
2
|
+
import { sumBuckets } from '../util.js';
|
|
3
|
+
|
|
4
|
+
const BASE = 'https://api.openai.com';
|
|
5
|
+
|
|
6
|
+
// OpenAI only exposes cost/usage data through organization endpoints that
|
|
7
|
+
// require an Admin key. A regular key can only be validated.
|
|
8
|
+
export async function fetchStatus({ apiKey, adminKey }, cycle) {
|
|
9
|
+
const auth = (key) => ({ Authorization: `Bearer ${key}` });
|
|
10
|
+
|
|
11
|
+
if (apiKey) {
|
|
12
|
+
await httpJson(`${BASE}/v1/models`, { headers: auth(apiKey) });
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
if (!adminKey) {
|
|
16
|
+
return {
|
|
17
|
+
ok: true,
|
|
18
|
+
usageAvailable: false,
|
|
19
|
+
usage: null,
|
|
20
|
+
note: 'key valid Β· add an admin key to see spend (platform.openai.com β settings β admin keys)',
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const start = Math.floor(new Date(cycle.start).getTime() / 1000);
|
|
25
|
+
const end = Math.floor(new Date(cycle.end).getTime() / 1000);
|
|
26
|
+
const data = await httpJson(
|
|
27
|
+
`${BASE}/v1/organization/costs?start_time=${start}&end_time=${end}&bucket_width=1d&limit=31`,
|
|
28
|
+
{ headers: auth(adminKey) },
|
|
29
|
+
);
|
|
30
|
+
|
|
31
|
+
const spent = sumBuckets(data, (r) => r?.amount?.value);
|
|
32
|
+
const currency = data?.data?.[0]?.results?.[0]?.amount?.currency ?? 'USD';
|
|
33
|
+
|
|
34
|
+
return {
|
|
35
|
+
ok: true,
|
|
36
|
+
usageAvailable: true,
|
|
37
|
+
usage: { spent, currency },
|
|
38
|
+
note: null,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { promisify } from 'node:util';
|
|
3
|
+
import { readFile } from 'node:fs/promises';
|
|
4
|
+
import { homedir, platform } from 'node:os';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import { httpJson } from '../http.js';
|
|
7
|
+
import { throwIfExpired, rethrowIfUnauthorized } from '../util.js';
|
|
8
|
+
|
|
9
|
+
const execFileP = promisify(execFile);
|
|
10
|
+
const EXPIRED_ERROR = 'Claude Code session expired β open Claude Code once to refresh it';
|
|
11
|
+
|
|
12
|
+
// Claude Code stores OAuth credentials in the macOS Keychain (service
|
|
13
|
+
// "Claude Code-credentials") or ~/.claude/.credentials.json on Linux.
|
|
14
|
+
// We only ever READ the access token β never refresh (rotation races).
|
|
15
|
+
async function readCredentials() {
|
|
16
|
+
if (process.env.CLAUDE_CODE_OAUTH_TOKEN) {
|
|
17
|
+
return { accessToken: process.env.CLAUDE_CODE_OAUTH_TOKEN };
|
|
18
|
+
}
|
|
19
|
+
if (platform() === 'darwin') {
|
|
20
|
+
try {
|
|
21
|
+
const { stdout } = await execFileP(
|
|
22
|
+
'security',
|
|
23
|
+
['find-generic-password', '-s', 'Claude Code-credentials', '-w'],
|
|
24
|
+
{ timeout: 5000 },
|
|
25
|
+
);
|
|
26
|
+
const oauth = JSON.parse(stdout.trim())?.claudeAiOauth;
|
|
27
|
+
if (oauth?.accessToken) return oauth;
|
|
28
|
+
} catch {
|
|
29
|
+
// keychain item missing or unreadable β fall through to file
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
try {
|
|
33
|
+
const raw = await readFile(join(homedir(), '.claude', '.credentials.json'), 'utf8');
|
|
34
|
+
const oauth = JSON.parse(raw)?.claudeAiOauth;
|
|
35
|
+
if (oauth?.accessToken) return oauth;
|
|
36
|
+
} catch {
|
|
37
|
+
// no file
|
|
38
|
+
}
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function planName(oauth) {
|
|
43
|
+
const type = oauth.subscriptionType;
|
|
44
|
+
const tier = oauth.rateLimitTier ?? '';
|
|
45
|
+
const multiplier = tier.match(/(\d+x)/)?.[1];
|
|
46
|
+
if (!type) return null;
|
|
47
|
+
const name = type.charAt(0).toUpperCase() + type.slice(1);
|
|
48
|
+
return multiplier ? `${name} (${multiplier})` : name;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export async function available() {
|
|
52
|
+
return (await readCredentials()) !== null;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export async function fetchStatus() {
|
|
56
|
+
const oauth = await readCredentials();
|
|
57
|
+
if (!oauth) throw new Error('no Claude Code credentials found (is Claude Code installed and signed in?)');
|
|
58
|
+
throwIfExpired(Number(oauth.expiresAt) || null, EXPIRED_ERROR);
|
|
59
|
+
|
|
60
|
+
let data;
|
|
61
|
+
try {
|
|
62
|
+
data = await httpJson('https://api.anthropic.com/api/oauth/usage', {
|
|
63
|
+
headers: {
|
|
64
|
+
Authorization: `Bearer ${oauth.accessToken}`,
|
|
65
|
+
'anthropic-beta': 'oauth-2025-04-20',
|
|
66
|
+
Accept: 'application/json',
|
|
67
|
+
'User-Agent': 'claude-code/2.1.0 (external, cli)',
|
|
68
|
+
},
|
|
69
|
+
});
|
|
70
|
+
} catch (err) {
|
|
71
|
+
rethrowIfUnauthorized(err, EXPIRED_ERROR);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const windows = [];
|
|
75
|
+
const windowMap = [
|
|
76
|
+
['five_hour', 'Session (5h)'],
|
|
77
|
+
['seven_day', 'Weekly (all models)'],
|
|
78
|
+
['seven_day_opus', 'Weekly (Opus)'],
|
|
79
|
+
['seven_day_sonnet', 'Weekly (Sonnet)'],
|
|
80
|
+
];
|
|
81
|
+
for (const [key, label] of windowMap) {
|
|
82
|
+
const w = data?.[key];
|
|
83
|
+
const used = Number(w?.utilization);
|
|
84
|
+
if (w && Number.isFinite(used)) {
|
|
85
|
+
windows.push({ label, usedPercent: used, resetsAt: w.resets_at ?? null });
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
// Newer flat list supersedes the fixed fields when present.
|
|
89
|
+
if (Array.isArray(data?.limits) && windows.length === 0) {
|
|
90
|
+
for (const limit of data.limits) {
|
|
91
|
+
const used = Number(limit?.percent);
|
|
92
|
+
if (Number.isFinite(used)) {
|
|
93
|
+
windows.push({
|
|
94
|
+
label: limit?.scope?.model?.display_name ?? limit?.kind ?? 'limit',
|
|
95
|
+
usedPercent: used,
|
|
96
|
+
resetsAt: limit?.resets_at ?? null,
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
let credits = null;
|
|
103
|
+
if (data?.extra_usage?.is_enabled) {
|
|
104
|
+
credits = {
|
|
105
|
+
used: data.extra_usage.used_credits ?? null,
|
|
106
|
+
limit: data.extra_usage.monthly_limit ?? null,
|
|
107
|
+
currency: data.extra_usage.currency ?? 'USD',
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
return {
|
|
112
|
+
kind: 'subscription',
|
|
113
|
+
ok: true,
|
|
114
|
+
plan: planName(oauth),
|
|
115
|
+
windows,
|
|
116
|
+
credits,
|
|
117
|
+
note: null,
|
|
118
|
+
};
|
|
119
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
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
|
+
// Codex CLI stores ChatGPT OAuth tokens in ~/.codex/auth.json.
|
|
8
|
+
// We only ever READ the access token β never refresh (tokens rotate).
|
|
9
|
+
async function readAuth() {
|
|
10
|
+
const dir = process.env.CODEX_HOME ?? join(homedir(), '.codex');
|
|
11
|
+
try {
|
|
12
|
+
const auth = JSON.parse(await readFile(join(dir, 'auth.json'), 'utf8'));
|
|
13
|
+
if (auth?.tokens?.access_token) return auth.tokens;
|
|
14
|
+
} catch {
|
|
15
|
+
// not installed / not signed in
|
|
16
|
+
}
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// Window labels come from the window's own duration β OpenAI has used both
|
|
21
|
+
// 5-hour and weekly windows in the primary slot.
|
|
22
|
+
function windowLabel(seconds) {
|
|
23
|
+
const s = Number(seconds);
|
|
24
|
+
if (!Number.isFinite(s)) return 'Limit';
|
|
25
|
+
if (s >= 604800) return 'Weekly';
|
|
26
|
+
if (s >= 86400) return `${Math.round(s / 86400)}d window`;
|
|
27
|
+
if (s >= 3600) return `Session (${Math.round(s / 3600)}h)`;
|
|
28
|
+
return `${Math.round(s / 60)}m window`;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function windowFrom(w, fallbackLabel) {
|
|
32
|
+
const used = Number(w?.used_percent);
|
|
33
|
+
if (!w || !Number.isFinite(used)) return null;
|
|
34
|
+
return {
|
|
35
|
+
label: fallbackLabel ?? windowLabel(w.limit_window_seconds),
|
|
36
|
+
usedPercent: used,
|
|
37
|
+
resetsAt: w.reset_at ? new Date(Number(w.reset_at) * 1000).toISOString() : null,
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const EXPIRED_ERROR = 'Codex session expired β run any codex command once to refresh it';
|
|
42
|
+
|
|
43
|
+
function jwtExpMs(token) {
|
|
44
|
+
try {
|
|
45
|
+
const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString());
|
|
46
|
+
return payload?.exp ? Number(payload.exp) * 1000 : null;
|
|
47
|
+
} catch {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export async function available() {
|
|
53
|
+
return (await readAuth()) !== null;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export async function fetchStatus() {
|
|
57
|
+
const tokens = await readAuth();
|
|
58
|
+
if (!tokens) throw new Error('no Codex credentials found (is Codex CLI installed and signed in?)');
|
|
59
|
+
const exp = jwtExpMs(tokens.access_token);
|
|
60
|
+
throwIfExpired(exp, EXPIRED_ERROR);
|
|
61
|
+
|
|
62
|
+
let data;
|
|
63
|
+
try {
|
|
64
|
+
data = await httpJson('https://chatgpt.com/backend-api/wham/usage', {
|
|
65
|
+
headers: {
|
|
66
|
+
Authorization: `Bearer ${tokens.access_token}`,
|
|
67
|
+
...(tokens.account_id ? { 'ChatGPT-Account-Id': tokens.account_id } : {}),
|
|
68
|
+
'User-Agent': 'codex_cli_rs/0.50.0 (sage)',
|
|
69
|
+
Accept: 'application/json',
|
|
70
|
+
},
|
|
71
|
+
});
|
|
72
|
+
} catch (err) {
|
|
73
|
+
rethrowIfUnauthorized(err, EXPIRED_ERROR);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const windows = [];
|
|
77
|
+
const primary = windowFrom(data?.rate_limit?.primary_window, null);
|
|
78
|
+
const secondary = windowFrom(data?.rate_limit?.secondary_window, null);
|
|
79
|
+
if (primary) windows.push(primary);
|
|
80
|
+
if (secondary) windows.push(secondary);
|
|
81
|
+
for (const extra of data?.additional_rate_limits ?? []) {
|
|
82
|
+
const w = windowFrom(extra?.rate_limit?.secondary_window ?? extra?.rate_limit?.primary_window, extra?.limit_name);
|
|
83
|
+
if (w) windows.push(w);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
return {
|
|
87
|
+
kind: 'subscription',
|
|
88
|
+
ok: true,
|
|
89
|
+
plan: data?.plan_type ? data.plan_type.charAt(0).toUpperCase() + data.plan_type.slice(1) : null,
|
|
90
|
+
windows,
|
|
91
|
+
credits: data?.credits?.has_credits ? { balance: data.credits.balance ?? null, currency: 'USD' } : null,
|
|
92
|
+
note: null,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { promisify } from 'node:util';
|
|
3
|
+
import { existsSync } from 'node:fs';
|
|
4
|
+
import { homedir } from 'node:os';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import { httpJson } from '../http.js';
|
|
7
|
+
import { rethrowIfUnauthorized } from '../util.js';
|
|
8
|
+
|
|
9
|
+
const execFileP = promisify(execFile);
|
|
10
|
+
|
|
11
|
+
// Cursor stores its session in the editor's state DB. Read-only: we query
|
|
12
|
+
// the token and call the same dashboard endpoint cursor.com uses.
|
|
13
|
+
function dbPath() {
|
|
14
|
+
return join(homedir(), 'Library', 'Application Support', 'Cursor', 'User', 'globalStorage', 'state.vscdb');
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
async function readCursorAuth(key) {
|
|
18
|
+
try {
|
|
19
|
+
const { stdout } = await execFileP(
|
|
20
|
+
'sqlite3',
|
|
21
|
+
[dbPath(), `SELECT value FROM ItemTable WHERE key='cursorAuth/${key}';`],
|
|
22
|
+
{ timeout: 5000, maxBuffer: 1024 * 1024 },
|
|
23
|
+
);
|
|
24
|
+
return stdout.trim() || null;
|
|
25
|
+
} catch {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export async function available() {
|
|
31
|
+
return existsSync(dbPath()) && (await readCursorAuth('accessToken')) !== null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export async function fetchStatus() {
|
|
35
|
+
const token = await readCursorAuth('accessToken');
|
|
36
|
+
if (!token) throw new Error('no Cursor credentials found (is Cursor installed and signed in?)');
|
|
37
|
+
const membership = await readCursorAuth('stripeMembershipType');
|
|
38
|
+
|
|
39
|
+
let data;
|
|
40
|
+
try {
|
|
41
|
+
data = await httpJson('https://api2.cursor.sh/aiserver.v1.DashboardService/GetCurrentPeriodUsage', {
|
|
42
|
+
method: 'POST',
|
|
43
|
+
body: {},
|
|
44
|
+
headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
|
|
45
|
+
});
|
|
46
|
+
} catch (err) {
|
|
47
|
+
rethrowIfUnauthorized(err, 'Cursor session expired β open Cursor once to refresh it');
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const windows = [];
|
|
51
|
+
const used = Number(data?.planUsage?.totalPercentUsed);
|
|
52
|
+
if (Number.isFinite(used)) {
|
|
53
|
+
windows.push({
|
|
54
|
+
label: 'Monthly',
|
|
55
|
+
usedPercent: Math.round(used * 10) / 10,
|
|
56
|
+
resetsAt: data?.billingCycleEnd ? new Date(Number(data.billingCycleEnd)).toISOString() : null,
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
return {
|
|
61
|
+
kind: 'subscription',
|
|
62
|
+
ok: true,
|
|
63
|
+
plan: membership ? membership.charAt(0).toUpperCase() + membership.slice(1) : null,
|
|
64
|
+
windows,
|
|
65
|
+
credits: null,
|
|
66
|
+
note: null,
|
|
67
|
+
};
|
|
68
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import * as claude from './claude.js';
|
|
2
|
+
import * as codex from './codex.js';
|
|
3
|
+
import * as kimi from './kimi.js';
|
|
4
|
+
import * as cursor from './cursor.js';
|
|
5
|
+
|
|
6
|
+
// Subscription sources are auto-detected from local app/CLI credentials β
|
|
7
|
+
// nothing to configure. Anthropic rate-limits its usage endpoint hard,
|
|
8
|
+
// so each source declares a minimum fetch interval served from cache.
|
|
9
|
+
export const SUBSCRIPTIONS = {
|
|
10
|
+
claude: { fetchStatus: claude.fetchStatus, available: claude.available, minIntervalMs: 5 * 60_000 },
|
|
11
|
+
codex: { fetchStatus: codex.fetchStatus, available: codex.available, minIntervalMs: 60_000 },
|
|
12
|
+
'kimi-code': { fetchStatus: kimi.fetchStatus, available: kimi.available, minIntervalMs: 60_000 },
|
|
13
|
+
cursor: { fetchStatus: cursor.fetchStatus, available: cursor.available, minIntervalMs: 60_000 },
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export const SUBSCRIPTION_NAMES = Object.keys(SUBSCRIPTIONS);
|
|
17
|
+
|
|
18
|
+
// Consistent window ordering across providers: the main quota first
|
|
19
|
+
// (weekly/monthly), then short session/rate-limit windows, then the rest.
|
|
20
|
+
export function windowRank(label) {
|
|
21
|
+
const l = String(label).toLowerCase();
|
|
22
|
+
if (l.includes('week') || l.includes('month') || l.includes('billing')) return 0;
|
|
23
|
+
if (l.includes('session') || /^\d+h /.test(l) || l.includes('rate limit')) return 1;
|
|
24
|
+
return 2;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function sortWindows(windows) {
|
|
28
|
+
return [...(windows ?? [])].sort((a, b) => windowRank(a.label) - windowRank(b.label));
|
|
29
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
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://api.kimi.com/coding/v1';
|
|
8
|
+
|
|
9
|
+
// Kimi Code CLI stores OAuth tokens in ~/.kimi-code/credentials/kimi-code.json
|
|
10
|
+
// (legacy: ~/.kimi/credentials/kimi-code.json). A Kimi Code API key from the
|
|
11
|
+
// console also works. Read-only: we never refresh the rotating token.
|
|
12
|
+
// Note: access tokens expire ~hourly; the CLI refreshes its own on use.
|
|
13
|
+
async function readCredentials() {
|
|
14
|
+
if (process.env.KIMI_CODE_API_KEY) return { token: process.env.KIMI_CODE_API_KEY, expiresAt: null };
|
|
15
|
+
for (const dir of ['.kimi-code', '.kimi']) {
|
|
16
|
+
try {
|
|
17
|
+
const creds = JSON.parse(
|
|
18
|
+
await readFile(join(homedir(), dir, 'credentials', 'kimi-code.json'), 'utf8'),
|
|
19
|
+
);
|
|
20
|
+
if (creds?.access_token) {
|
|
21
|
+
return { token: creds.access_token, expiresAt: creds.expires_at ? Number(creds.expires_at) * 1000 : null };
|
|
22
|
+
}
|
|
23
|
+
} catch {
|
|
24
|
+
// try next location
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function percent(used, limit) {
|
|
31
|
+
const u = Number(used);
|
|
32
|
+
const l = Number(limit);
|
|
33
|
+
if (!Number.isFinite(u) || !Number.isFinite(l) || l <= 0) return null;
|
|
34
|
+
return Math.round((u / l) * 1000) / 10;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function windowLabel(window) {
|
|
38
|
+
const duration = Number(window?.duration);
|
|
39
|
+
const unit = window?.timeUnit ?? '';
|
|
40
|
+
if (!Number.isFinite(duration)) return 'Rate limit';
|
|
41
|
+
const minutes = unit.includes('SECOND') ? duration / 60 : duration;
|
|
42
|
+
if (minutes >= 60 * 24 * 7) return `Weekly rate limit`;
|
|
43
|
+
if (minutes >= 60) return `${Math.round(minutes / 60)}h rate limit`;
|
|
44
|
+
return `${Math.round(minutes)}m rate limit`;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const EXPIRED_ERROR = 'Kimi Code session expired (tokens last ~1h) β run any kimi command once to refresh it';
|
|
48
|
+
|
|
49
|
+
export async function available() {
|
|
50
|
+
return (await readCredentials()) !== null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export async function fetchStatus() {
|
|
54
|
+
const creds = await readCredentials();
|
|
55
|
+
if (!creds) throw new Error('no Kimi Code credentials found (is Kimi Code CLI installed and signed in?)');
|
|
56
|
+
throwIfExpired(creds.expiresAt, EXPIRED_ERROR);
|
|
57
|
+
const headers = { Authorization: `Bearer ${creds.token}`, Accept: 'application/json' };
|
|
58
|
+
|
|
59
|
+
const windows = [];
|
|
60
|
+
let usage;
|
|
61
|
+
let me = null;
|
|
62
|
+
try {
|
|
63
|
+
[usage, me] = await Promise.all([
|
|
64
|
+
httpJson(`${BASE}/usages`, { headers }),
|
|
65
|
+
httpJson(`${BASE}/me`, { headers }).catch(() => null),
|
|
66
|
+
]);
|
|
67
|
+
} catch (err) {
|
|
68
|
+
rethrowIfUnauthorized(err, EXPIRED_ERROR);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const weekly = percent(usage?.usage?.used, usage?.usage?.limit);
|
|
72
|
+
if (weekly !== null) {
|
|
73
|
+
windows.push({
|
|
74
|
+
label: usage.usage.name ?? 'Weekly',
|
|
75
|
+
usedPercent: weekly,
|
|
76
|
+
resetsAt: usage.usage.resetTime ?? usage.usage.reset_at ?? null,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
for (const entry of usage?.limits ?? []) {
|
|
80
|
+
const used = percent(entry?.detail?.used, entry?.detail?.limit);
|
|
81
|
+
if (used !== null) {
|
|
82
|
+
windows.push({
|
|
83
|
+
label: windowLabel(entry?.window),
|
|
84
|
+
usedPercent: used,
|
|
85
|
+
resetsAt: entry?.detail?.resetTime ?? entry?.detail?.reset_at ?? null,
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
return { kind: 'subscription', ok: true, plan: me?.user_level_name ?? null, windows, credits: null, note: null };
|
|
91
|
+
}
|
package/src/util.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// Shared helpers for provider fetchers.
|
|
2
|
+
|
|
3
|
+
// Sum numeric values out of time-bucketed cost responses
|
|
4
|
+
// (OpenAI /organization/costs, Anthropic /organizations/cost_report).
|
|
5
|
+
export function sumBuckets(data, pick) {
|
|
6
|
+
let total = 0;
|
|
7
|
+
for (const bucket of data?.data ?? []) {
|
|
8
|
+
for (const result of bucket?.results ?? []) {
|
|
9
|
+
const value = Number(pick(result));
|
|
10
|
+
if (Number.isFinite(value)) total += value;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
return Math.round(total * 100) / 100;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// Subscription tokens expire; sage never refreshes them (rotation would race
|
|
17
|
+
// the CLI/app that owns them), so surface a clear re-auth instruction instead.
|
|
18
|
+
export function throwIfExpired(expiresAtMs, message) {
|
|
19
|
+
if (expiresAtMs && expiresAtMs < Date.now()) throw new Error(message);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// Map a 401 from a subscription endpoint to the same re-auth instruction.
|
|
23
|
+
export function rethrowIfUnauthorized(err, message) {
|
|
24
|
+
if (err.status === 401) throw new Error(message);
|
|
25
|
+
throw err;
|
|
26
|
+
}
|