tokenusage-cli 0.4.5 → 0.4.7

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.
@@ -67,11 +67,11 @@ function readCursorAccessTokenFromStateDb(stateDbPath, deps = {}) {
67
67
 
68
68
  /**
69
69
  * Extract Cursor session cookie from local SQLite + cli-config.json.
70
- * Returns { cookie, userId } or null on failure.
70
+ * Returns { cookie, cookies, userId, userIds } or null on failure.
71
71
  *
72
72
  * Cookie format: WorkosCursorSessionToken=<userId>%3A%3A<jwt>
73
73
  * - JWT from state.vscdb → ItemTable → cursorAuth/accessToken
74
- * - userId from cli-config.json → authInfo.authId
74
+ * - userId candidates, JWT subject first, then cli-config.json authInfo.authId:
75
75
  * - native Cursor email/password: "auth0|user_XXXXX" → "user_XXXXX"
76
76
  * - Google sign-in via WorkOS: "google-oauth2|<numeric>" → kept verbatim
77
77
  * - other WorkOS subjects: "github|…", "oidc|…" → kept verbatim
@@ -79,7 +79,9 @@ function readCursorAccessTokenFromStateDb(stateDbPath, deps = {}) {
79
79
  function extractCursorSessionToken({ home, platform, env, deps } = {}) {
80
80
  const auth = extractCursorAuth({ home, platform, env, deps });
81
81
  if (!auth) return null;
82
- return { cookie: auth.cookie, userId: auth.userId };
82
+ // `cookies` is additive: callers that only need one session cookie keep
83
+ // using `cookie`, while sync can retry the remaining userId candidates.
84
+ return { cookie: auth.cookie, cookies: auth.cookies, userId: auth.userId };
83
85
  }
84
86
 
85
87
  /**
@@ -99,16 +101,16 @@ function extractCursorAuth({ home, platform, env, deps } = {}) {
99
101
  const jwt = readCursorAccessTokenFromStateDb(stateDbPath, deps);
100
102
  if (!jwt || jwt.length < 10) return null;
101
103
 
102
- // 2. Extract userId — try cli-config.json first, fall back to JWT decode
103
- let userId = extractUserIdFromCliConfig(cliConfigPath);
104
- if (!userId) {
105
- userId = extractUserIdFromJwt(jwt);
106
- }
104
+ // 2. Build every userId candidate — JWT subject first (cli-config.json can
105
+ // hold a stale account and pairing it with the current token is a
106
+ // persistent 401), then the cli-config authId as a fallback.
107
+ const userIds = collectCursorSessionUserIds(jwt, readCursorCliAuthId(cliConfigPath));
108
+ const userId = userIds[0] || null;
107
109
  if (!userId) return null;
108
110
 
109
- // 3. Build cookie
110
- const cookie = `WorkosCursorSessionToken=${userId}%3A%3A${jwt}`;
111
- return { cookie, userId, accessToken: jwt };
111
+ // 3. Build cookie(s)
112
+ const cookies = userIds.map((id) => `${CURSOR_SESSION_COOKIE}=${id}%3A%3A${jwt}`);
113
+ return { cookie: cookies[0], cookies, userId, userIds, accessToken: jwt };
112
114
  }
113
115
 
114
116
  // WorkOS OAuth subject prefixes Cursor accepts as-is in the session cookie.
@@ -125,26 +127,57 @@ function normalizeCursorSubject(subject) {
125
127
  return null;
126
128
  }
127
129
 
128
- function extractUserIdFromCliConfig(configPath) {
130
+ function readCursorCliAuthId(configPath) {
129
131
  try {
130
132
  const config = JSON.parse(fs.readFileSync(configPath, "utf8"));
131
- return normalizeCursorSubject(config?.authInfo?.authId || "");
133
+ const raw = typeof config?.authInfo?.authId === "string" ? config.authInfo.authId.trim() : "";
134
+ return raw || null;
132
135
  } catch {
133
136
  return null;
134
137
  }
135
138
  }
136
139
 
137
- function extractUserIdFromJwt(jwt) {
140
+ function decodeJwtSubject(jwt) {
138
141
  try {
139
142
  const parts = jwt.split(".");
140
143
  if (parts.length !== 3) return null;
141
144
  const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString());
142
- return normalizeCursorSubject(payload.sub || "");
145
+ return typeof payload.sub === "string" && payload.sub.trim() ? payload.sub.trim() : null;
143
146
  } catch {
144
147
  return null;
145
148
  }
146
149
  }
147
150
 
151
+ const CURSOR_SESSION_COOKIE = "WorkosCursorSessionToken";
152
+ const CURSOR_USER_ID_RE = /^user_[A-Za-z0-9_]+$/;
153
+
154
+ function addCursorUserIdCandidate(ids, value) {
155
+ const trimmed = typeof value === "string" ? value.trim() : "";
156
+ if (!trimmed) return;
157
+ // Same acceptance rule as normalizeCursorSubject: bare `user_*` ids or a
158
+ // WorkOS provider subject. Anything else is not a cookie identity.
159
+ if (!normalizeCursorSubject(trimmed) && !CURSOR_USER_ID_RE.test(trimmed)) return;
160
+ if (!ids.includes(trimmed)) ids.push(trimmed);
161
+ }
162
+
163
+ /**
164
+ * Ordered userId candidates for the Cursor session cookie.
165
+ *
166
+ * The JWT subject is authoritative: cli-config.json can still hold a different
167
+ * (stale) account, and pairing that id with the current access token is a
168
+ * persistent 401. Both the normalized and the raw subject are kept because
169
+ * Cursor accepts `auth0|user_x` and `user_x` for the same login.
170
+ */
171
+ function collectCursorSessionUserIds(jwt, cliAuthId) {
172
+ const ids = [];
173
+ const jwtSubject = decodeJwtSubject(jwt);
174
+ addCursorUserIdCandidate(ids, normalizeCursorSubject(jwtSubject || ""));
175
+ addCursorUserIdCandidate(ids, jwtSubject);
176
+ addCursorUserIdCandidate(ids, normalizeCursorSubject(cliAuthId || ""));
177
+ addCursorUserIdCandidate(ids, cliAuthId);
178
+ return ids;
179
+ }
180
+
148
181
  // ── API client ──
149
182
 
150
183
  const CURSOR_CSV_URL = "https://cursor.com/api/dashboard/export-usage-events-csv?strategy=tokens";
@@ -207,7 +240,11 @@ function fetchCursorUsageCsv({ cookie, timeoutMs = 30000, fetchImpl = fetch }) {
207
240
  signal: AbortSignal.timeout(timeoutMs),
208
241
  }).then(async (res) => {
209
242
  if (res.status === 401 || res.status === 403) {
210
- throw new Error("Cursor session expired — re-login in Cursor to refresh");
243
+ const error = new Error("Cursor session expired — re-login in Cursor to refresh");
244
+ // Lets sync retry the remaining userId candidates instead of treating
245
+ // one stale cli-config account as a dead session.
246
+ error.code = "AUTH_EXPIRED";
247
+ throw error;
211
248
  }
212
249
  if (res.status === 308 || res.status === 301 || res.status === 302) {
213
250
  // Follow redirect once. Keep this hop on redirect:"manual" so the
@@ -224,6 +261,48 @@ function fetchCursorUsageCsv({ cookie, timeoutMs = 30000, fetchImpl = fetch }) {
224
261
  }).catch(remapCursorFetchTimeout);
225
262
  }
226
263
 
264
+ /**
265
+ * Fetch the CSV trying each userId candidate in order.
266
+ *
267
+ * Only an auth rejection (`AUTH_EXPIRED`) moves to the next candidate: a stale
268
+ * cli-config account produces exactly that, while a network/timeout failure
269
+ * says nothing about the identity and must surface immediately.
270
+ */
271
+ async function fetchCursorUsageCsvWithFallback({
272
+ cookies,
273
+ cookie,
274
+ timeoutMs,
275
+ fetchImpl = fetch,
276
+ cookieFetcher,
277
+ } = {}) {
278
+ const candidates = Array.isArray(cookies) && cookies.length > 0
279
+ ? cookies
280
+ : (cookie ? [cookie] : []);
281
+ if (candidates.length === 0) {
282
+ throw new Error("Cursor session cookie is missing — re-login in Cursor to refresh");
283
+ }
284
+ const fetcher = typeof cookieFetcher === "function"
285
+ ? cookieFetcher
286
+ : (opts) => fetchCursorUsageCsv({
287
+ cookie: opts.cookie,
288
+ fetchImpl,
289
+ ...(timeoutMs ? { timeoutMs } : {}),
290
+ });
291
+ let lastAuthError = null;
292
+ for (const candidate of candidates) {
293
+ try {
294
+ return await fetcher({ cookie: candidate });
295
+ } catch (err) {
296
+ if (err && err.code === "AUTH_EXPIRED") {
297
+ lastAuthError = err;
298
+ continue;
299
+ }
300
+ throw err;
301
+ }
302
+ }
303
+ throw lastAuthError;
304
+ }
305
+
227
306
  /**
228
307
  * Fetch Cursor usage summary JSON.
229
308
  * Returns parsed JSON body or throws on error.
@@ -502,7 +581,22 @@ function parseCursorCsv(csvText) {
502
581
  cost: toFloat(fields[costIdx]),
503
582
  };
504
583
 
505
- if (record.totalTokens <= 0 && record.inputTokens <= 0 && record.outputTokens <= 0) continue;
584
+ // Token presence is judged on the component columns (not the Total
585
+ // column) so a cache-read-only or cache-write-only row survives even when
586
+ // Cursor's Total disagrees — normalizeCursorUsage and the downstream
587
+ // isAllZeroUsage gate read these same component fields. Rows with no
588
+ // token component at all stay dropped on purpose (A8 decision,
589
+ // 2026-11-05): a 0-token request-only row would add a conversation but no
590
+ // tokens, and the dashboard derives active days from day buckets, so
591
+ // admitting them invents active days and counts bot/automation traffic as
592
+ // conversations. Upstream keeps them to pair with its cloud-side request
593
+ // retention, which this project does not have.
594
+ const hasTokens =
595
+ record.inputTokens > 0 ||
596
+ record.cacheWriteTokens > 0 ||
597
+ record.cacheReadTokens > 0 ||
598
+ record.outputTokens > 0;
599
+ if (!hasTokens) continue;
506
600
 
507
601
  records.push(record);
508
602
  }
@@ -597,7 +691,9 @@ module.exports = {
597
691
  readCursorAccessTokenFromStateDb,
598
692
  extractCursorAuth,
599
693
  extractCursorSessionToken,
694
+ collectCursorSessionUserIds,
600
695
  fetchCursorUsageCsv,
696
+ fetchCursorUsageCsvWithFallback,
601
697
  fetchCursorUsageSummary,
602
698
  decodeCursorSandAccessStatus,
603
699
  decodeCursorSandUsageStatus,
@@ -0,0 +1,84 @@
1
+ "use strict";
2
+
3
+ const fs = require("node:fs");
4
+ const os = require("node:os");
5
+ const path = require("node:path");
6
+
7
+ // Hostname fallback — the contract (§2.2) uses this when client_info carries
8
+ // no hostname, so the cloud device name stays `<host> #<machine_id[:8]>`.
9
+ const FALLBACK_DEVICE_NAME = "Token Usage CLI";
10
+
11
+ function trimmedString(value) {
12
+ return typeof value === "string" && value.trim() ? value.trim() : "";
13
+ }
14
+
15
+ function readSeedMachineId(seedPath) {
16
+ try {
17
+ return trimmedString(fs.readFileSync(seedPath, "utf8"));
18
+ } catch {
19
+ return "";
20
+ }
21
+ }
22
+
23
+ function defaultSeedPath(home = os.homedir()) {
24
+ return path.join(home, ".config", "tokenusage", "machine-id");
25
+ }
26
+
27
+ /**
28
+ * This machine's cloud device identity.
29
+ *
30
+ * The device name is defined by docs/cli-contract.md §2.2:
31
+ * `<client_info hostname> #<machine_id first 8 chars>`
32
+ * — client_info without a hostname falls back to "Token Usage CLI", a missing
33
+ * machine_id drops the suffix. The cloud derives it the same way from the
34
+ * `client_info` / `machine_id` the CLI sends at device-flow time, so the name
35
+ * computed here matches the dashboard's device card byte for byte.
36
+ *
37
+ * Why the CLI bothers to print it: two collector machines report into one
38
+ * account, and `status` output is what gets pasted into issue trackers and
39
+ * release checklists. Without the identity in the output, a reader cannot tell
40
+ * which machine produced a number — that is how "this machine" and "the other
41
+ * machine" got mixed up in the docs.
42
+ *
43
+ * Read-only on purpose: unlike getOrCreateMachineId() this never mints or
44
+ * persists an id, so `status` stays a safe command to run anywhere.
45
+ */
46
+ function buildDeviceIdentity({
47
+ config = {},
48
+ hostname = os.hostname(),
49
+ seedPath = null,
50
+ home = os.homedir(),
51
+ } = {}) {
52
+ const machineId =
53
+ trimmedString(config.machineId) || (seedPath ? readSeedMachineId(seedPath) : "");
54
+ const deviceId = trimmedString(config.deviceId);
55
+ const host = trimmedString(hostname) || FALLBACK_DEVICE_NAME;
56
+ const suffix = machineId ? machineId.slice(0, 8) : "";
57
+
58
+ return {
59
+ name: suffix ? `${host} #${suffix}` : host,
60
+ hostname: host,
61
+ machine_id: machineId || null,
62
+ device_id: deviceId || null,
63
+ };
64
+ }
65
+
66
+ /**
67
+ * Identity of the machine this CLI runs on, reading the tracker config plus
68
+ * the purge-surviving identity seed (so `status` still names the device after
69
+ * a `uninstall --purge` wiped ~/.tokenusage).
70
+ */
71
+ function resolveLocalDeviceIdentity({ config = {}, home = os.homedir() } = {}) {
72
+ return buildDeviceIdentity({
73
+ config,
74
+ hostname: os.hostname(),
75
+ seedPath: defaultSeedPath(home),
76
+ home,
77
+ });
78
+ }
79
+
80
+ module.exports = {
81
+ FALLBACK_DEVICE_NAME,
82
+ buildDeviceIdentity,
83
+ resolveLocalDeviceIdentity,
84
+ };
package/src/lib/doctor.js CHANGED
@@ -10,11 +10,13 @@ async function buildDoctorReport({
10
10
  diagnostics = null,
11
11
  fetch = globalThis.fetch,
12
12
  now = () => new Date(),
13
+ deviceIdentity = null,
13
14
  paths = {},
14
15
  } = {}) {
15
16
  const checks = [];
16
17
 
17
18
  checks.push(...buildRuntimeChecks(runtime));
19
+ checks.push(...buildDeviceIdentityChecks(deviceIdentity));
18
20
 
19
21
  if (paths.trackerDir) {
20
22
  checks.push(await checkTrackerDir(paths.trackerDir));
@@ -131,6 +133,34 @@ function buildRuntimeChecks(runtime = {}) {
131
133
  return checks;
132
134
  }
133
135
 
136
+ /**
137
+ * Which collector machine is this? The account has two of them, and every
138
+ * doctor report gets pasted into release checklists — without the device
139
+ * identity in the report, a reader cannot tell the two apart.
140
+ */
141
+ function buildDeviceIdentityChecks(deviceIdentity) {
142
+ const checks = [];
143
+ if (!deviceIdentity) return checks;
144
+
145
+ const machineId = deviceIdentity.machine_id || null;
146
+ checks.push({
147
+ id: "runtime.device_identity",
148
+ status: machineId ? "ok" : "warn",
149
+ detail: machineId
150
+ ? `device ${deviceIdentity.name} (id ${deviceIdentity.device_id || "unpaired"})`
151
+ : `device ${deviceIdentity.name} (machine_id missing)`,
152
+ critical: false,
153
+ meta: {
154
+ name: deviceIdentity.name || null,
155
+ hostname: deviceIdentity.hostname || null,
156
+ machine_id: machineId,
157
+ device_id: deviceIdentity.device_id || null,
158
+ },
159
+ });
160
+
161
+ return checks;
162
+ }
163
+
134
164
  async function checkTrackerDir(trackerDir) {
135
165
  try {
136
166
  const st = await fs.stat(trackerDir);
@@ -180,7 +210,7 @@ async function checkTrackerDir(trackerDir) {
180
210
  }
181
211
  }
182
212
 
183
- // B3 (docs/upstream-comparison-plan.md §2): pricing coverage of the local
213
+ // B3 (docs/archive/upstream-2026-11-03.md): pricing coverage of the local
184
214
  // last-wins queue over the trailing 7 days, plus the C2 unknown-alignment
185
215
  // dry-run preview. Informational only — never critical, never writes.
186
216
  async function checkPricingCoverage(trackerDir) {
@@ -502,4 +532,4 @@ function summarizeChecks(checks = []) {
502
532
  return summary;
503
533
  }
504
534
 
505
- module.exports = { buildDoctorReport };
535
+ module.exports = { buildDoctorReport, buildDeviceIdentityChecks };
@@ -113,7 +113,7 @@ function getPricingRevision() {
113
113
 
114
114
  // Read-only snapshot of where pricing data came from and how stale it is.
115
115
  // Surfaced by `status --json` so a $0 cost can be triaged as "not collected"
116
- // vs "not priced" without digging into cache files (docs/upstream-comparison-plan.md §1 A3).
116
+ // vs "not priced" without digging into cache files (docs/archive/upstream-2026-11-03.md A3).
117
117
  function getPricingMeta() {
118
118
  return {
119
119
  source: state.source,
@@ -2,7 +2,7 @@
2
2
 
3
3
  // Read-only pricing-coverage and unknown-model alignment analysis over the
4
4
  // local last-wins queue baseline (queue.jsonl). Used by `doctor`
5
- // (docs/upstream-comparison-plan.md §2 B3 + §3 C2 dry-run). This module never
5
+ // (docs/archive/upstream-2026-11-03.md B3 + §3 C2 dry-run). This module never
6
6
  // writes anything; the alignment preview is a dry-run projection only and does
7
7
  // NOT change any bucket's stored or displayed model.
8
8
 
@@ -68,9 +68,38 @@ function formatBytes(bytes) {
68
68
  return `${fixed} ${units[i]}`;
69
69
  }
70
70
 
71
+ function formatDuration(ms) {
72
+ const n = Number(ms);
73
+ if (!Number.isFinite(n) || n < 0) return "0s";
74
+ if (n < 1) return "0s";
75
+ if (n < 1000) return `${Math.round(n)}ms`;
76
+ const seconds = n / 1000;
77
+ if (seconds < 60) return `${seconds.toFixed(seconds < 10 ? 1 : 0)}s`;
78
+ const minutes = Math.floor(seconds / 60);
79
+ if (minutes < 60) return `${minutes}m ${String(Math.round(seconds - minutes * 60)).padStart(2, "0")}s`;
80
+ const hours = Math.floor(minutes / 60);
81
+ return `${hours}h ${String(minutes - hours * 60).padStart(2, "0")}m`;
82
+ }
83
+
84
+ /**
85
+ * The one line that says which collector machine produced this output.
86
+ *
87
+ * One account has two collector machines, and command output gets pasted into
88
+ * release checklists and issue trackers. Without the identity, "the machine"
89
+ * is ambiguous — the device name is the cloud's own name for it
90
+ * (docs/cli-contract.md §2.2), so it matches the dashboard device card.
91
+ */
92
+ function formatDeviceLine(identity, { label = "Device", indent = "- " } = {}) {
93
+ const name = identity?.name || "unknown machine";
94
+ const id = identity?.device_id;
95
+ return `${indent}${label}: ${name}${id ? ` (id ${id})` : " (not paired)"}`;
96
+ }
97
+
71
98
  module.exports = {
72
99
  createProgress,
73
100
  renderBar,
74
101
  formatNumber,
75
102
  formatBytes,
103
+ formatDuration,
104
+ formatDeviceLine,
76
105
  };