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

accountUsage.ts

390 lines15.2 KB

1import type { UsageRecord } from "@t3tools/provider-core/server/usage";
2import * as Digest from "effect/crypto/Digest";
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 type { CursorCredentialSource } from "./accountCache.ts";
17import { DEFAULT_CURSOR_API_ENDPOINT, exchangeCursorApiKey } from "./apiKey.ts";
18import * as CursorKeychain from "./CursorKeychain.ts";
19​
20function object(value: unknown): Record<string, unknown> {
21 return typeof value === "object" && value !== null && !Array.isArray(value)
22 ? (value as Record<string, unknown>)
23 : {};
25​
26function tokens(value: unknown): number {
27 return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0;
29​
30// Grok's xAI first-party rate entry has no bare alias.
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 digest = yield* Digest.Digest;
63 return Hex.encode(yield* digest.digest(Digest.sha256, 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: CursorCredentialSource,
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 | Digest.Digest | 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 : credentialSource.kind === "apiKey"
126 ? exchangeCursorApiKey(credentialSource.apiKey).pipe(
127 Effect.provideService(HttpClient.HttpClient, httpClient),
128 Effect.mapError(
129 () => new CursorAccountUsageInvalidError({ reason: "Invalid API key" }),
130 ),
131 )
132 : keychainToken,
133 );
134 if (Result.isFailure(credential)) {
135 const cause = credential.failure;
136 const missing =
137 typeof credentialSource === "string" &&
138 PlatformError.isPlatformError(cause) &&
139 cause.reason._tag === "NotFound";
140 return {
141 accountKey: null,
142 records: [],
143 missing,
144 error: missing
145 ? null
146 : typeof credentialSource === "string"
147 ? "Cursor credentials could not be read."
148 : credentialSource.kind === "apiKey"
149 ? "Cursor account usage could not be read."
150 : CursorKeychain.isCursorKeychainTimeoutError(cause)
151 ? "Allow Keychain access on the Mac running T3 Code, then refresh."
152 : "Cursor Keychain credentials could not be read.",
153 };
154 }
155 const accessToken = credential.success;
156 if (typeof accessToken !== "string" || !accessToken) {
157 return {
158 accountKey: null,
159 records: [],
160 missing: true,
161 error:
162 typeof credentialSource === "string"
163 ? null
164 : "Cursor account history needs a macOS Keychain CLI login on this server.",
165 };
166 }
167 let accountKey: string | null = null;
168 const read = Effect.gen(function* () {
169 const payload = Base64Url.decodeString(accessToken.split(".")[1] ?? "");
170 if (Result.isFailure(payload)) return yield* invalid("Invalid authentication");
171 const subject = object(
172 yield* decodeJson(payload.success).pipe(
173 Effect.catch(() => invalid("Invalid authentication")),
174 ),
175 ).sub;
176 if (typeof subject !== "string" || !subject) return yield* invalid("Invalid authentication");
177 const userId = subject.split("|").at(-1);
178 if (!userId) return yield* invalid("Invalid authentication");
179 accountKey = yield* accountHash(subject);
180 if (!Number.isFinite(sinceMs) || !Number.isFinite(endDate) || sinceMs < 0 || sinceMs > endDate)
181 return yield* invalid("Invalid date window");
182 // The web dashboard rejects API-key tokens; Cursor's RPC API accepts them.
183 const pageRequest =
184 typeof credentialSource !== "string" && credentialSource.kind === "apiKey"
185 ? HttpClientRequest.post(
186 `${DEFAULT_CURSOR_API_ENDPOINT}/aiserver.v1.DashboardService/GetFilteredUsageEvents`,
187 ).pipe(
188 HttpClientRequest.bearerToken(accessToken),
189 HttpClientRequest.setHeader("connect-protocol-version", "1"),
190 )
191 : HttpClientRequest.post(DASHBOARD_USAGE_URL).pipe(
192 HttpClientRequest.setHeaders({
193 Origin: "https://cursor.com",
194 Cookie: `WorkosCursorSessionToken=${encodeURIComponent(`${userId}::${accessToken}`)}`,
195 }),
196 );
197 const records: UsageRecord[] = [];
198 const occurrences = new Map<string, number>();
199 const pages: unknown[][] = [];
200 let completed = false;
201 const pageSize = 1000;
202 let total: number | undefined;
203 const readPage = Effect.fn("CursorAccountUsage.readPage")(
204 function* (page: number) {
205 // A count can include overlapping page boundaries. Allow room to
206 // reconcile them without imposing a fixed account-size limit.
207 if (page > (total === undefined ? 1000 : Math.ceil(total / pageSize) * 2 + 1)) {
208 return yield* invalid("Account usage page limit exceeded");
209 }
210 const response = yield* httpClient
211 .execute(
212 pageRequest.pipe(
213 HttpClientRequest.bodyText(
214 pageRequestBody(page, pageSize, sinceMs, endDate),
215 "application/json",
216 ),
217 ),
218 )
219 .pipe(
220 Effect.provideService(FetchHttpClient.RequestInit, NO_REDIRECT),
221 Effect.mapError(
222 () => new CursorAccountUsageInvalidError({ reason: "Account usage request failed" }),
223 ),
224 );
225 if (response.status === 401 || response.status === 403) {
226 return {
227 accountKey,
228 records: [],
229 missing: false,
230 error: "Sign in to Cursor again to read account usage.",
231 } satisfies CursorAccountUsageReadResult;
232 }
233 if (response.status < 200 || response.status >= 300)
234 return yield* invalid("Account usage request failed");
235 const parsed: unknown = yield* response.json.pipe(
236 Effect.mapError(
237 () => new CursorAccountUsageInvalidError({ reason: "Invalid account usage page" }),
238 ),
239 );
240 if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
241 return yield* invalid("Invalid account usage page");
242 }
243 const body = object(parsed);
244 const keys = Object.keys(body);
245 if ("error" in body || "message" in body || "code" in body)
246 return yield* invalid("Account usage error response");
247 const count = keys.length === 0 ? 0 : body.totalUsageEventsCount;
248 const events =
249 keys.length === 0 || (keys.length === 1 && keys[0] === "totalUsageEventsCount")
250 ? []
251 : body.usageEventsDisplay;
252 if (
253 (count !== undefined &&
254 (typeof count !== "number" ||
255 !Number.isSafeInteger(count) ||
256 count < 0 ||
257 (total !== undefined && count !== total))) ||
258 !Array.isArray(events) ||
259 events.length > pageSize ||
260 (count === undefined && !Array.isArray(body.usageEventsDisplay))
261 ) {
262 return yield* invalid("Inconsistent account usage page");
263 }
264 if (typeof count === "number") total = count;
265 return events as unknown[];
266 },
267 Effect.timeoutOrElse({
268 duration: Duration.seconds(10),
269 orElse: () => invalid("Account usage request timed out"),
270 }),
271 );
272 // Cursor caps a page at 1,000 events and takes about a second to answer one, so the pages
273 // the first one's count implies are requested up to six ahead and consumed in page order.
274 const ahead: Fiber.Fiber<
275 Effect.Success<ReturnType<typeof readPage>>,
276 CursorAccountUsageInvalidError
277 >[] = [];
278 for (let page = 1; ; page++) {
279 while (ahead.length < Math.min(6, Math.ceil((total ?? 0) / pageSize) - page + 1)) {
280 ahead.push(yield* Effect.forkScoped(readPage(page + ahead.length)));
281 }
282 const next = ahead.shift();
283 const events = yield* next === undefined ? readPage(page) : Fiber.join(next);
284 if (!Array.isArray(events)) return events;
285 pages.push(events);
286 if (events.length < pageSize) {
287 completed = true;
288 break;
289 }
290 }
291 if (!completed) return yield* invalid("Account usage page limit exceeded");
292 const rawCount = pages.reduce((sum, page) => sum + page.length, 0);
293 if (total !== undefined && rawCount < total)
294 return yield* invalid("Incomplete account usage pages");
295 let removalsRemaining = total === undefined ? 0 : rawCount - total;
296 let previousKeys: string[] = [];
297 for (const events of pages) {
298 const eventKeys =
299 removalsRemaining > 0
300 ? yield* Effect.forEach(events, (event) => accountHash(canonicalJson(event)))
301 : [];
302 const removalCount = Math.min(removalsRemaining, boundaryOverlap(previousKeys, eventKeys));
303 removalsRemaining -= removalCount;
304 previousKeys = eventKeys;
305 for (const raw of events.slice(removalCount)) {
306 const event = object(raw);
307 const usage = object(event.tokenUsage);
308 if (event.tokenUsage === undefined || event.tokenUsage === null) continue;
309 for (const key of [
310 "inputTokens",
311 "outputTokens",
312 "cacheReadTokens",
313 "cacheWriteTokens",
314 "totalCents",
315 ]) {
316 const value = usage[key];
317 if (
318 value !== undefined &&
319 (typeof value !== "number" || !Number.isFinite(value) || value < 0)
320 ) {
321 return yield* invalid("Invalid account usage totals");
322 }
323 }
324 const timestampMs =
325 typeof event.timestamp === "string" && event.timestamp.trim() !== ""
326 ? Number(event.timestamp)
327 : event.timestamp;
328 if (
329 typeof timestampMs !== "number" ||
330 !Number.isFinite(timestampMs) ||
331 typeof event.model !== "string" ||
332 !event.model
333 )
334 return yield* invalid("Invalid account usage event");
335 if (timestampMs < sinceMs || timestampMs > endDate) continue;
336 const totals = {
337 uncachedInputTokens: tokens(usage.inputTokens),
338 cachedInputTokens: tokens(usage.cacheReadTokens),
339 cacheCreationTokens: tokens(usage.cacheWriteTokens),
340 outputTokens: tokens(usage.outputTokens),
341 reasoningTokens: 0,
342 };
343 const reportedCostUsd =
344 typeof usage.totalCents === "number" ? usage.totalCents / 100 : null;
345 const sessionId = typeof event.conversationId === "string" ? event.conversationId : "";
346 // No event ID is provided. Preserve identical billed rows with an occurrence index.
347 const key = yield* accountHash(
348 billedEventIdentity(timestampMs, event.model, sessionId, totals, reportedCostUsd),
349 );
350 const occurrence = occurrences.get(key) ?? 0;
351 occurrences.set(key, occurrence + 1);
352 records.push({
353 provider: "cursor",
354 timestampMs,
355 model: event.model,
356 rateModel: cursorRateModel(event.model),
357 sessionId,
358 totals,
359 reportedCostUsd,
360 speed: "standard",
361 dedupeKey: `cursor-account:${accountKey}:${key}:${occurrence}`,
362 });
363 }
364 yield* Effect.yieldNow;
365 }
366 if (removalsRemaining !== 0) return yield* invalid("Inconsistent account usage boundaries");
367 return {
368 accountKey,
369 records,
370 missing: false,
371 error: null,
372 } satisfies CursorAccountUsageReadResult;
373 });
374 return yield* read.pipe(
375 Effect.scoped,
376 Effect.timeoutOrElse({
377 duration: Duration.seconds(60),
378 orElse: () => invalid("Account usage read timed out"),
379 }),
380 Effect.orElseSucceed(
381 () =>
382 ({
383 accountKey,
384 records: [],
385 missing: false,
386 error: "Cursor account usage could not be read.",
387 }) satisfies CursorAccountUsageReadResult,
388 ),
389 );
390});