@thedevdavid/sage 0.1.4 → 0.1.6

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
@@ -125,10 +125,10 @@ about API spend or cycle status — without ever reading your keys.
125
125
  ## Releasing
126
126
 
127
127
  ```bash
128
- make release VERSION=0.1.4
128
+ make release VERSION=0.1.5
129
129
  ```
130
130
 
131
- That bumps `cli/package.json`, commits, tags `v0.1.4` and pushes. The tag
131
+ That bumps `cli/package.json`, commits, tags `v0.1.5` and pushes. The tag
132
132
  triggers `.github/workflows/release.yml`, which does the rest on a macOS
133
133
  runner: smoke-tests the CLI, builds and zips the app, creates the GitHub
134
134
  release, publishes to npm (trusted publishing — no token stored), and commits
package/bin/sage.js CHANGED
@@ -181,6 +181,30 @@ function cleanLabel(label) {
181
181
  return String(label).replace('(all models)', '').trim();
182
182
  }
183
183
 
184
+ function formatLimitNumber(value) {
185
+ const number = Number(value);
186
+ if (!Number.isFinite(number)) return null;
187
+ return Number.isInteger(number) ? String(number) : number.toFixed(1).replace(/\.0$/, '');
188
+ }
189
+
190
+ function printRateLimitRows(rows, labelWidth) {
191
+ if (!rows.length) return;
192
+ console.log(` ${dim('Rate limits')}`);
193
+ for (const row of rows) {
194
+ const label = cleanLabel(row.label).padEnd(labelWidth);
195
+ const remaining = formatLimitNumber(row.remaining);
196
+ const limit = formatLimitNumber(row.limit);
197
+ const unit = row.unit ?? 'requests';
198
+ const value = remaining !== null && limit !== null
199
+ ? `${remaining}/${limit} ${unit}`
200
+ : limit !== null
201
+ ? `${limit} ${unit}`
202
+ : `${Math.max(0, Math.round(100 - (Number(row.usedPercent) || 0)))}% left`;
203
+ const reset = formatReset(row.resetsAt);
204
+ console.log(` ${label} ${value}${reset ? dim(` · ${reset}`) : ''}`);
205
+ }
206
+ }
207
+
184
208
  function printSubscription(name, status, labelWidth) {
185
209
  const brand = BRAND[name] ?? 15;
186
210
  const cached = status?.stale ? ` ${paint('yellow', '· cached')}` : '';
@@ -196,13 +220,26 @@ function printSubscription(name, status, labelWidth) {
196
220
  return;
197
221
  }
198
222
  const windows = status.windows ?? [];
199
- for (const w of windows) {
223
+ const quotaWindows = windows.filter((window) => window.category !== 'model' && window.category !== 'rate');
224
+ for (const w of quotaWindows) {
200
225
  const left = Math.max(0, Math.round(100 - (Number(w.usedPercent) || 0)));
201
226
  const reset = formatReset(w.resetsAt);
202
227
  console.log(
203
228
  ` ${cleanLabel(w.label).padEnd(labelWidth)} ${usageBar(w.usedPercent)} ${String(left + '% left').padStart(8)}${reset ? dim(` · ${reset}`) : ''}`,
204
229
  );
205
230
  }
231
+ const modelLimits = windows.filter((window) => window.category === 'model');
232
+ if (modelLimits.length) {
233
+ console.log(` ${dim('Model limits')}`);
234
+ for (const w of modelLimits) {
235
+ const left = Math.max(0, Math.round(100 - (Number(w.usedPercent) || 0)));
236
+ const reset = formatReset(w.resetsAt);
237
+ console.log(
238
+ ` ${cleanLabel(w.label).padEnd(labelWidth)} ${usageBar(w.usedPercent)} ${String(left + '% left').padStart(8)}${reset ? dim(` · ${reset}`) : ''}`,
239
+ );
240
+ }
241
+ }
242
+ printRateLimitRows(windows.filter((window) => window.category === 'rate'), labelWidth);
206
243
  if (status.credits?.balance != null) console.log(` ${'credits'.padEnd(12)} $${status.credits.balance}`);
207
244
  if (status.credits?.used != null) {
208
245
  console.log(` ${'extra usage'.padEnd(12)} $${status.credits.used}${status.credits.limit != null ? `/$${status.credits.limit}` : ''}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thedevdavid/sage",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
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": {
@@ -111,28 +111,37 @@ function planName(organization) {
111
111
 
112
112
  export function parseClaudeDesktopUsage(data, organization) {
113
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);
114
+ const modelNames = new Map([
115
+ ['seven_day_opus', 'Opus'],
116
+ ['seven_day_sonnet', 'Sonnet'],
117
+ ]);
118
+ for (const [key, label] of [['five_hour', 'Session (5h)'], ['seven_day', 'Weekly (all models)'], ...modelNames]) {
119
+ const value = data?.[key];
120
+ const used = Number(value?.utilization);
121
+ if (!Number.isFinite(used)) continue;
122
+ windows.push({ label: label ?? key, usedPercent: used, resetsAt: value?.resets_at ?? null, ...(modelNames.has(key) ? { category: 'model' } : {}) });
123
+ }
124
+ for (const [key, value] of Object.entries(data ?? {})) {
125
+ if (!key.startsWith('seven_day_') || modelNames.has(key) || !value || typeof value !== 'object') continue;
126
+ const used = Number(value.utilization);
121
127
  if (Number.isFinite(used)) {
122
- windows.push({ label, usedPercent: used, resetsAt: data[key].resets_at ?? null });
128
+ const label = key.slice('seven_day_'.length).replace(/[_-]+/g, ' ').replace(/\b\w/g, (part) => part.toUpperCase());
129
+ windows.push({ label, usedPercent: used, resetsAt: value.resets_at ?? null, category: 'model' });
123
130
  }
124
131
  }
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
- }
132
+ for (const value of data?.model_limits ?? []) {
133
+ const model = value?.scope?.model?.display_name ?? value?.model_name ?? value?.model;
134
+ const used = Number(value?.utilization ?? value?.percent);
135
+ if (model && Number.isFinite(used)) windows.push({ label: model, usedPercent: used, resetsAt: value?.resets_at ?? null, category: 'model' });
136
+ }
137
+ for (const value of data?.rate_limits ?? []) {
138
+ const detail = value?.detail ?? value;
139
+ const limit = Number(detail?.limit);
140
+ const remaining = Number(detail?.remaining);
141
+ const used = Number(detail?.used_percent ?? detail?.utilization);
142
+ const usedPercent = Number.isFinite(used) ? used : Number.isFinite(limit) && Number.isFinite(remaining) && limit > 0 ? ((limit - remaining) / limit) * 100 : null;
143
+ if (usedPercent === null && !Number.isFinite(limit) && !Number.isFinite(remaining)) continue;
144
+ windows.push({ label: value?.name ?? value?.label ?? 'Rate limit', usedPercent: usedPercent ?? 0, resetsAt: detail?.resets_at ?? detail?.reset_at ?? null, category: 'rate', ...(Number.isFinite(limit) ? { limit } : {}), ...(Number.isFinite(remaining) ? { remaining } : {}), unit: value?.unit ?? detail?.unit ?? 'requests' });
136
145
  }
137
146
 
138
147
  let credits = null;
@@ -5,7 +5,7 @@ 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
+ import { fetchClaudeDesktopStatus, parseClaudeDesktopUsage, readClaudeDesktopCookies } from './claude-desktop.js';
9
9
 
10
10
  const execFileP = promisify(execFile);
11
11
  const EXPIRED_ERROR = 'Claude Code session expired — open Claude Code once to refresh it';
@@ -71,51 +71,7 @@ async function fetchClaudeCodeStatus() {
71
71
  rethrowIfUnauthorized(err, EXPIRED_ERROR);
72
72
  }
73
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
- };
74
+ return { ...parseClaudeDesktopUsage(data, null), plan: planName(oauth) };
119
75
  }
120
76
 
121
77
  export async function fetchStatus() {
@@ -80,7 +80,11 @@ export async function fetchStatus() {
80
80
  if (secondary) windows.push(secondary);
81
81
  for (const extra of data?.additional_rate_limits ?? []) {
82
82
  const w = windowFrom(extra?.rate_limit?.secondary_window ?? extra?.rate_limit?.primary_window, extra?.limit_name);
83
- if (w) windows.push(w);
83
+ if (!w) continue;
84
+ const model = extra?.model_name ?? extra?.model?.display_name ?? extra?.limit_name ?? null;
85
+ if (model) w.category = 'model';
86
+ else w.category = 'rate';
87
+ windows.push(w);
84
88
  }
85
89
 
86
90
  return {
@@ -13,11 +13,11 @@ function percent(used, limit) {
13
13
  function windowLabel(window) {
14
14
  const duration = Number(window?.duration);
15
15
  const unit = window?.timeUnit ?? '';
16
- if (!Number.isFinite(duration)) return 'Rate limit';
16
+ if (!Number.isFinite(duration)) return 'Limit';
17
17
  const minutes = unit.includes('SECOND') ? duration / 60 : duration;
18
- if (minutes >= 60 * 24 * 7) return `Weekly rate limit`;
19
- if (minutes >= 60) return `${Math.round(minutes / 60)}h rate limit`;
20
- return `${Math.round(minutes)}m rate limit`;
18
+ if (minutes >= 60 * 24 * 7) return 'Weekly';
19
+ if (minutes >= 60) return `${Math.round(minutes / 60)}h`;
20
+ return `${Math.round(minutes)}m`;
21
21
  }
22
22
 
23
23
  const EXPIRED_ERROR = 'Kimi Code session expired (tokens last ~1h) — run any kimi command once to refresh it';
@@ -26,20 +26,8 @@ export async function available() {
26
26
  return (await readKimiCodeCredentials()) !== null;
27
27
  }
28
28
 
29
- async function fetchUsage(creds) {
30
- const headers = { Authorization: `Bearer ${creds.token}`, Accept: 'application/json' };
29
+ function parseKimiUsage(usage, me) {
31
30
  const windows = [];
32
- let usage;
33
- let me = null;
34
- try {
35
- [usage, me] = await Promise.all([
36
- httpJson(`${BASE}/usages`, { headers }),
37
- httpJson(`${BASE}/me`, { headers }).catch(() => null),
38
- ]);
39
- } catch (err) {
40
- if (err.status === 401) throw err;
41
- throw err;
42
- }
43
31
 
44
32
  const weekly = percent(usage?.usage?.used, usage?.usage?.limit);
45
33
  if (weekly !== null) {
@@ -50,19 +38,63 @@ async function fetchUsage(creds) {
50
38
  });
51
39
  }
52
40
  for (const entry of usage?.limits ?? []) {
53
- const used = percent(entry?.detail?.used, entry?.detail?.limit);
54
- if (used !== null) {
55
- windows.push({
56
- label: windowLabel(entry?.window),
57
- usedPercent: used,
58
- resetsAt: entry?.detail?.resetTime ?? entry?.detail?.reset_at ?? null,
59
- });
60
- }
41
+ const model = entry?.model?.display_name ?? entry?.model_name ?? entry?.model ?? null;
42
+ const limit = Number(entry?.detail?.limit);
43
+ const remaining = Number(entry?.detail?.remaining);
44
+ const directUsed = Number(entry?.detail?.used);
45
+ const used = Number.isFinite(directUsed)
46
+ ? directUsed
47
+ : Number.isFinite(limit) && Number.isFinite(remaining)
48
+ ? limit - remaining
49
+ : null;
50
+ const usedPercent = used !== null ? percent(used, limit) : null;
51
+ if (usedPercent === null && !Number.isFinite(limit) && !Number.isFinite(remaining)) continue;
52
+ const row = {
53
+ label: model ?? windowLabel(entry?.window),
54
+ usedPercent: usedPercent ?? 0,
55
+ resetsAt: entry?.detail?.resetTime ?? entry?.detail?.reset_at ?? null,
56
+ category: model ? 'model' : 'rate',
57
+ };
58
+ if (Number.isFinite(limit)) row.limit = limit;
59
+ if (Number.isFinite(remaining)) row.remaining = remaining;
60
+ row.unit = entry?.detail?.unit ?? 'requests';
61
+ windows.push(row);
62
+ }
63
+
64
+ const parallelLimit = Number(usage?.parallel?.limit);
65
+ if (Number.isFinite(parallelLimit)) {
66
+ const parallelRemaining = Number(usage?.parallel?.remaining);
67
+ const remaining = Number.isFinite(parallelRemaining) ? parallelRemaining : parallelLimit;
68
+ windows.push({
69
+ label: 'Concurrency',
70
+ usedPercent: percent(parallelLimit - remaining, parallelLimit) ?? 0,
71
+ resetsAt: null,
72
+ category: 'rate',
73
+ limit: parallelLimit,
74
+ remaining,
75
+ unit: 'concurrent requests',
76
+ });
61
77
  }
62
78
 
63
79
  return { kind: 'subscription', ok: true, plan: me?.user_level_name ?? null, windows, credits: null, note: null };
64
80
  }
65
81
 
82
+ async function fetchUsage(creds) {
83
+ const headers = { Authorization: `Bearer ${creds.token}`, Accept: 'application/json' };
84
+ let usage;
85
+ let me = null;
86
+ try {
87
+ [usage, me] = await Promise.all([
88
+ httpJson(`${BASE}/usages`, { headers }),
89
+ httpJson(`${BASE}/me`, { headers }).catch(() => null),
90
+ ]);
91
+ } catch (err) {
92
+ if (err.status === 401) throw err;
93
+ throw err;
94
+ }
95
+ return parseKimiUsage(usage, me);
96
+ }
97
+
66
98
  async function refreshOrExplain(creds) {
67
99
  if (!creds.refreshToken || !creds.path) throw new Error(EXPIRED_ERROR);
68
100
  try {