Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

cursorUsageReader.ts

267 lines10.3 KB

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