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