tokenusage-cli 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -0
- package/LICENSE +22 -0
- package/README.md +94 -0
- package/THIRD_PARTY_NOTICES.md +140 -0
- package/bin/tokenusage.js +69 -0
- package/package.json +59 -0
- package/src/cli.js +134 -0
- package/src/commands/device-login.js +205 -0
- package/src/commands/diagnostics.js +38 -0
- package/src/commands/doctor.js +110 -0
- package/src/commands/init.js +2436 -0
- package/src/commands/sessions.js +29 -0
- package/src/commands/status.js +1747 -0
- package/src/commands/sync.js +7934 -0
- package/src/commands/uninstall.js +312 -0
- package/src/lib/account-usage-dedup.js +267 -0
- package/src/lib/antigravity-paths.js +48 -0
- package/src/lib/ark-agent-plan-limits.js +438 -0
- package/src/lib/ark-coding-plan-limits.js +537 -0
- package/src/lib/async-queue-reader.js +138 -0
- package/src/lib/atomic-json.js +27 -0
- package/src/lib/bearer-token.js +11 -0
- package/src/lib/categorizer-utils.js +232 -0
- package/src/lib/claude-categorizer.js +1343 -0
- package/src/lib/claude-config.js +279 -0
- package/src/lib/claude-user-identity.js +56 -0
- package/src/lib/cli-ui.js +179 -0
- package/src/lib/cloud-account.js +541 -0
- package/src/lib/cloud-device-token.js +141 -0
- package/src/lib/cloud-sync-prefs.js +14 -0
- package/src/lib/cloud-usage-reset.js +115 -0
- package/src/lib/codex-config.js +595 -0
- package/src/lib/codex-context-breakdown.js +806 -0
- package/src/lib/codex-model-attribution.js +128 -0
- package/src/lib/codex-rollout-parser.js +1471 -0
- package/src/lib/codex-service-tier.js +49 -0
- package/src/lib/codex-token-refresh.js +140 -0
- package/src/lib/codex-token-usage.js +195 -0
- package/src/lib/codex-usage-record.js +195 -0
- package/src/lib/command-runner.js +313 -0
- package/src/lib/commandcode-limits.js +317 -0
- package/src/lib/context-health.js +124 -0
- package/src/lib/cursor-config.js +605 -0
- package/src/lib/cursor-store.js +1918 -0
- package/src/lib/debug-flags.js +7 -0
- package/src/lib/devin-limits.js +249 -0
- package/src/lib/devin-usage.js +212 -0
- package/src/lib/diagnostics.js +383 -0
- package/src/lib/doctor.js +385 -0
- package/src/lib/dumate.js +95 -0
- package/src/lib/fs.js +455 -0
- package/src/lib/function-url.js +14 -0
- package/src/lib/gemini-config.js +291 -0
- package/src/lib/git-outcomes.js +243 -0
- package/src/lib/grok-context-breakdown.js +890 -0
- package/src/lib/grok-hook.js +360 -0
- package/src/lib/grok-limits.js +865 -0
- package/src/lib/grok-usage.js +98 -0
- package/src/lib/heatmap-compact.js +114 -0
- package/src/lib/ingest-sanitize.js +41 -0
- package/src/lib/init-flow.js +42 -0
- package/src/lib/install-resolver.js +170 -0
- package/src/lib/jsonl-lines.js +134 -0
- package/src/lib/kimi-model-repair.js +173 -0
- package/src/lib/kimi-profile.js +61 -0
- package/src/lib/kimi-session.js +216 -0
- package/src/lib/local-api.js +3588 -0
- package/src/lib/machine-id.js +238 -0
- package/src/lib/multi-install-parser.js +113 -0
- package/src/lib/notify-command.js +38 -0
- package/src/lib/omp-hook.js +589 -0
- package/src/lib/openclaw-cli.js +104 -0
- package/src/lib/openclaw-hook.js +375 -0
- package/src/lib/openclaw-session-plugin.js +560 -0
- package/src/lib/opencode-config.js +121 -0
- package/src/lib/opencode-go-limits.js +807 -0
- package/src/lib/outcomes-engine.js +253 -0
- package/src/lib/passive-mode.js +219 -0
- package/src/lib/pet-packages.js +722 -0
- package/src/lib/pricing/curated-overrides.json +822 -0
- package/src/lib/pricing/index.js +379 -0
- package/src/lib/pricing/litellm-fetcher.js +172 -0
- package/src/lib/pricing/matcher.js +456 -0
- package/src/lib/pricing/seed-snapshot.json +1 -0
- package/src/lib/progress.js +76 -0
- package/src/lib/project-usage-purge.js +117 -0
- package/src/lib/prompt.js +24 -0
- package/src/lib/provider-status.js +104 -0
- package/src/lib/proxy-env.js +489 -0
- package/src/lib/proxy-settings.js +163 -0
- package/src/lib/qoder-cn-cli-limits.js +119 -0
- package/src/lib/qoder-limits.js +880 -0
- package/src/lib/quiet-warnings.js +26 -0
- package/src/lib/rollout.js +25966 -0
- package/src/lib/runtime-config.js +259 -0
- package/src/lib/scan-roots.js +277 -0
- package/src/lib/sentry.js +231 -0
- package/src/lib/session-analytics.js +2972 -0
- package/src/lib/session-performance.js +237 -0
- package/src/lib/session-upload.js +379 -0
- package/src/lib/skill-usage.js +267 -0
- package/src/lib/skills-manager.js +1591 -0
- package/src/lib/source-metadata.js +48 -0
- package/src/lib/sqlite-reader.js +215 -0
- package/src/lib/star-cta.js +73 -0
- package/src/lib/subscription-manager.js +293 -0
- package/src/lib/subscriptions.js +508 -0
- package/src/lib/telemetry.js +193 -0
- package/src/lib/tracker-paths.js +16 -0
- package/src/lib/trae-cn-config.js +548 -0
- package/src/lib/trae-db.js +127 -0
- package/src/lib/trae-snapshot.js +230 -0
- package/src/lib/trae-sqlite.js +143 -0
- package/src/lib/trae-usage.js +121 -0
- package/src/lib/upload-queue.js +134 -0
- package/src/lib/upload-throttle.js +171 -0
- package/src/lib/usage-limits.js +4552 -0
- package/src/lib/wrapped-aggregator.js +236 -0
- package/src/lib/wsl-probe.js +281 -0
- package/src/lib/zcode-limits.js +1172 -0
- package/src/lib/zcode-reset-credits.js +66 -0
- package/test/cli-smoke.test.js +53 -0
- package/test/ingest-sanitize.test.js +162 -0
- package/test/quiet-warnings.test.js +53 -0
- package/test/session-upload.test.js +427 -0
|
@@ -0,0 +1,605 @@
|
|
|
1
|
+
const os = require("node:os");
|
|
2
|
+
const path = require("node:path");
|
|
3
|
+
const fs = require("node:fs");
|
|
4
|
+
|
|
5
|
+
const { readJson } = require("./fs");
|
|
6
|
+
const { readSqliteFirstValue } = require("./sqlite-reader");
|
|
7
|
+
|
|
8
|
+
// ── Path resolution ──
|
|
9
|
+
|
|
10
|
+
function resolveCursorPaths({ home, platform = process.platform, env = process.env } = {}) {
|
|
11
|
+
const h = home || os.homedir();
|
|
12
|
+
const pathForPlatform = platform === "win32" ? path.win32 : path.posix;
|
|
13
|
+
let appDir;
|
|
14
|
+
if (platform === "darwin") {
|
|
15
|
+
appDir = pathForPlatform.join(h, "Library", "Application Support", "Cursor");
|
|
16
|
+
} else if (platform === "win32") {
|
|
17
|
+
const appData =
|
|
18
|
+
((!home || h === os.homedir() || env !== process.env) &&
|
|
19
|
+
typeof env.APPDATA === "string" && env.APPDATA.trim()) ||
|
|
20
|
+
pathForPlatform.join(h, "AppData", "Roaming");
|
|
21
|
+
appDir = pathForPlatform.join(appData, "Cursor");
|
|
22
|
+
} else {
|
|
23
|
+
const xdg =
|
|
24
|
+
(typeof env.XDG_CONFIG_HOME === "string" && env.XDG_CONFIG_HOME.trim()) ||
|
|
25
|
+
pathForPlatform.join(h, ".config");
|
|
26
|
+
appDir = pathForPlatform.join(xdg, "Cursor");
|
|
27
|
+
}
|
|
28
|
+
return {
|
|
29
|
+
appDir,
|
|
30
|
+
stateDbPath: pathForPlatform.join(appDir, "User", "globalStorage", "state.vscdb"),
|
|
31
|
+
cliConfigPath: pathForPlatform.join(h, ".cursor", "cli-config.json"),
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function isCursorInstalled({ home, platform, env } = {}) {
|
|
36
|
+
const { appDir } = resolveCursorPaths({ home, platform, env });
|
|
37
|
+
try {
|
|
38
|
+
return fs.statSync(appDir).isDirectory();
|
|
39
|
+
} catch {
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// ── Auth token extraction ──
|
|
45
|
+
|
|
46
|
+
const CURSOR_ACCESS_TOKEN_SQL =
|
|
47
|
+
"SELECT value FROM ItemTable WHERE key = 'cursorAuth/accessToken';";
|
|
48
|
+
|
|
49
|
+
function cursorDebugLog(message, env = process.env) {
|
|
50
|
+
const dbg = String((env && env.TOKENUSAGE_DEBUG) || "").toLowerCase();
|
|
51
|
+
if (dbg === "1" || dbg === "true") {
|
|
52
|
+
process.stderr.write(`[cursor] ${message}\n`);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function readCursorAccessTokenFromStateDb(stateDbPath, deps = {}) {
|
|
57
|
+
return readSqliteFirstValue(stateDbPath, CURSOR_ACCESS_TOKEN_SQL, "value", {
|
|
58
|
+
execFileSync: deps.execFileSync,
|
|
59
|
+
requireFn: deps.requireFn,
|
|
60
|
+
env: deps.env,
|
|
61
|
+
stderr: deps.stderr,
|
|
62
|
+
label: "Cursor",
|
|
63
|
+
timeout: 5000,
|
|
64
|
+
maxBuffer: 1024 * 1024,
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Extract Cursor session cookie from local SQLite + cli-config.json.
|
|
70
|
+
* Returns { cookie, userId } or null on failure.
|
|
71
|
+
*
|
|
72
|
+
* Cookie format: WorkosCursorSessionToken=<userId>%3A%3A<jwt>
|
|
73
|
+
* - JWT from state.vscdb → ItemTable → cursorAuth/accessToken
|
|
74
|
+
* - userId from cli-config.json → authInfo.authId
|
|
75
|
+
* - native Cursor email/password: "auth0|user_XXXXX" → "user_XXXXX"
|
|
76
|
+
* - Google sign-in via WorkOS: "google-oauth2|<numeric>" → kept verbatim
|
|
77
|
+
* - other WorkOS subjects: "github|…", "oidc|…" → kept verbatim
|
|
78
|
+
*/
|
|
79
|
+
function extractCursorSessionToken({ home, platform, env, deps } = {}) {
|
|
80
|
+
const auth = extractCursorAuth({ home, platform, env, deps });
|
|
81
|
+
if (!auth) return null;
|
|
82
|
+
return { cookie: auth.cookie, userId: auth.userId };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Extract the Cursor web session and API bearer token from Cursor's own local
|
|
87
|
+
* login state. The raw access token is needed for Cursor's first-party Connect
|
|
88
|
+
* RPCs, while callers that only need the web cookie should continue using
|
|
89
|
+
* extractCursorSessionToken so the token is not propagated unnecessarily.
|
|
90
|
+
*/
|
|
91
|
+
function extractCursorAuth({ home, platform, env, deps } = {}) {
|
|
92
|
+
const { stateDbPath, cliConfigPath } = resolveCursorPaths({ home, platform, env });
|
|
93
|
+
|
|
94
|
+
// 1. Extract JWT from SQLite
|
|
95
|
+
if (!fs.existsSync(stateDbPath)) {
|
|
96
|
+
cursorDebugLog(`Cursor state DB not found at ${stateDbPath}`, deps?.env);
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
const jwt = readCursorAccessTokenFromStateDb(stateDbPath, deps);
|
|
100
|
+
if (!jwt || jwt.length < 10) return null;
|
|
101
|
+
|
|
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
|
+
}
|
|
107
|
+
if (!userId) return null;
|
|
108
|
+
|
|
109
|
+
// 3. Build cookie
|
|
110
|
+
const cookie = `WorkosCursorSessionToken=${userId}%3A%3A${jwt}`;
|
|
111
|
+
return { cookie, userId, accessToken: jwt };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// WorkOS OAuth subject prefixes Cursor accepts as-is in the session cookie.
|
|
115
|
+
// Verified against cursor.com/api/usage-summary (issue #88).
|
|
116
|
+
const WORKOS_OAUTH_SUBJECT_RE = /^(google-oauth2|github|oidc|auth0)\|[^|]+$/;
|
|
117
|
+
|
|
118
|
+
function normalizeCursorSubject(subject) {
|
|
119
|
+
if (!subject) return null;
|
|
120
|
+
// Native Cursor: "auth0|user_XXXXX" → strip provider prefix, return "user_XXXXX"
|
|
121
|
+
const native = subject.match(/\|(user_[A-Za-z0-9_]+)$/);
|
|
122
|
+
if (native) return native[1];
|
|
123
|
+
// WorkOS-bridged OAuth: keep the full "<provider>|<id>" subject
|
|
124
|
+
if (WORKOS_OAUTH_SUBJECT_RE.test(subject)) return subject;
|
|
125
|
+
return null;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function extractUserIdFromCliConfig(configPath) {
|
|
129
|
+
try {
|
|
130
|
+
const config = JSON.parse(fs.readFileSync(configPath, "utf8"));
|
|
131
|
+
return normalizeCursorSubject(config?.authInfo?.authId || "");
|
|
132
|
+
} catch {
|
|
133
|
+
return null;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function extractUserIdFromJwt(jwt) {
|
|
138
|
+
try {
|
|
139
|
+
const parts = jwt.split(".");
|
|
140
|
+
if (parts.length !== 3) return null;
|
|
141
|
+
const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString());
|
|
142
|
+
return normalizeCursorSubject(payload.sub || "");
|
|
143
|
+
} catch {
|
|
144
|
+
return null;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// ── API client ──
|
|
149
|
+
|
|
150
|
+
const CURSOR_CSV_URL = "https://cursor.com/api/dashboard/export-usage-events-csv?strategy=tokens";
|
|
151
|
+
const CURSOR_SUMMARY_URL = "https://cursor.com/api/usage-summary";
|
|
152
|
+
const CURSOR_RPC_ORIGIN = "https://api2.cursor.sh";
|
|
153
|
+
const CURSOR_SAND_ACCESS_URL = `${CURSOR_RPC_ORIGIN}/aiserver.v1.DashboardService/GetSandAccessStatus`;
|
|
154
|
+
const CURSOR_SAND_USAGE_URL = `${CURSOR_RPC_ORIGIN}/aiserver.v1.DashboardService/GetSandUsageStatus`;
|
|
155
|
+
const CURSOR_RPC_MAX_RESPONSE_BYTES = 64 * 1024;
|
|
156
|
+
const CURSOR_SOURCE_SCOPE = "account";
|
|
157
|
+
|
|
158
|
+
function isCursorFetchTimeout(err) {
|
|
159
|
+
return Boolean(err && (err.name === "TimeoutError" || err.name === "AbortError"));
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function remapCursorFetchTimeout(err) {
|
|
163
|
+
if (isCursorFetchTimeout(err)) {
|
|
164
|
+
throw new Error("Cursor API request timed out");
|
|
165
|
+
}
|
|
166
|
+
throw err;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const CURSOR_REDIRECT_HOSTS = new Set(["cursor.com", "www.cursor.com"]);
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Resolve a redirect `Location` before the session cookie is forwarded to it.
|
|
173
|
+
*
|
|
174
|
+
* The header is attacker-influenced in principle, and the next hop carries the
|
|
175
|
+
* Cursor session cookie, so an off-origin redirect would disclose it. Resolving
|
|
176
|
+
* against the request URL also handles a relative Location, which bare
|
|
177
|
+
* `fetch(location)` would reject.
|
|
178
|
+
*/
|
|
179
|
+
function resolveCursorRedirect(location, baseUrl) {
|
|
180
|
+
let url;
|
|
181
|
+
try {
|
|
182
|
+
url = new URL(location, baseUrl);
|
|
183
|
+
} catch {
|
|
184
|
+
throw new Error("Cursor API redirect to an untrusted origin");
|
|
185
|
+
}
|
|
186
|
+
if (url.protocol !== "https:" || !CURSOR_REDIRECT_HOSTS.has(url.hostname)) {
|
|
187
|
+
throw new Error("Cursor API redirect to an untrusted origin");
|
|
188
|
+
}
|
|
189
|
+
return url.toString();
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Fetch full usage CSV from Cursor API.
|
|
194
|
+
* Returns raw CSV string or throws on error.
|
|
195
|
+
*/
|
|
196
|
+
function fetchCursorUsageCsv({ cookie, timeoutMs = 30000, fetchImpl = fetch }) {
|
|
197
|
+
return fetchImpl(CURSOR_CSV_URL, {
|
|
198
|
+
method: "GET",
|
|
199
|
+
headers: {
|
|
200
|
+
Accept: "*/*",
|
|
201
|
+
Cookie: cookie,
|
|
202
|
+
Referer: "https://www.cursor.com/settings",
|
|
203
|
+
"User-Agent":
|
|
204
|
+
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
|
|
205
|
+
},
|
|
206
|
+
redirect: "manual",
|
|
207
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
208
|
+
}).then(async (res) => {
|
|
209
|
+
if (res.status === 401 || res.status === 403) {
|
|
210
|
+
throw new Error("Cursor session expired — re-login in Cursor to refresh");
|
|
211
|
+
}
|
|
212
|
+
if (res.status === 308 || res.status === 301 || res.status === 302) {
|
|
213
|
+
// Follow redirect once. Keep this hop on redirect:"manual" so the
|
|
214
|
+
// Location + Cookie are forwarded explicitly (cursor.com → www.cursor.com).
|
|
215
|
+
const location = res.headers.get("location");
|
|
216
|
+
if (!location) throw new Error("Cursor API redirect without Location header");
|
|
217
|
+
const target = resolveCursorRedirect(location, CURSOR_CSV_URL);
|
|
218
|
+
return fetchUrlRaw({ urlStr: target, cookie, timeoutMs, fetchImpl });
|
|
219
|
+
}
|
|
220
|
+
if (res.status !== 200) {
|
|
221
|
+
throw new Error(`Cursor API returned ${res.status}`);
|
|
222
|
+
}
|
|
223
|
+
return res.text();
|
|
224
|
+
}).catch(remapCursorFetchTimeout);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Fetch Cursor usage summary JSON.
|
|
229
|
+
* Returns parsed JSON body or throws on error.
|
|
230
|
+
*/
|
|
231
|
+
function fetchCursorUsageSummary({ cookie, timeoutMs = 30000, fetchImpl = fetch }) {
|
|
232
|
+
return fetchImpl(CURSOR_SUMMARY_URL, {
|
|
233
|
+
method: "GET",
|
|
234
|
+
headers: {
|
|
235
|
+
Accept: "application/json",
|
|
236
|
+
Cookie: cookie,
|
|
237
|
+
Referer: "https://www.cursor.com/settings",
|
|
238
|
+
"User-Agent":
|
|
239
|
+
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
|
|
240
|
+
},
|
|
241
|
+
redirect: "follow",
|
|
242
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
243
|
+
}).then(async (res) => {
|
|
244
|
+
if (res.status === 401 || res.status === 403) {
|
|
245
|
+
throw new Error("Cursor session expired — re-login in Cursor to refresh");
|
|
246
|
+
}
|
|
247
|
+
if (!res.ok) {
|
|
248
|
+
throw new Error(`Cursor API returned ${res.status}`);
|
|
249
|
+
}
|
|
250
|
+
return res.json();
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
function readProtoVarint(buffer, offset) {
|
|
255
|
+
let value = 0n;
|
|
256
|
+
let shift = 0n;
|
|
257
|
+
for (let i = offset; i < buffer.length && i < offset + 10; i += 1) {
|
|
258
|
+
const byte = buffer[i];
|
|
259
|
+
value |= BigInt(byte & 0x7f) << shift;
|
|
260
|
+
if ((byte & 0x80) === 0) return { value, offset: i + 1 };
|
|
261
|
+
shift += 7n;
|
|
262
|
+
}
|
|
263
|
+
throw new Error("Cursor API returned malformed protobuf");
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function readProtoFields(input) {
|
|
267
|
+
const buffer = Buffer.isBuffer(input) ? input : Buffer.from(input);
|
|
268
|
+
const fields = [];
|
|
269
|
+
let offset = 0;
|
|
270
|
+
while (offset < buffer.length) {
|
|
271
|
+
const tag = readProtoVarint(buffer, offset);
|
|
272
|
+
offset = tag.offset;
|
|
273
|
+
const fieldNumber = Number(tag.value >> 3n);
|
|
274
|
+
const wireType = Number(tag.value & 0x07n);
|
|
275
|
+
if (!Number.isInteger(fieldNumber) || fieldNumber <= 0) {
|
|
276
|
+
throw new Error("Cursor API returned malformed protobuf");
|
|
277
|
+
}
|
|
278
|
+
if (wireType === 0) {
|
|
279
|
+
const decoded = readProtoVarint(buffer, offset);
|
|
280
|
+
fields.push({ fieldNumber, wireType, value: decoded.value });
|
|
281
|
+
offset = decoded.offset;
|
|
282
|
+
} else if (wireType === 1) {
|
|
283
|
+
if (offset + 8 > buffer.length) throw new Error("Cursor API returned malformed protobuf");
|
|
284
|
+
fields.push({ fieldNumber, wireType, value: buffer.subarray(offset, offset + 8) });
|
|
285
|
+
offset += 8;
|
|
286
|
+
} else if (wireType === 2) {
|
|
287
|
+
const decodedLength = readProtoVarint(buffer, offset);
|
|
288
|
+
offset = decodedLength.offset;
|
|
289
|
+
const length = Number(decodedLength.value);
|
|
290
|
+
if (!Number.isSafeInteger(length) || length < 0 || offset + length > buffer.length) {
|
|
291
|
+
throw new Error("Cursor API returned malformed protobuf");
|
|
292
|
+
}
|
|
293
|
+
fields.push({ fieldNumber, wireType, value: buffer.subarray(offset, offset + length) });
|
|
294
|
+
offset += length;
|
|
295
|
+
} else if (wireType === 5) {
|
|
296
|
+
if (offset + 4 > buffer.length) throw new Error("Cursor API returned malformed protobuf");
|
|
297
|
+
fields.push({ fieldNumber, wireType, value: buffer.subarray(offset, offset + 4) });
|
|
298
|
+
offset += 4;
|
|
299
|
+
} else {
|
|
300
|
+
throw new Error("Cursor API returned unsupported protobuf wire type");
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
return fields;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function protoTimestampToIso(input) {
|
|
307
|
+
let seconds = null;
|
|
308
|
+
let nanos = 0n;
|
|
309
|
+
for (const field of readProtoFields(input)) {
|
|
310
|
+
if (field.fieldNumber === 1 && field.wireType === 0) seconds = field.value;
|
|
311
|
+
if (field.fieldNumber === 2 && field.wireType === 0) nanos = field.value;
|
|
312
|
+
}
|
|
313
|
+
if (seconds === null || nanos < 0n || nanos > 999_999_999n) return null;
|
|
314
|
+
const milliseconds = Number(seconds) * 1000 + Number(nanos) / 1_000_000;
|
|
315
|
+
if (!Number.isFinite(milliseconds)) return null;
|
|
316
|
+
try {
|
|
317
|
+
return new Date(milliseconds).toISOString();
|
|
318
|
+
} catch {
|
|
319
|
+
return null;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function decodeCursorSandAccessStatus(input) {
|
|
324
|
+
let state = 0;
|
|
325
|
+
let blockReason = 0;
|
|
326
|
+
for (const field of readProtoFields(input)) {
|
|
327
|
+
if (field.fieldNumber === 1 && field.wireType === 0) state = Number(field.value);
|
|
328
|
+
if (field.fieldNumber === 3 && field.wireType === 0) blockReason = Number(field.value);
|
|
329
|
+
}
|
|
330
|
+
return { state, blockReason, granted: state === 1 };
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function decodeCursorSandUsageStatus(input) {
|
|
334
|
+
const result = {
|
|
335
|
+
currentPeriodStart: null,
|
|
336
|
+
nextResetAt: null,
|
|
337
|
+
usagePercent: null,
|
|
338
|
+
includedLimitZero: false,
|
|
339
|
+
availableBankedResetCount: 0,
|
|
340
|
+
usesPooledEnterpriseAllowance: false,
|
|
341
|
+
hasAvailableUsage: false,
|
|
342
|
+
hasNonZeroIncludedLimit: false,
|
|
343
|
+
};
|
|
344
|
+
for (const field of readProtoFields(input)) {
|
|
345
|
+
if (field.fieldNumber === 1 && field.wireType === 2) {
|
|
346
|
+
result.currentPeriodStart = protoTimestampToIso(field.value);
|
|
347
|
+
} else if (field.fieldNumber === 2 && field.wireType === 2) {
|
|
348
|
+
result.nextResetAt = protoTimestampToIso(field.value);
|
|
349
|
+
} else if (field.fieldNumber === 3 && field.wireType === 1) {
|
|
350
|
+
result.usagePercent = field.value.readDoubleLE(0);
|
|
351
|
+
} else if (field.fieldNumber === 4 && field.wireType === 0) {
|
|
352
|
+
result.includedLimitZero = field.value !== 0n;
|
|
353
|
+
} else if (field.fieldNumber === 5 && field.wireType === 0) {
|
|
354
|
+
result.availableBankedResetCount = Number(field.value);
|
|
355
|
+
} else if (field.fieldNumber === 6 && field.wireType === 0) {
|
|
356
|
+
result.usesPooledEnterpriseAllowance = field.value !== 0n;
|
|
357
|
+
} else if (field.fieldNumber === 7 && field.wireType === 0) {
|
|
358
|
+
result.hasAvailableUsage = field.value !== 0n;
|
|
359
|
+
} else if (field.fieldNumber === 8 && field.wireType === 0) {
|
|
360
|
+
result.hasNonZeroIncludedLimit = field.value !== 0n;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
if (!Number.isFinite(result.usagePercent)) result.usagePercent = null;
|
|
364
|
+
return result;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
async function fetchCursorProtoRpc({ url, accessToken, timeoutMs = 15000, fetchImpl = fetch }) {
|
|
368
|
+
const res = await fetchImpl(url, {
|
|
369
|
+
method: "POST",
|
|
370
|
+
headers: {
|
|
371
|
+
Authorization: `Bearer ${accessToken}`,
|
|
372
|
+
"Content-Type": "application/proto",
|
|
373
|
+
"Connect-Protocol-Version": "1",
|
|
374
|
+
},
|
|
375
|
+
body: Buffer.alloc(0),
|
|
376
|
+
redirect: "error",
|
|
377
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
378
|
+
});
|
|
379
|
+
if (res.status === 401 || res.status === 403) {
|
|
380
|
+
throw new Error("Cursor session expired — re-login in Cursor to refresh");
|
|
381
|
+
}
|
|
382
|
+
if (res.status !== 200) throw new Error(`Cursor API returned ${res.status}`);
|
|
383
|
+
const contentType = String(res.headers?.get?.("content-type") || "").toLowerCase();
|
|
384
|
+
if (!contentType.startsWith("application/proto")) {
|
|
385
|
+
throw new Error("Cursor API returned an unexpected response type");
|
|
386
|
+
}
|
|
387
|
+
const body = Buffer.from(await res.arrayBuffer());
|
|
388
|
+
if (body.length > CURSOR_RPC_MAX_RESPONSE_BYTES) {
|
|
389
|
+
throw new Error("Cursor API returned an oversized response");
|
|
390
|
+
}
|
|
391
|
+
return body;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
async function fetchCursorSandAccessStatus({ accessToken, timeoutMs, fetchImpl = fetch }) {
|
|
395
|
+
const body = await fetchCursorProtoRpc({
|
|
396
|
+
url: CURSOR_SAND_ACCESS_URL,
|
|
397
|
+
accessToken,
|
|
398
|
+
timeoutMs,
|
|
399
|
+
fetchImpl,
|
|
400
|
+
});
|
|
401
|
+
return decodeCursorSandAccessStatus(body);
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
async function fetchCursorSandUsageStatus({ accessToken, timeoutMs, fetchImpl = fetch }) {
|
|
405
|
+
const body = await fetchCursorProtoRpc({
|
|
406
|
+
url: CURSOR_SAND_USAGE_URL,
|
|
407
|
+
accessToken,
|
|
408
|
+
timeoutMs,
|
|
409
|
+
fetchImpl,
|
|
410
|
+
});
|
|
411
|
+
return decodeCursorSandUsageStatus(body);
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
function fetchUrlRaw({ urlStr, cookie, timeoutMs = 30000, fetchImpl = fetch }) {
|
|
415
|
+
return fetchImpl(urlStr, {
|
|
416
|
+
method: "GET",
|
|
417
|
+
headers: {
|
|
418
|
+
Accept: "*/*",
|
|
419
|
+
Cookie: cookie,
|
|
420
|
+
Referer: "https://www.cursor.com/settings",
|
|
421
|
+
"User-Agent":
|
|
422
|
+
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
|
|
423
|
+
},
|
|
424
|
+
// Keep manual: the previous hop did not follow a second redirect.
|
|
425
|
+
// redirect:"follow" would turn a second 301/302/308 into a silent
|
|
426
|
+
// success and may drop the explicit Cookie on a cross-host hop.
|
|
427
|
+
redirect: "manual",
|
|
428
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
429
|
+
}).then(async (res) => {
|
|
430
|
+
if (res.status !== 200) {
|
|
431
|
+
throw new Error(`Cursor API returned ${res.status} from ${urlStr}`);
|
|
432
|
+
}
|
|
433
|
+
return res.text();
|
|
434
|
+
}).catch(remapCursorFetchTimeout);
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
// ── CSV parsing ──
|
|
438
|
+
|
|
439
|
+
/**
|
|
440
|
+
* Parse Cursor usage CSV into structured records.
|
|
441
|
+
*
|
|
442
|
+
* Column order has changed multiple times (e.g. new "Cloud Agent ID",
|
|
443
|
+
* "Automation ID" columns inserted before "Kind"). Resolve columns by
|
|
444
|
+
* header name instead of fixed index so the parser keeps working across
|
|
445
|
+
* future Cursor updates.
|
|
446
|
+
*
|
|
447
|
+
* Known required columns: Date, Model, Input (w/ Cache Write),
|
|
448
|
+
* Input (w/o Cache Write), Cache Read, Output Tokens, Total Tokens, Cost.
|
|
449
|
+
* Optional: Kind, Max Mode.
|
|
450
|
+
*/
|
|
451
|
+
function parseCursorCsv(csvText) {
|
|
452
|
+
const lines = csvText.split("\n").filter((l) => l.trim().length > 0);
|
|
453
|
+
if (lines.length < 2) return [];
|
|
454
|
+
|
|
455
|
+
const headerFields = parseCsvLine(lines[0]).map((f) => stripQuotes(f));
|
|
456
|
+
const columnIndex = new Map();
|
|
457
|
+
for (let i = 0; i < headerFields.length; i++) {
|
|
458
|
+
columnIndex.set(headerFields[i], i);
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
const dateIdx = columnIndex.get("Date");
|
|
462
|
+
const modelIdx = columnIndex.get("Model");
|
|
463
|
+
const inputWithIdx = columnIndex.get("Input (w/ Cache Write)");
|
|
464
|
+
const inputWithoutIdx = columnIndex.get("Input (w/o Cache Write)");
|
|
465
|
+
const cacheReadIdx = columnIndex.get("Cache Read");
|
|
466
|
+
const outputIdx = columnIndex.get("Output Tokens");
|
|
467
|
+
const totalIdx = columnIndex.get("Total Tokens");
|
|
468
|
+
const costIdx = columnIndex.get("Cost");
|
|
469
|
+
const kindIdx = columnIndex.get("Kind");
|
|
470
|
+
const maxModeIdx = columnIndex.get("Max Mode");
|
|
471
|
+
|
|
472
|
+
const required = [dateIdx, modelIdx, inputWithIdx, inputWithoutIdx, cacheReadIdx, outputIdx, totalIdx, costIdx];
|
|
473
|
+
if (required.some((idx) => idx === undefined)) return [];
|
|
474
|
+
|
|
475
|
+
const minFields = Math.max(...required) + 1;
|
|
476
|
+
|
|
477
|
+
const records = [];
|
|
478
|
+
for (let i = 1; i < lines.length; i++) {
|
|
479
|
+
const fields = parseCsvLine(lines[i]);
|
|
480
|
+
if (!fields || fields.length < minFields) continue;
|
|
481
|
+
|
|
482
|
+
const inputWithCache = toNum(fields[inputWithIdx]);
|
|
483
|
+
const inputWithoutCache = toNum(fields[inputWithoutIdx]);
|
|
484
|
+
const record = {
|
|
485
|
+
date: stripQuotes(fields[dateIdx]),
|
|
486
|
+
kind: kindIdx !== undefined ? stripQuotes(fields[kindIdx]) : "unknown",
|
|
487
|
+
model: stripQuotes(fields[modelIdx]),
|
|
488
|
+
maxMode: maxModeIdx !== undefined ? stripQuotes(fields[maxModeIdx]) : "No",
|
|
489
|
+
sourceScope: CURSOR_SOURCE_SCOPE,
|
|
490
|
+
billableKind: isCursorBillableKind(kindIdx !== undefined ? fields[kindIdx] : "unknown")
|
|
491
|
+
? "billable"
|
|
492
|
+
: "non_billable",
|
|
493
|
+
inputTokens: inputWithoutCache,
|
|
494
|
+
cacheWriteTokens: Math.max(0, inputWithCache - inputWithoutCache),
|
|
495
|
+
cacheReadTokens: toNum(fields[cacheReadIdx]),
|
|
496
|
+
outputTokens: toNum(fields[outputIdx]),
|
|
497
|
+
totalTokens: toNum(fields[totalIdx]),
|
|
498
|
+
cost: toFloat(fields[costIdx]),
|
|
499
|
+
};
|
|
500
|
+
|
|
501
|
+
if (record.totalTokens <= 0 && record.inputTokens <= 0 && record.outputTokens <= 0) continue;
|
|
502
|
+
|
|
503
|
+
records.push(record);
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
return records;
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
/**
|
|
510
|
+
* Normalize a Cursor CSV record to Token Usage's standard token format.
|
|
511
|
+
*/
|
|
512
|
+
function normalizeCursorUsage(record) {
|
|
513
|
+
const inputTokens = Math.max(0, Math.floor(record.inputTokens || 0));
|
|
514
|
+
const cacheWrite = Math.max(0, Math.floor(record.cacheWriteTokens || 0));
|
|
515
|
+
const cacheRead = Math.max(0, Math.floor(record.cacheReadTokens || 0));
|
|
516
|
+
const outputTokens = Math.max(0, Math.floor(record.outputTokens || 0));
|
|
517
|
+
const totalTokens = inputTokens + outputTokens + cacheWrite + cacheRead;
|
|
518
|
+
return {
|
|
519
|
+
input_tokens: inputTokens,
|
|
520
|
+
cached_input_tokens: cacheRead,
|
|
521
|
+
cache_creation_input_tokens: cacheWrite,
|
|
522
|
+
output_tokens: outputTokens,
|
|
523
|
+
reasoning_output_tokens: 0,
|
|
524
|
+
total_tokens: totalTokens,
|
|
525
|
+
// Usage tracking and billing are orthogonal: a Cursor Enterprise /
|
|
526
|
+
// Included-in-Pro request still consumes tokens even when the user
|
|
527
|
+
// pays nothing for them. Cost is computed independently from
|
|
528
|
+
// per-column tokens × MODEL_PRICING (see computeRowCost — it never
|
|
529
|
+
// reads this field), while the dashboard headline reads
|
|
530
|
+
// billable_total_tokens. Writing 0 here silently hides non-billable
|
|
531
|
+
// Cursor usage from the headline once any other source pushes the
|
|
532
|
+
// aggregate billable above 0 (see GitHub issue #106).
|
|
533
|
+
// isCursorBillableKind is retained for a future paid-vs-included
|
|
534
|
+
// breakdown via a separate is_billable field, not by overloading the
|
|
535
|
+
// token count.
|
|
536
|
+
billable_total_tokens: totalTokens,
|
|
537
|
+
};
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
function isCursorBillableKind(kind) {
|
|
541
|
+
const normalized = String(kind || "").trim().toLowerCase();
|
|
542
|
+
if (!normalized) return true;
|
|
543
|
+
if (normalized.includes("no charge")) return false;
|
|
544
|
+
if (normalized === "free") return false;
|
|
545
|
+
return true;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
// ── CSV helpers ──
|
|
549
|
+
|
|
550
|
+
function parseCsvLine(line) {
|
|
551
|
+
const fields = [];
|
|
552
|
+
let current = "";
|
|
553
|
+
let inQuotes = false;
|
|
554
|
+
for (let i = 0; i < line.length; i++) {
|
|
555
|
+
const ch = line[i];
|
|
556
|
+
if (ch === '"') {
|
|
557
|
+
inQuotes = !inQuotes;
|
|
558
|
+
current += ch;
|
|
559
|
+
} else if (ch === "," && !inQuotes) {
|
|
560
|
+
fields.push(current.trim());
|
|
561
|
+
current = "";
|
|
562
|
+
} else {
|
|
563
|
+
current += ch;
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
fields.push(current.trim());
|
|
567
|
+
return fields;
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
function stripQuotes(s) {
|
|
571
|
+
if (!s) return "";
|
|
572
|
+
const trimmed = s.trim();
|
|
573
|
+
if (trimmed.startsWith('"') && trimmed.endsWith('"')) {
|
|
574
|
+
return trimmed.slice(1, -1);
|
|
575
|
+
}
|
|
576
|
+
return trimmed;
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
function toNum(s) {
|
|
580
|
+
const n = Number(stripQuotes(s));
|
|
581
|
+
return Number.isFinite(n) && n >= 0 ? Math.floor(n) : 0;
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
function toFloat(s) {
|
|
585
|
+
const cleaned = stripQuotes(s).replace(/[$,]/g, "");
|
|
586
|
+
const n = Number(cleaned);
|
|
587
|
+
return Number.isFinite(n) ? n : 0;
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
module.exports = {
|
|
591
|
+
resolveCursorPaths,
|
|
592
|
+
isCursorInstalled,
|
|
593
|
+
readCursorAccessTokenFromStateDb,
|
|
594
|
+
extractCursorAuth,
|
|
595
|
+
extractCursorSessionToken,
|
|
596
|
+
fetchCursorUsageCsv,
|
|
597
|
+
fetchCursorUsageSummary,
|
|
598
|
+
decodeCursorSandAccessStatus,
|
|
599
|
+
decodeCursorSandUsageStatus,
|
|
600
|
+
fetchCursorSandAccessStatus,
|
|
601
|
+
fetchCursorSandUsageStatus,
|
|
602
|
+
parseCursorCsv,
|
|
603
|
+
isCursorBillableKind,
|
|
604
|
+
normalizeCursorUsage,
|
|
605
|
+
};
|