@thedevdavid/sage 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -61,14 +61,14 @@ usage windows, and reset times:
61
61
  Monthly ███████████████░ 3% left · 2026-08-06
62
62
  ```
63
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`.
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
72
 
73
73
  ## CLI commands
74
74
 
@@ -100,7 +100,8 @@ open sage.xcodeproj # build & run (macOS 26+, Xcode 26+)
100
100
 
101
101
  A leaf appears in your menu bar with cycle progress and per-provider usage.
102
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.
103
+ the CLI — both share `~/.sage/`. It refreshes every 15 minutes, and the
104
+ **Refresh now** button forces an immediate pull from every detected source.
104
105
 
105
106
  ## Agent skill
106
107
 
@@ -124,10 +125,10 @@ about API spend or cycle status — without ever reading your keys.
124
125
  ## Releasing
125
126
 
126
127
  ```bash
127
- make release VERSION=0.1.2
128
+ make release VERSION=0.1.4
128
129
  ```
129
130
 
130
- That bumps `cli/package.json`, commits, tags `v0.1.2` and pushes. The tag
131
+ That bumps `cli/package.json`, commits, tags `v0.1.4` and pushes. The tag
131
132
  triggers `.github/workflows/release.yml`, which does the rest on a macOS
132
133
  runner: smoke-tests the CLI, builds and zips the app, creates the GitHub
133
134
  release, publishes to npm (trusted publishing — no token stored), and commits
@@ -137,6 +138,10 @@ The only stored credential is `TAP_TOKEN`, a fine-grained PAT limited to the
137
138
  tap repo (`Contents: read and write`) — cross-repo pushes are the one thing the
138
139
  built-in Actions token cannot do.
139
140
 
141
+ The app ships ad-hoc signed, so macOS warns on first launch. See
142
+ [SIGNING.md](SIGNING.md) to set up Developer ID signing and notarization, which
143
+ the release workflow picks up automatically once the secrets exist.
144
+
140
145
  ## License
141
146
 
142
147
  MIT
package/bin/sage.js CHANGED
@@ -32,7 +32,7 @@ Commands:
32
32
 
33
33
  API keys live in ~/.sage/config.json (chmod 600).
34
34
  Subscriptions (Claude Max, ChatGPT/Codex, Kimi Code) are auto-detected from
35
- the CLIs installed on this machine — read-only, nothing to configure.
35
+ the desktop apps and CLIs installed on this machine — nothing to configure.
36
36
  No account, no telemetry, no cloud.
