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

accountUsage.ts

369 lines14.2 KB

1import type { UsageRecord } from "@t3tools/provider-core/server/usage";
2import * as Crypto from "effect/Crypto";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Base64Url from "effect/encoding/Base64Url";
6import * as Hex from "effect/encoding/Hex";
7import * as Fiber from "effect/Fiber";
8import * as FileSystem from "effect/FileSystem";
9import * as FetchHttpClient from "effect/http/FetchHttpClient";
10import * as HttpClient from "effect/http/HttpClient";
11import * as HttpClientRequest from "effect/http/HttpClientRequest";
12import * as PlatformError from "effect/PlatformError";
13import * as Result from "effect/Result";
14import * as Schema from "effect/Schema";
15​
16import * as CursorKeychain from "./CursorKeychain.ts";
17​
18function object(value: unknown): Record<string, unknown> {
19 return typeof value === "object" && value !== null && !Array.isArray(value)
20 ? (value as Record<string, unknown>)
21 : {};
23​
24function tokens(value: unknown): number {
25 return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0;
27​
28/**
29 * Grok resolves through xAI's first-party entry, which has no bare alias.
30 */
31export function cursorRateModel(model: string): string {
32 const base = model
33 .replace(/^cursor-/, "")
34 .replace(/(?:-thinking)?(?:-(?:none|minimal|low|medium|high|xhigh|max))?(?:-fast)?$/, "");
35 return base.startsWith("grok-") ? `xai/${base}` : base;
37​
38export interface CursorAccountUsageReadResult {
39 readonly accountKey: string | null;
40 readonly records: readonly UsageRecord[];
41 readonly missing: boolean;
42 readonly error: string | null;
44​
45class CursorAccountUsageInvalidError extends Schema.TaggedError<CursorAccountUsageInvalidError>()(
46 "CursorAccountUsageInvalidError",
47 { reason: Schema.String },
48) {}
49​
50const invalid = (reason: string) => Effect.fail(new CursorAccountUsageInvalidError({ reason }));
51​
52const decodeJson = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown));
53​
54const pageRequestBody = (page: number, pageSize: number, sinceMs: number, endDate: number) =>
55 JSON.stringify({ page, pageSize, startDate: String(sinceMs), endDate: String(endDate) });
56​
57const billedEventIdentity = (...fields: readonly unknown[]) => JSON.stringify(fields);
58​
59const textEncoder = new TextEncoder();
60​
61const accountHash = Effect.fn("accountHash")(function* (value: string) {
62 const crypto = yield* Crypto.Crypto;
63 return Hex.encode(yield* crypto.digest("SHA-256", textEncoder.encode(value)));
64});
65​
66function canonicalJson(value: unknown): string {
67 if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
68 if (value !== null && typeof value === "object") {
69 return `{${Object.entries(value)
70 .sort(([a], [b]) => a.localeCompare(b))
71 .map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`)
72 .join(",")}}`;
73 }
74 return JSON.stringify(value) ?? "null";
76​
77function boundaryOverlap(previous: readonly string[], current: readonly string[]): number {
78 const sequence = [...current, "", ...previous];
79 const lengths = Array.from({ length: sequence.length }, () => 0);
80 for (let index = 1; index < sequence.length; index++) {
81 let length = lengths[index - 1]!;
82 while (length > 0 && sequence[index] !== sequence[length]) length = lengths[length - 1]!;
83 if (sequence[index] === sequence[length]) length++;
84 lengths[index] = length;
85 }
86 return lengths.at(-1) ?? 0;
88​
89const DASHBOARD_USAGE_URL = "https://cursor.com/api/dashboard/get-filtered-usage-events";
90​
91/** The session cookie must never follow a redirect off cursor.com. */
92const NO_REDIRECT: RequestInit = { redirect: "error" };
93​
94export const readCursorAccountUsage = Effect.fn("readCursorAccountUsage")(function* (
95 credentialSource: string | { readonly kind: "keychain" },
96 sinceMs: number,
97 endDate: number,
98 keychainToken: Effect.Effect<
99 string | null,
100 | CursorKeychain.CursorKeychainTimeoutError
101 | CursorKeychain.CursorKeychainReadError
102 | CursorAccountUsageInvalidError
103 > = invalid("No Keychain reader"),
104): Effect.fn.Return<
105 CursorAccountUsageReadResult,
106 never,
107 FileSystem.FileSystem | Crypto.Crypto | HttpClient.HttpClient
108> {
109 const fileSystem = yield* FileSystem.FileSystem;
110 const httpClient = yield* HttpClient.HttpClient;
111 const credential = yield* Effect.result<
112 unknown,
113 | PlatformError.PlatformError
114 | Schema.SchemaError
115 | CursorKeychain.CursorKeychainTimeoutError
116 | CursorKeychain.CursorKeychainReadError
117 | CursorAccountUsageInvalidError,
118 never
119 >(
120 typeof credentialSource === "string"
121 ? fileSystem.readFileString(credentialSource).pipe(
122 Effect.flatMap(decodeJson),
123 Effect.map((credentials) => object(credentials).accessToken),
124 )
125 : keychainToken,
126 );
127 if (Result.isFailure(credential)) {
128 const cause = credential.failure;
129 const missing =
130 typeof credentialSource === "string" &&
131 PlatformError.isPlatformError(cause) &&
132 cause.reason._tag === "NotFound";
133 return {
134 accountKey: null,
135 records: [],
136 missing,
137 error: missing
138 ? null
139 : typeof credentialSource === "string"
140 ? "Cursor credentials could not be read."
141 : CursorKeychain.isCursorKeychainTimeoutError(cause)
142 ? "Allow Keychain access on the Mac running T3 Code, then refresh."
143 : "Cursor Keychain credentials could not be read.",
144 };
145 }
146 const accessToken = credential.success;
147 if (typeof accessToken !== "string" || !accessToken) {
148 return {
149 accountKey: null,
150 records: [],
151 missing: true,
152 error:
153 typeof credentialSource === "string"
154 ? null
155 : "Cursor account history needs a macOS Keychain CLI login on this server.",
156 };
157 }
158 let accountKey: string | null = null;
159 const read = Effect.gen(function* () {
160 const payload = Base64Url.decodeString(accessToken.split(".")[1] ?? "");
161 if (Result.isFailure(payload)) return yield* invalid("Invalid authentication");
162 const subject = object(
163 yield* decodeJson(payload.success).pipe(
164 Effect.catch(() => invalid("Invalid authentication")),
165 ),
166 ).sub;
167 if (typeof subject !== "string" || !subject) return yield* invalid("Invalid authentication");
168 const userId = subject.split("|").at(-1);
169 if (!userId) return yield* invalid("Invalid authentication");
170 accountKey = yield* accountHash(subject);
171 if (!Number.isFinite(sinceMs) || !Number.isFinite(endDate) || sinceMs < 0 || sinceMs > endDate)
172 return yield* invalid("Invalid date window");
173 const records: UsageRecord[] = [];
174 const occurrences = new Map<string, number>();
175 const pages: unknown[][] = [];
176 let completed = false;
177 const pageSize = 1000;
178 let total: number | undefined;
179 const readPage = (page: number) =>
180 Effect.gen(function* () {
181 // A count can include overlapping page boundaries. Allow room to
182 // reconcile them without imposing a fixed account-size limit.
183 if (page > (total === undefined ? 1000 : Math.ceil(total / pageSize) * 2 + 1)) {
184 return yield* invalid("Account usage page limit exceeded");
185 }
186 const response = yield* httpClient
187 .execute(
188 HttpClientRequest.post(DASHBOARD_USAGE_URL).pipe(
189 HttpClientRequest.setHeaders({
190 Origin: "https://cursor.com",
191 Cookie: `WorkosCursorSessionToken=${encodeURIComponent(`${userId}::${accessToken}`)}`,
192 }),
193 HttpClientRequest.bodyText(
194 pageRequestBody(page, pageSize, sinceMs, endDate),
195 "application/json",
196 ),
197 ),
198 )
199 .pipe(
200 Effect.provideService(FetchHttpClient.RequestInit, NO_REDIRECT),
201 Effect.mapError(
202 () => new CursorAccountUsageInvalidError({ reason: "Account usage request failed" }),
203 ),
204 );
205 if (response.status === 401 || response.status === 403) {
206 return {
207 accountKey,
208 records: [],
209 missing: false,
210 error: "Sign in to Cursor again to read account usage.",
211 } satisfies CursorAccountUsageReadResult;
212 }
213 if (response.status < 200 || response.status >= 300)
214 return yield* invalid("Account usage request failed");
215 const parsed: unknown = yield* response.json.pipe(
216 Effect.mapError(
217 () => new CursorAccountUsageInvalidError({ reason: "Invalid account usage page" }),
218 ),
219 );
220 if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
221 return yield* invalid("Invalid account usage page");
222 }
223 const body = object(parsed);
224 const keys = Object.keys(body);
225 if ("error" in body || "message" in body || "code" in body)
226 return yield* invalid("Account usage error response");
227 const count = keys.length === 0 ? 0 : body.totalUsageEventsCount;
228 const events =
229 keys.length === 0 || (keys.length === 1 && keys[0] === "totalUsageEventsCount")
230 ? []
231 : body.usageEventsDisplay;
232 if (
233 (count !== undefined &&
234 (typeof count !== "number" ||
235 !Number.isSafeInteger(count) ||
236 count < 0 ||
237 (total !== undefined && count !== total))) ||
238 !Array.isArray(events) ||
239 events.length > pageSize ||
240 (count === undefined && !Array.isArray(body.usageEventsDisplay))
241 ) {
242 return yield* invalid("Inconsistent account usage page");
243 }
244 if (typeof count === "number") total = count;
245 return events as unknown[];
246 }).pipe(
247 Effect.timeoutOrElse({
248 duration: Duration.seconds(10),
249 orElse: () => invalid("Account usage request timed out"),
250 }),
251 );
252 // Cursor caps a page at 1,000 events and takes about a second to answer one, so the pages
253 // the first one's count implies are requested up to six ahead and consumed in page order.
254 const ahead: Fiber.Fiber<
255 Effect.Success<ReturnType<typeof readPage>>,
256 CursorAccountUsageInvalidError
257 >[] = [];
258 for (let page = 1; ; page++) {
259 while (ahead.length < Math.min(6, Math.ceil((total ?? 0) / pageSize) - page + 1)) {
260 ahead.push(yield* Effect.forkScoped(readPage(page + ahead.length)));
261 }
262 const next = ahead.shift();
263 const events = yield* next === undefined ? readPage(page) : Fiber.join(next);
264 if (!Array.isArray(events)) return events;
265 pages.push(events);
266 if (events.length < pageSize) {
267 completed = true;
268 break;
269 }
270 }
271 if (!completed) return yield* invalid("Account usage page limit exceeded");
272 const rawCount = pages.reduce((sum, page) => sum + page.length, 0);
273 if (total !== undefined && rawCount < total)
274 return yield* invalid("Incomplete account usage pages");
275 let removalsRemaining = total === undefined ? 0 : rawCount - total;
276 let previousKeys: string[] = [];
277 for (const events of pages) {
278 const eventKeys =
279 removalsRemaining > 0
280 ? yield* Effect.forEach(events, (event) => accountHash(canonicalJson(event)))
281 : [];
282 const removalCount = Math.min(removalsRemaining, boundaryOverlap(previousKeys, eventKeys));
283 removalsRemaining -= removalCount;
284 previousKeys = eventKeys;
285 for (const raw of events.slice(removalCount)) {
286 const event = object(raw);
287 const usage = object(event.tokenUsage);
288 if (event.tokenUsage === undefined || event.tokenUsage === null) continue;
289 for (const key of [
290 "inputTokens",
291 "outputTokens",
292 "cacheReadTokens",
293 "cacheWriteTokens",
294 "totalCents",
295 ]) {
296 const value = usage[key];
297 if (
298 value !== undefined &&
299 (typeof value !== "number" || !Number.isFinite(value) || value < 0)
300 ) {
301 return yield* invalid("Invalid account usage totals");
302 }
303 }
304 const timestampMs =
305 typeof event.timestamp === "string" && event.timestamp.trim() !== ""
306 ? Number(event.timestamp)
307 : event.timestamp;
308 if (
309 typeof timestampMs !== "number" ||
310 !Number.isFinite(timestampMs) ||
311 typeof event.model !== "string" ||
312 !event.model
313 )
314 return yield* invalid("Invalid account usage event");
315 if (timestampMs < sinceMs || timestampMs > endDate) continue;
316 const totals = {
317 uncachedInputTokens: tokens(usage.inputTokens),
318 cachedInputTokens: tokens(usage.cacheReadTokens),
319 cacheCreationTokens: tokens(usage.cacheWriteTokens),
320 outputTokens: tokens(usage.outputTokens),
321 reasoningTokens: 0,
322 };
323 const reportedCostUsd =
324 typeof usage.totalCents === "number" ? usage.totalCents / 100 : null;
325 const sessionId = typeof event.conversationId === "string" ? event.conversationId : "";
326 // No event ID is provided. Preserve identical billed rows with an occurrence index.
327 const key = yield* accountHash(
328 billedEventIdentity(timestampMs, event.model, sessionId, totals, reportedCostUsd),
329 );
330 const occurrence = occurrences.get(key) ?? 0;
331 occurrences.set(key, occurrence + 1);
332 records.push({
333 provider: "cursor",
334 timestampMs,
335 model: event.model,
336 rateModel: cursorRateModel(event.model),
337 sessionId,
338 totals,
339 reportedCostUsd,
340 speed: "standard",
341 dedupeKey: `cursor-account:${accountKey}:${key}:${occurrence}`,
342 });
343 }
344 yield* Effect.yieldNow;
345 }
346 if (removalsRemaining !== 0) return yield* invalid("Inconsistent account usage boundaries");
347 return {
348 accountKey,
349 records,
350 missing: false,
351 error: null,
352 } satisfies CursorAccountUsageReadResult;
353 });
354 return yield* read.pipe(
355 Effect.scoped,
356 Effect.timeoutOrElse({
357 duration: Duration.seconds(60),
358 orElse: () => invalid("Account usage read timed out"),
359 }),
360 Effect.catch(() =>
361 Effect.succeed({
362 accountKey,
363 records: [],
364 missing: false,
365 error: "Cursor account usage could not be read.",
366 } satisfies CursorAccountUsageReadResult),
367 ),
368 );
369});