Open History to see the last commit
1// Node fs reads CLI credentials, and crypto hashes account IDs for deduplication.
2// @effect-diagnostics nodeBuiltinImport:off
3import * as NodeFSP from "node:fs/promises";
4import * as NodeCrypto from "node:crypto";
5import * as NodeTimersPromises from "node:timers/promises";
6
7import type { UsageRecord } from "./usageTranscripts.ts";
8import { readMacCursorAccessToken } from "../provider/cursorCredentialStore.ts";
9
10function object(value: unknown): Record<string, unknown> {
11 return typeof value === "object" && value !== null && !Array.isArray(value)
12 ? (value as Record<string, unknown>)
13 : {};
14}
15
16function tokens(value: unknown): number {
17 return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0;
18}
19
20export interface CursorAccountUsageReadResult {
21 readonly accountKey: string | null;
22 readonly records: readonly UsageRecord[];
23 readonly missing: boolean;
24 readonly error: string | null;
25}
26
27const accountHash = (value: string) => NodeCrypto.createHash("sha256").update(value).digest("hex");
28
29function canonicalJson(value: unknown): string {
30 if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
31 if (value !== null && typeof value === "object") {
32 return `{${Object.entries(value)
33 .sort(([a], [b]) => a.localeCompare(b))
34 .map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`)
35 .join(",")}}`;
36 }
37 return JSON.stringify(value) ?? "null";
38}
39
40/** Find the longest exact suffix/prefix overlap in linear time. */
41function boundaryOverlap(previous: readonly string[], current: readonly string[]): number {
42 const sequence = [...current, "", ...previous];
43 const lengths = Array.from({ length: sequence.length }, () => 0);
44 for (let index = 1; index < sequence.length; index++) {
45 let length = lengths[index - 1]!;
46 while (length > 0 && sequence[index] !== sequence[length]) length = lengths[length - 1]!;
47 if (sequence[index] === sequence[length]) length++;
48 lengths[index] = length;
49 }
50 return lengths.at(-1) ?? 0;
51}
52
53/** Dashboard usage includes headless agents and reports fresh input separately from cache reads. */
54export async function readCursorAccountUsage(
55 credentialSource: string | { readonly kind: "keychain" },
56 sinceMs: number,
57 endDate: number,
58 request: (url: string, init: RequestInit) => Promise<Response> = globalThis.fetch,
59 keychainToken: () => Promise<string | null> = readMacCursorAccessToken,
60): Promise<CursorAccountUsageReadResult> {
61 let accessToken: unknown;
62 try {
63 accessToken =
64 typeof credentialSource === "string"
65 ? object(JSON.parse(await NodeFSP.readFile(credentialSource, "utf8"))).accessToken
66 : await keychainToken();
67 } catch (cause) {
68 const missing = typeof credentialSource === "string" && object(cause).code === "ENOENT";
69 return {
70 accountKey: null,
71 records: [],
72 missing,
73 error: missing
74 ? null
75 : typeof credentialSource === "string"
76 ? "Cursor credentials could not be read."
77 : "Cursor Keychain credentials could not be read.",
78 };
79 }
80 if (typeof accessToken !== "string" || !accessToken) {
81 return {
82 accountKey: null,
83 records: [],
84 missing: true,
85 error:
86 typeof credentialSource === "string"
87 ? null
88 : "Cursor account history needs a macOS Keychain CLI login on this server.",
89 };
90 }
91 let accountKey: string | null = null;
92 try {
93 const payload = accessToken.split(".")[1];
94 const subject = object(
95 JSON.parse(Buffer.from(payload ?? "", "base64url").toString("utf8")),
96 ).sub;
97 if (typeof subject !== "string" || !subject) throw new Error("Invalid authentication");
98 const userId = subject.split("|").at(-1);
99 if (!userId) throw new Error("Invalid authentication");
100 accountKey = accountHash(subject);
101 if (!Number.isFinite(sinceMs) || !Number.isFinite(endDate) || sinceMs < 0 || sinceMs > endDate)
102 throw new Error("Invalid date window");
103 const deadline = AbortSignal.timeout(60_000);
104 const records: UsageRecord[] = [];
105 const occurrences = new Map<string, number>();
106 const pages: unknown[][] = [];
107 let completed = false;
108 const pageSize = 1000;
109 let total: number | undefined;
110 for (let page = 1; ; page++) {
111 // A count can include overlapping page boundaries. Allow room to
112 // reconcile them without imposing a fixed account-size limit.
113 if (page > (total === undefined ? 1000 : Math.ceil(total / pageSize) * 2 + 1)) {
114 throw new Error("Account usage page limit exceeded");
115 }
116 const response = await request("https://cursor.com/api/dashboard/get-filtered-usage-events", {
117 method: "POST",
118 redirect: "error",
119 signal: AbortSignal.any([deadline, AbortSignal.timeout(10_000)]),
120 headers: {
121 "Content-Type": "application/json",
122 Origin: "https://cursor.com",
123 Cookie: `WorkosCursorSessionToken=${encodeURIComponent(`${userId}::${accessToken}`)}`,
124 },
125 body: JSON.stringify({
126 page,
127 pageSize,
128 startDate: String(sinceMs),
129 endDate: String(endDate),
130 }),
131 });
132 if (response.status === 401 || response.status === 403) {
133 return {
134 accountKey,
135 records: [],
136 missing: false,
137 error: "Sign in to Cursor again to read account usage.",
138 };
139 }
140 if (!response.ok) throw new Error("Account usage request failed");
141 const parsed: unknown = await response.json();
142 if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
143 throw new Error("Invalid account usage page");
144 }
145 const body = object(parsed);
146 const keys = Object.keys(body);
147 if ("error" in body || "message" in body || "code" in body)
148 throw new Error("Account usage error response");
149 const count = keys.length === 0 ? 0 : body.totalUsageEventsCount;
150 const events =
151 keys.length === 0 || (keys.length === 1 && keys[0] === "totalUsageEventsCount")
152 ? []
153 : body.usageEventsDisplay;
154 if (
155 (count !== undefined &&
156 (typeof count !== "number" ||
157 !Number.isSafeInteger(count) ||
158 count < 0 ||
159 (total !== undefined && count !== total))) ||
160 !Array.isArray(events) ||
161 events.length > pageSize ||
162 (count === undefined && !Array.isArray(body.usageEventsDisplay))
163 ) {
164 throw new Error("Inconsistent account usage page");
165 }
166 if (typeof count === "number") total = count;
167 pages.push(events);
168 if (events.length < pageSize) {
169 completed = true;
170 break;
171 }
172 }
173 if (!completed) throw new Error("Account usage page limit exceeded");
174 const rawCount = pages.reduce((sum, page) => sum + page.length, 0);
175 if (total !== undefined && rawCount < total) throw new Error("Incomplete account usage pages");
176 let removalsRemaining = total === undefined ? 0 : rawCount - total;
177 let previousKeys: string[] = [];
178 for (const events of pages) {
179 const eventKeys =
180 removalsRemaining > 0 ? events.map((event) => accountHash(canonicalJson(event))) : [];
181 const removalCount = Math.min(removalsRemaining, boundaryOverlap(previousKeys, eventKeys));
182 removalsRemaining -= removalCount;
183 previousKeys = eventKeys;
184 for (const raw of events.slice(removalCount)) {
185 const event = object(raw);
186 const usage = object(event.tokenUsage);
187 if (event.tokenUsage === undefined || event.tokenUsage === null) continue;
188 for (const key of [
189 "inputTokens",
190 "outputTokens",
191 "cacheReadTokens",
192 "cacheWriteTokens",
193 "totalCents",
194 ]) {
195 const value = usage[key];
196 if (
197 value !== undefined &&
198 (typeof value !== "number" || !Number.isFinite(value) || value < 0)
199 ) {
200 throw new Error("Invalid account usage totals");
201 }
202 }
203 const timestampMs =
204 typeof event.timestamp === "string" && event.timestamp.trim() !== ""
205 ? Number(event.timestamp)
206 : event.timestamp;
207 if (
208 typeof timestampMs !== "number" ||
209 !Number.isFinite(timestampMs) ||
210 typeof event.model !== "string" ||
211 !event.model
212 )
213 throw new Error("Invalid account usage event");
214 if (timestampMs < sinceMs || timestampMs > endDate) continue;
215 const totals = {
216 uncachedInputTokens: tokens(usage.inputTokens),
217 cachedInputTokens: tokens(usage.cacheReadTokens),
218 cacheCreationTokens: tokens(usage.cacheWriteTokens),
219 outputTokens: tokens(usage.outputTokens),
220 reasoningTokens: 0,
221 };
222 const reportedCostUsd =
223 typeof usage.totalCents === "number" ? usage.totalCents / 100 : null;
224 const sessionId = typeof event.conversationId === "string" ? event.conversationId : "";
225 // No event ID is provided. Preserve identical billed rows with an occurrence index.
226 const key = accountHash(
227 JSON.stringify([timestampMs, event.model, sessionId, totals, reportedCostUsd]),
228 );
229 const occurrence = occurrences.get(key) ?? 0;
230 occurrences.set(key, occurrence + 1);
231 records.push({
232 provider: "cursor",
233 timestampMs,
234 model: event.model,
235 sessionId,
236 totals,
237 reportedCostUsd,
238 fast: false,
239 dedupeKey: `cursor-account:${accountKey}:${key}:${occurrence}`,
240 });
241 }
242 await NodeTimersPromises.setImmediate();
243 }
244 if (removalsRemaining !== 0) throw new Error("Inconsistent account usage boundaries");
245 return { accountKey, records, missing: false, error: null };
246 } catch {
247 return {
248 accountKey,
249 records: [],
250 missing: false,
251 error: "Cursor account usage could not be read.",
252 };
253 }
254}