37
37
  `;
38
38
 
@@ -213,7 +213,7 @@ function printStatus({ cycle, api, subscriptions, configured, detected }) {
213
213
  if (configured.length === 0 && detected.length === 0) {
214
214
  console.log('No API keys configured and no subscriptions detected.');
215
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.');
216
+ console.log('Subscriptions appear automatically once Claude Desktop, Claude Code, Codex, or Kimi Code is signed in.');
217
217
  return;
218
218
  }
219
219
  // One global label column so bars and dates align across providers.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thedevdavid/sage",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "Local-only usage & billing-cycle tracker for LLM API keys and subscriptions (OpenAI, Anthropic/Claude, Kimi, Cursor).",
5
5
  "type": "module",
6
6
  "bin": {
@@ -31,11 +31,13 @@ sage cycle # cycle boundaries and days remaining
31
31
  If `sage` is not on PATH, use `bunx @thedevdavid/sage ...` instead.
32
32
 
33
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
34
+ ChatGPT/Codex, Kimi Code — auto-detected from local desktop/CLI sessions) live
35
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.
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.
39
41
 
40
42
  ## First run / missing provider
41
43
 
@@ -0,0 +1,192 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+ import { homedir, platform } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { createDecipheriv, pbkdf2Sync } from 'node:crypto';
6
+ import { httpJson } from '../http.js';
7
+
8
+ const execFileP = promisify(execFile);
9
+ const CLAUDE_DATA_DIR = join(homedir(), 'Library', 'Application Support', 'Claude');
10
+ const COOKIE_DB = join(CLAUDE_DATA_DIR, 'Cookies');
11
+ const COOKIE_QUERY = `
12
+ SELECT name, hex(encrypted_value), value
13
+ FROM cookies
14
+ WHERE host_key LIKE '%claude.ai'
15
+ AND (length(encrypted_value) > 0 OR length(value) > 0);
16
+ `;
17
+ const SESSION_COOKIE_NAMES = new Set(['sessionKey', 'sessionKeyV3', 'sessionKeyLC', 'sessionKeyV3LC']);
18
+ const COOKIE_USER_AGENT =
19
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36';
20
+
21
+ function printable(buffer) {
22
+ return [...buffer].every((byte) => byte >= 0x20 && byte <= 0x7e);
23
+ }
24
+
25
+ function toEncryptedBuffer(value) {
26
+ if (Buffer.isBuffer(value)) return value;
27
+ if (typeof value !== 'string') return null;
28
+ try {
29
+ return Buffer.from(value, 'hex');
30
+ } catch {
31
+ return null;
32
+ }
33
+ }
34
+
35
+ // Claude Desktop uses Chromium's macOS cookie format: PBKDF2-HMAC-SHA1 and
36
+ // AES-128-CBC with the v10 prefix. Newer Chromium builds prepend a 32-byte
37
+ // metadata block to the decrypted value; support both generations.
38
+ export function decryptChromiumCookie(encryptedValue, safeStoragePassword) {
39
+ const encrypted = toEncryptedBuffer(encryptedValue);
40
+ if (!encrypted || encrypted.subarray(0, 3).toString() !== 'v10') return null;
41
+ const key = pbkdf2Sync(safeStoragePassword, 'saltysalt', 1003, 16, 'sha1');
42
+ try {
43
+ const decipher = createDecipheriv('aes-128-cbc', key, Buffer.alloc(16, 0x20));
44
+ const plaintext = Buffer.concat([
45
+ decipher.update(encrypted.subarray(3)),
46
+ decipher.final(),
47
+ ]);
48
+ if (printable(plaintext)) return plaintext.toString('utf8');
49
+ const withoutMetadata = plaintext.subarray(32);
50
+ return printable(withoutMetadata) ? withoutMetadata.toString('utf8') : null;
51
+ } catch {
52
+ return null;
53
+ }
54
+ }
55
+
56
+ async function readClaudeSafeStoragePassword() {
57
+ const { stdout } = await execFileP(
58
+ '/usr/bin/security',
59
+ ['find-generic-password', '-s', 'Claude Safe Storage', '-a', 'Claude Key', '-w'],
60
+ { timeout: 5000, maxBuffer: 64 * 1024 },
61
+ );
62
+ return stdout.trim();
63
+ }
64
+
65
+ export async function readClaudeDesktopCookies() {
66
+ if (platform() !== 'darwin') return null;
67
+ try {
68
+ const safeStoragePassword = await readClaudeSafeStoragePassword();
69
+ if (!safeStoragePassword) return null;
70
+ const { stdout } = await execFileP(
71
+ '/usr/bin/sqlite3',
72
+ ['-readonly', '-separator', '\t', COOKIE_DB, COOKIE_QUERY],
73
+ { timeout: 5000, maxBuffer: 2 * 1024 * 1024 },
74
+ );
75
+ const cookies = new Map();
76
+ for (const line of stdout.split('\n')) {
77
+ if (!line) continue;
78
+ const [name, encryptedHex, plaintext] = line.split('\t');
79
+ if (!name) continue;
80
+ const value = encryptedHex
81
+ ? decryptChromiumCookie(encryptedHex, safeStoragePassword)
82
+ : plaintext;
83
+ if (value) cookies.set(name, value);
84
+ }
85
+ return [...SESSION_COOKIE_NAMES].some((name) => cookies.has(name)) ? cookies : null;
86
+ } catch {
87
+ return null;
88
+ }
89
+ }
90
+
91
+ function desktopHeaders(cookies) {
92
+ return {
93
+ Cookie: [...cookies].map(([name, value]) => `${name}=${value}`).join('; '),
94
+ Accept: 'application/json',
95
+ 'Accept-Language': 'en-US,en;q=0.9',
96
+ Referer: 'https://claude.ai/',
97
+ 'User-Agent': COOKIE_USER_AGENT,
98
+ };
99
+ }
100
+
101
+ function planName(organization) {
102
+ const tier = String(organization?.rate_limit_tier ?? '').trim();
103
+ const multiplier = tier.match(/(\d+x)/i)?.[1];
104
+ if (/max/i.test(tier)) return multiplier ? `Max (${multiplier})` : 'Max';
105
+ if (/pro/i.test(tier)) return multiplier ? `Pro (${multiplier})` : 'Pro';
106
+ if (/team/i.test(tier)) return 'Team';
107
+ if (/enterprise/i.test(tier)) return 'Enterprise';
108
+ const billing = String(organization?.billing_type ?? '').trim();
109
+ return billing ? billing.charAt(0).toUpperCase() + billing.slice(1) : null;
110
+ }
111
+
112
+ export function parseClaudeDesktopUsage(data, organization) {
113
+ const windows = [];
114
+ for (const [key, label] of [
115
+ ['five_hour', 'Session (5h)'],
116
+ ['seven_day', 'Weekly (all models)'],
117
+ ['seven_day_opus', 'Weekly (Opus)'],
118
+ ['seven_day_sonnet', 'Weekly (Sonnet)'],
119
+ ]) {
120
+ const used = Number(data?.[key]?.utilization);
121
+ if (Number.isFinite(used)) {
122
+ windows.push({ label, usedPercent: used, resetsAt: data[key].resets_at ?? null });
123
+ }
124
+ }
125
+ if (Array.isArray(data?.limits) && windows.length === 0) {
126
+ for (const limit of data.limits) {
127
+ const used = Number(limit?.percent);
128
+ if (Number.isFinite(used)) {
129
+ windows.push({
130
+ label: limit?.scope?.model?.display_name ?? limit?.kind ?? 'limit',
131
+ usedPercent: used,
132
+ resetsAt: limit?.resets_at ?? null,
133
+ });
134
+ }
135
+ }
136
+ }
137
+
138
+ let credits = null;
139
+ if (data?.extra_usage?.is_enabled) {
140
+ credits = {
141
+ used: data.extra_usage.used_credits ?? null,
142
+ limit: data.extra_usage.monthly_limit ?? null,
143
+ currency: data.extra_usage.currency ?? 'USD',
144
+ };
145
+ }
146
+
147
+ return {
148
+ kind: 'subscription',
149
+ ok: true,
150
+ plan: planName(organization),
151
+ windows,
152
+ credits,
153
+ note: null,
154
+ };
155
+ }
156
+
157
+ function organizationId(organization) {
158
+ return organization?.uuid ?? organization?.organization_uuid ?? organization?.id ?? null;
159
+ }
160
+
161
+ async function fetchOrganizations(headers) {
162
+ const data = await httpJson('https://claude.ai/api/organizations', { headers });
163
+ return Array.isArray(data) ? data : [];
164
+ }
165
+
166
+ export async function fetchClaudeDesktopStatus() {
167
+ const cookies = await readClaudeDesktopCookies();
168
+ if (!cookies) throw new Error('no active Claude Desktop session found');
169
+ const headers = desktopHeaders(cookies);
170
+ const activeId = cookies.get('lastActiveOrg');
171
+
172
+ let organizations = [];
173
+ let activeOrganization = null;
174
+ if (activeId) {
175
+ // Usage works with the active-org cookie even when the organization list is
176
+ // briefly challenged by Cloudflare. Plan metadata is best-effort.
177
+ const [usage, listed] = await Promise.all([
178
+ httpJson(`https://claude.ai/api/organizations/${encodeURIComponent(activeId)}/usage`, { headers }),
179
+ fetchOrganizations(headers).catch(() => []),
180
+ ]);
181
+ organizations = listed;
182
+ activeOrganization = organizations.find((organization) => organizationId(organization) === activeId) ?? null;
183
+ return parseClaudeDesktopUsage(usage, activeOrganization);
184
+ }
185
+
186
+ organizations = await fetchOrganizations(headers);
187
+ activeOrganization = organizations[0] ?? null;
188
+ const id = organizationId(activeOrganization);
189
+ if (!id) throw new Error('Claude Desktop session has no active organization');
190
+ const usage = await httpJson(`https://claude.ai/api/organizations/${encodeURIComponent(id)}/usage`, { headers });
191
+ return parseClaudeDesktopUsage(usage, activeOrganization);
192
+ }
@@ -5,13 +5,13 @@ import { homedir, platform } from 'node:os';
5
5
  import { join } from 'node:path';
