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

cursorUsageReader.ts

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