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

accountUsage.ts

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