6
6
  import { httpJson } from '../http.js';
7
7
  import { throwIfExpired, rethrowIfUnauthorized } from '../util.js';
8
+ import { fetchClaudeDesktopStatus, readClaudeDesktopCookies } from './claude-desktop.js';
8
9
 
9
10
  const execFileP = promisify(execFile);
10
11
  const EXPIRED_ERROR = 'Claude Code session expired — open Claude Code once to refresh it';
11
12
 
12
13
  // Claude Code stores OAuth credentials in the macOS Keychain (service
13
14
  // "Claude Code-credentials") or ~/.claude/.credentials.json on Linux.
14
- // We only ever READ the access token — never refresh (rotation races).
15
15
  async function readCredentials() {
16
16
  if (process.env.CLAUDE_CODE_OAUTH_TOKEN) {
17
17
  return { accessToken: process.env.CLAUDE_CODE_OAUTH_TOKEN };
@@ -49,10 +49,10 @@ function planName(oauth) {
49
49
  }
50
50
 
51
51
  export async function available() {
52
- return (await readCredentials()) !== null;
52
+ return (await readClaudeDesktopCookies()) !== null || (await readCredentials()) !== null;
53
53
  }
54
54
 
55
- export async function fetchStatus() {
55
+ async function fetchClaudeCodeStatus() {
56
56
  const oauth = await readCredentials();
57
57
  if (!oauth) throw new Error('no Claude Code credentials found (is Claude Code installed and signed in?)');
58
58
  throwIfExpired(Number(oauth.expiresAt) || null, EXPIRED_ERROR);
@@ -117,3 +117,20 @@ export async function fetchStatus() {
117
117
  note: null,
118
118
  };
119
119
  }
120
+
121
+ export async function fetchStatus() {
122
+ if (await readClaudeDesktopCookies()) {
123
+ try {
124
+ return await fetchClaudeDesktopStatus();
125
+ } catch (err) {
126
+ if (err.status === 401 || err.status === 403) {
127
+ if (err.status === 403) {
128
+ throw new Error('Claude Desktop request was blocked — try Refresh now');
129
+ }
130
+ throw new Error('Claude Desktop session expired — open Claude Desktop once to refresh it');
131
+ }
132
+ throw err;
133
+ }
134
+ }
135
+ return fetchClaudeCodeStatus();
136
+ }
@@ -0,0 +1,187 @@
1
+ import { chmod, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
2
+ import { homedir, hostname, platform, release, arch } from 'node:os';
3
+ import { basename, dirname, join } from 'node:path';
4
+
5
+ const DEFAULT_OAUTH_HOST = 'https://auth.kimi.com';
6
+ const CLIENT_ID = '17e5f671-d194-4dfb-9706-5516cb48c098';
7
+ const KIMI_CODE_HOME = join(homedir(), '.kimi-code');
8
+
9
+ export async function readKimiCodeCredentials() {
10
+ if (process.env.KIMI_CODE_API_KEY) {
11
+ return { token: process.env.KIMI_CODE_API_KEY, refreshToken: null, expiresAt: null, path: null, raw: null };
12
+ }
13
+ for (const dir of ['.kimi-code', '.kimi']) {
14
+ const path = join(homedir(), dir, 'credentials', 'kimi-code.json');
15
+ try {
16
+ const raw = JSON.parse(await readFile(path, 'utf8'));
17
+ if (raw?.access_token) {
18
+ return {
19
+ token: raw.access_token,
20
+ refreshToken: raw.refresh_token ?? null,
21
+ expiresAt: raw.expires_at ? Number(raw.expires_at) * 1000 : null,
22
+ path,
23
+ raw,
24
+ };
25
+ }
26
+ } catch {
27
+ // Try the legacy location.
28
+ }
29
+ }
30
+ return null;
31
+ }
32
+
33
+ export async function readKimiIdentity(home = KIMI_CODE_HOME) {
34
+ let version = 'unknown';
35
+ try {
36
+ const install = JSON.parse(await readFile(join(home, 'updates', 'install.json'), 'utf8'));
37
+ version = install?.lastSuccess?.version ?? version;
38
+ } catch {
39
+ // The version header is informational; the auth endpoint still works on a
40
+ // fresh installation before the update metadata exists.
41
+ }
42
+ let deviceId = null;
43
+ try {
44
+ deviceId = (await readFile(join(home, 'device_id'), 'utf8')).trim() || null;
45
+ } catch {
46
+ // Older installations did not persist a device id.
47
+ }
48
+ return { version, deviceId };
49
+ }
50
+
51
+ function deviceModel() {
52
+ return `${platform()} ${release()} ${arch()}`;
53
+ }
54
+
55
+ export function buildKimiRefreshRequest({
56
+ refreshToken,
57
+ version = 'unknown',
58
+ deviceId = null,
59
+ oauthHost = process.env.KIMI_CODE_OAUTH_HOST ?? process.env.KIMI_OAUTH_HOST ?? DEFAULT_OAUTH_HOST,
60
+ deviceName = hostname(),
61
+ osVersion = release(),
62
+ model = deviceModel(),
63
+ }) {
64
+ const headers = {
65
+ 'Content-Type': 'application/x-www-form-urlencoded',
66
+ Accept: 'application/json',
67
+ 'User-Agent': `Kimi Code CLI/${version}`,
68
+ 'X-Msh-Platform': 'kimi_code_cli',
69
+ 'X-Msh-Version': version,
70
+ 'X-Msh-Device-Name': deviceName,
71
+ 'X-Msh-Device-Model': model,
72
+ 'X-Msh-Os-Version': osVersion,
73
+ };
74
+ if (deviceId) headers['X-Msh-Device-Id'] = deviceId;
75
+ return {
76
+ url: `${oauthHost.replace(/\/+$/, '')}/api/oauth/token`,
77
+ options: {
78
+ method: 'POST',
79
+ headers,
80
+ body: new URLSearchParams({
81
+ client_id: CLIENT_ID,
82
+ grant_type: 'refresh_token',
83
+ refresh_token: refreshToken,
84
+ }).toString(),
85
+ },
86
+ };
87
+ }
88
+
89
+ async function saveKimiCredentials(credentials, raw) {
90
+ if (!credentials.path) return;
91
+ const directory = dirname(credentials.path);
92
+ await mkdir(directory, { recursive: true, mode: 0o700 });
93
+ const temporary = `${credentials.path}.tmp.${process.pid}`;
94
+ await writeFile(temporary, `${JSON.stringify(raw, null, 2)}\n`, { mode: 0o600 });
95
+ await chmod(temporary, 0o600);
96
+ await rename(temporary, credentials.path);
97
+ }
98
+
99
+ async function withKimiRefreshLock(path, work) {
100
+ const credentialDirectory = dirname(path);
101
+ const home = basename(credentialDirectory) === 'credentials' ? dirname(credentialDirectory) : credentialDirectory;
102
+ const lockPath = join(home, 'oauth', 'kimi-code.lock');
103
+ await mkdir(dirname(lockPath), { recursive: true, mode: 0o700 });
104
+ const deadline = Date.now() + 5000;
105
+ while (true) {
106
+ try {
107
+ await mkdir(lockPath);
108
+ break;
109
+ } catch (error) {
110
+ if (error.code !== 'EEXIST' || Date.now() >= deadline) throw new Error('Kimi Code refresh is already in progress');
111
+ await new Promise((resolve) => setTimeout(resolve, 100));
112
+ }
113
+ }
114
+ try {
115
+ return await work();
116
+ } finally {
117
+ await rm(lockPath, { recursive: true, force: true });
118
+ }
119
+ }
120
+
121
+ export async function refreshKimiCodeCredentials(credentials, {
122
+ fetchImpl = fetch,
123
+ now = Date.now(),
124
+ identity = undefined,
125
+ } = {}) {
126
+ if (!credentials?.refreshToken || !credentials.path) {
127
+ throw new Error('Kimi Code has no refresh token');
128
+ }
129
+ return withKimiRefreshLock(credentials.path, async () => {
130
+ let current = credentials;
131
+ try {
132
+ const latestRaw = JSON.parse(await readFile(credentials.path, 'utf8'));
133
+ const latestExpiresAt = latestRaw?.expires_at ? Number(latestRaw.expires_at) * 1000 : null;
134
+ if (latestRaw?.access_token && latestExpiresAt && latestExpiresAt > now + 30_000) {
135
+ return { ...credentials, token: latestRaw.access_token, refreshToken: latestRaw.refresh_token ?? null, expiresAt: latestExpiresAt, raw: latestRaw };
136
+ }
137
+ if (latestRaw?.access_token) {
138
+ current = { ...credentials, token: latestRaw.access_token, refreshToken: latestRaw.refresh_token ?? credentials.refreshToken, raw: latestRaw };
139
+ }
140
+ } catch {
141
+ // Use the credential snapshot supplied by the caller.
142
+ }
143
+ const request = buildKimiRefreshRequest({
144
+ refreshToken: current.refreshToken,
145
+ version: identity?.version,
146
+ deviceId: identity?.deviceId,
147
+ });
148
+ const response = await fetchImpl(request.url, request.options);
149
+ let data = null;
150
+ try {
151
+ data = await response.json();
152
+ } catch {
153
+ // The status below is enough to explain the failure without echoing a
154
+ // potentially sensitive provider response.
155
+ }
156
+ if (!response.ok) {
157
+ const error = new Error(data?.error_description ?? data?.message ?? `Kimi token refresh failed (${response.status})`);
158
+ error.status = response.status;
159
+ throw error;
160
+ }
161
+ if (typeof data?.access_token !== 'string' || !data.access_token) {
162
+ throw new Error('Kimi token refresh response did not include an access token');
163
+ }
164
+ const expiresIn = Number(data.expires_in);
165
+ if (!Number.isFinite(expiresIn) || expiresIn <= 0) {
166
+ throw new Error('Kimi token refresh response did not include a valid expiry');
167
+ }
168
+ const refreshToken = data.refresh_token || current.refreshToken;
169
+ const raw = {
170
+ ...(current.raw ?? {}),
171
+ access_token: data.access_token,
172
+ refresh_token: refreshToken,
173
+ expires_at: Math.floor(now / 1000) + expiresIn,
174
+ expires_in: expiresIn,
175
+ scope: data.scope ?? current.raw?.scope ?? 'kimi-code',
176
+ token_type: data.token_type ?? current.raw?.token_type ?? 'Bearer',
177
+ };
178
+ await saveKimiCredentials(current, raw);
179
+ return {
180
+ ...current,
181
+ token: data.access_token,
182
+ refreshToken,
183
+ expiresAt: (Math.floor(now / 1000) + expiresIn) * 1000,
184
+ raw,
185
+ };
186
+ });
187
+ }
@@ -1,32 +1,8 @@
1
- import { readFile } from 'node:fs/promises';
2
- import { homedir } from 'node:os';
3
- import { join } from 'node:path';
4
1
  import { httpJson } from '../http.js';
5
- import { throwIfExpired, rethrowIfUnauthorized } from '../util.js';
2
+ import { readKimiCodeCredentials, readKimiIdentity, refreshKimiCodeCredentials } from './kimi-auth.js';
6
3
 
7
4
  const BASE = 'https://api.kimi.com/coding/v1';
8
5
 
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
6
  function percent(used, limit) {
31
7
  const u = Number(used);
32
8
  const l = Number(limit);
@@ -47,15 +23,11 @@ function windowLabel(window) {
47
23
  const EXPIRED_ERROR = 'Kimi Code session expired (tokens last ~1h) — run any kimi command once to refresh it';
48
24
 
49
25
  export async function available() {
50
- return (await readCredentials()) !== null;
26
+ return (await readKimiCodeCredentials()) !== null;
51
27
  }
52
28
 
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);
29
+ async function fetchUsage(creds) {
57
30
  const headers = { Authorization: `Bearer ${creds.token}`, Accept: 'application/json' };
58
-
59
31
  const windows = [];
60
32
  let usage;
61
33
  let me = null;
@@ -65,7 +37,8 @@ export async function fetchStatus() {
65
37
  httpJson(`${BASE}/me`, { headers }).catch(() => null),
66
38
  ]);
67
39
  } catch (err) {
68
- rethrowIfUnauthorized(err, EXPIRED_ERROR);
40
+ if (err.status === 401) throw err;
41
+ throw err;
69
42
  }
70
43
 
71
44
  const weekly = percent(usage?.usage?.used, usage?.usage?.limit);
@@ -89,3 +62,25 @@ export async function fetchStatus() {
89
62
 
90
63
  return { kind: 'subscription', ok: true, plan: me?.user_level_name ?? null, windows, credits: null, note: null };
91
64
  }
65
+
66
+ async function refreshOrExplain(creds) {
67
+ if (!creds.refreshToken || !creds.path) throw new Error(EXPIRED_ERROR);
68
+ try {
69
+ return await refreshKimiCodeCredentials(creds, { identity: await readKimiIdentity() });
70
+ } catch (err) {
71
+ throw new Error(`Kimi Code session expired — Sage refresh failed: ${err.message}`);
72
+ }
73
+ }
74
+
75
+ export async function fetchStatus() {
76
+ let creds = await readKimiCodeCredentials();
77
+ if (!creds) throw new Error('no Kimi Code credentials found (is Kimi Code CLI installed and signed in?)');
78
+ if (creds.expiresAt && creds.expiresAt < Date.now()) creds = await refreshOrExplain(creds);
79
+ try {
80
+ return await fetchUsage(creds);
81
+ } catch (err) {
82
+ if (err.status !== 401) throw err;
83
+ creds = await refreshOrExplain(creds);
84
+ return fetchUsage(creds);
85
+ }
86
+ }
package/src/util.js CHANGED
@@ -13,8 +13,9 @@ export function sumBuckets(data, pick) {
13
13
  return Math.round(total * 100) / 100;
14
14
  }
15
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.
16
+ // Subscription providers may rotate tokens. Provider modules decide whether
17
+ // a refresh is safe for their own local credential store before surfacing an
18
+ // actionable re-auth instruction.
18
19
  export function throwIfExpired(expiresAtMs, message) {
19
20
  if (expiresAtMs && expiresAtMs < Date.now()) throw new Error(message);
20
21
  }