The best way to control Claude Code, Codex and more from any computer or phone

main
ts 437 lines 18 KB
Raw
1 import type { UsageRecord } from "@t3tools/provider-core/server/usage";
2 import * as Digest from "effect/crypto/Digest";
3 import * as Cache from "effect/Cache";
4 import * as Clock from "effect/Clock";
5 import * as Exit from "effect/Exit";
6 import * as Semaphore from "effect/Semaphore";
7 import * as Duration from "effect/Duration";
8 import * as Effect from "effect/Effect";
9 import * as Base64Url from "effect/encoding/Base64Url";
10 import * as Fiber from "effect/Fiber";
11 import * as FetchHttpClient from "effect/http/FetchHttpClient";
12 import * as HttpClient from "effect/http/HttpClient";
13 import * as HttpClientRequest from "effect/http/HttpClientRequest";
14 import * as Result from "effect/Result";
15 import * as Schema from "effect/Schema";
16
17 import type { CursorCredentialSource } from "./accountCache.ts";
18 import { DEFAULT_CURSOR_API_ENDPOINT, exchangeCursorApiKey } from "./apiKey.ts";
19
20 function object(value: unknown): Record<string, unknown> {
21 return typeof value === "object" && value !== null && !Array.isArray(value)
22 ? (value as Record<string, unknown>)
23 : {};
24 }
25
26 function tokens(value: unknown): number {
27 return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0;
28 }
29
30 // Grok's xAI first-party rate entry has no bare alias.
31 export 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;
36 }
37
38 export interface CursorAccountUsageReadResult {
39 readonly accountKey: string | null;
40 readonly records: readonly UsageRecord[];
41 readonly missing: boolean;
42 readonly error: string | null;
43 }
44
45 class CursorAccountUsageInvalidError extends Schema.TaggedError<CursorAccountUsageInvalidError>()(
46 "CursorAccountUsageInvalidError",
47 { reason: Schema.String },
48 ) {}
49
50 const invalid = (reason: string) => Effect.fail(new CursorAccountUsageInvalidError({ reason }));
51
52 const decodeJson = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown));
53
54 const decodeTeams = Schema.decodeUnknownEffect(
55 Schema.Struct({ teams: Schema.optionalKey(Schema.Array(Schema.Struct({ id: Schema.Number }))) }),
56 );
57 const decodeUser = Schema.decodeUnknownEffect(Schema.Struct({ userId: Schema.Number }));
58
59 const pageRequestBody = (
60 page: number,
61 pageSize: number,
62 sinceMs: number,
63 endDate: number,
64 teamId?: number,
65 userId?: number,
66 ) =>
67 JSON.stringify({
68 page,
69 pageSize,
70 startDate: String(sinceMs),
71 endDate: String(endDate),
72 ...(teamId === undefined ? {} : { teamId, userId }),
73 });
74
75 const billedEventIdentity = (...fields: readonly unknown[]) => JSON.stringify(fields);
76
77 const textEncoder = new TextEncoder();
78
79 function canonicalJson(value: unknown): string {
80 if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
81 if (value !== null && typeof value === "object") {
82 return `{${Object.entries(value)
83 .sort(([a], [b]) => a.localeCompare(b))
84 .map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`)
85 .join(",")}}`;
86 }
87 return JSON.stringify(value) ?? "null";
88 }
89
90 function boundaryOverlap(previous: readonly string[], current: readonly string[]): number {
91 const sequence = [...current, "", ...previous];
92 const lengths = Array.from({ length: sequence.length }, () => 0);
93 for (let index = 1; index < sequence.length; index++) {
94 let length = lengths[index - 1]!;
95 while (length > 0 && sequence[index] !== sequence[length]) length = lengths[length - 1]!;
96 if (sequence[index] === sequence[length]) length++;
97 lengths[index] = length;
98 }
99 return lengths.at(-1) ?? 0;
100 }
101
102 /** Never forward the access token through a redirect. */
103 const NO_REDIRECT: RequestInit = { redirect: "error" };
104
105 export const makeCursorAccountUsageReader = Effect.gen(function* () {
106 const httpClient = yield* HttpClient.HttpClient;
107 const digest = yield* Digest.Digest;
108 // Per-event hashes share the scan span and use the native hex encoder.
109 const accountHash = (value: string) => digest.digestHex(Digest.sha256, textEncoder.encode(value));
110 const readSession = Effect.fn("CursorAccountUsage.readSession")(function* (apiKey: string) {
111 const accessToken = yield* exchangeCursorApiKey(apiKey);
112 const payload = Base64Url.decodeString(accessToken.split(".")[1] ?? "");
113 if (Result.isFailure(payload)) return yield* invalid("Invalid authentication");
114 const authentication = object(
115 yield* decodeJson(payload.success).pipe(
116 Effect.catch(() => invalid("Invalid authentication")),
117 ),
118 );
119 const subject = authentication.sub;
120 if (typeof subject !== "string" || !subject) return yield* invalid("Invalid authentication");
121 const accountKey = yield* accountHash(subject);
122 const membershipRequest = Effect.fn("CursorAccountUsage.membershipRequest")(function* (
123 method: string,
124 ) {
125 const response = yield* httpClient
126 .execute(
127 HttpClientRequest.post(
128 `${DEFAULT_CURSOR_API_ENDPOINT}/aiserver.v1.DashboardService/${method}`,
129 ).pipe(
130 HttpClientRequest.bearerToken(accessToken),
131 HttpClientRequest.setHeader("connect-protocol-version", "1"),
132 HttpClientRequest.bodyText("{}", "application/json"),
133 ),
134 )
135 .pipe(Effect.provideService(FetchHttpClient.RequestInit, NO_REDIRECT));
136 if (response.status < 200 || response.status >= 300)
137 return yield* invalid("Account membership request failed");
138 const body = yield* response.json;
139 const fields = object(body);
140 if ("error" in fields || "message" in fields || "code" in fields)
141 return yield* invalid("Account membership error response");
142 return body;
143 }, Effect.timeout("10 seconds"));
144 const [teams, me] = yield* Effect.all(
145 [
146 membershipRequest("GetTeams").pipe(Effect.flatMap(decodeTeams)),
147 membershipRequest("GetMe").pipe(Effect.flatMap(decodeUser)),
148 ],
149 { concurrency: 2 },
150 );
151 const teamIds = [...new Set((teams.teams ?? []).map((team) => team.id))];
152 if (teamIds.some((id) => !Number.isSafeInteger(id) || id <= 0))
153 return yield* invalid("Invalid account teams");
154 const userId = me.userId;
155 if (!Number.isSafeInteger(userId) || userId <= 0) return yield* invalid("Invalid account user");
156
157 const nowMs = yield* Clock.currentTimeMillis;
158 const ttlMs =
159 typeof authentication.exp === "number"
160 ? Math.max(0, Math.min(5 * 60_000, authentication.exp * 1000 - nowMs - 30_000))
161 : 5 * 60_000;
162 return { accessToken, accountKey, teamIds, userId, ttlMs };
163 });
164 const sessions = yield* Cache.makeWith(readSession, {
165 capacity: 16,
166 timeToLive: (exit) =>
167 Exit.isSuccess(exit) ? Duration.millis(exit.value.ttlMs) : Duration.zero,
168 });
169 return Effect.fn("readCursorAccountUsage")(function* (
170 credentialSource: CursorCredentialSource,
171 sinceMs: number,
172 endDate: number,
173 ) {
174 let accountKey: string | null = null;
175 const read = Effect.gen(function* () {
176 if (
177 !Number.isFinite(sinceMs) ||
178 !Number.isFinite(endDate) ||
179 sinceMs < 0 ||
180 sinceMs > endDate
181 )
182 return yield* invalid("Invalid date window");
183 const session = yield* Cache.get(sessions, credentialSource.apiKey);
184 const { accessToken, teamIds, userId } = session;
185 accountKey = session.accountKey;
186 const pageSlots = yield* Semaphore.make(6);
187 // Omitting teamId returns personal history; team history also needs the current user filter.
188 const readScope = Effect.fn("CursorAccountUsage.readScope")(function* (teamId?: number) {
189 const pageRequest = HttpClientRequest.post(
190 `${DEFAULT_CURSOR_API_ENDPOINT}/aiserver.v1.DashboardService/GetFilteredUsageEvents`,
191 ).pipe(
192 HttpClientRequest.bearerToken(accessToken),
193 HttpClientRequest.setHeader("connect-protocol-version", "1"),
194 );
195 const records: UsageRecord[] = [];
196 const occurrences = new Map<string, number>();
197 const normalized: Array<(Omit<UsageRecord, "dedupeKey"> & { dedupeKey: string }) | null> =
198 [];
199 const pages: Array<{ start: number; end: number; overlap: number }> = [];
200 let previousEvents: unknown[] = [];
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, teamId, userId),
215 "application/json",
216 ),
217 ),
218 )
219 .pipe(
220 Effect.provideService(FetchHttpClient.RequestInit, NO_REDIRECT),
221 Effect.mapError(
222 () =>
223 new CursorAccountUsageInvalidError({ reason: "Account usage request failed" }),
224 ),
225 );
226 if (response.status === 401 || response.status === 403) {
227 yield* Cache.invalidate(sessions, credentialSource.apiKey);
228 return {
229 accountKey,
230 records: [],
231 missing: false,
232 error: "Sign in to Cursor again to read account usage.",
233 } satisfies CursorAccountUsageReadResult;
234 }
235 if (response.status < 200 || response.status >= 300)
236 return yield* invalid("Account usage request failed");
237 const parsed: unknown = yield* response.json.pipe(
238 Effect.mapError(
239 () => new CursorAccountUsageInvalidError({ reason: "Invalid account usage page" }),
240 ),
241 );
242 if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
243 return yield* invalid("Invalid account usage page");
244 }
245 const body = object(parsed);
246 const keys = Object.keys(body);
247 if ("error" in body || "message" in body || "code" in body)
248 return yield* invalid("Account usage error response");
249 const count = keys.length === 0 ? 0 : body.totalUsageEventsCount;
250 const events =
251 keys.length === 0 || (keys.length === 1 && keys[0] === "totalUsageEventsCount")
252 ? []
253 : body.usageEventsDisplay;
254 if (
255 (count !== undefined &&
256 (typeof count !== "number" ||
257 !Number.isSafeInteger(count) ||
258 count < 0 ||
259 (total !== undefined && count !== total))) ||
260 !Array.isArray(events) ||
261 events.length > pageSize ||
262 (count === undefined && !Array.isArray(body.usageEventsDisplay))
263 ) {
264 return yield* invalid("Inconsistent account usage page");
265 }
266 if (typeof count === "number") total = count;
267 return events as unknown[];
268 },
269 Effect.timeoutOrElse({
270 duration: Duration.seconds(10),
271 orElse: () => invalid("Account usage request timed out"),
272 }),
273 pageSlots.withPermit,
274 );
275 // Cursor caps a page at 1,000 events and takes about a second to answer one, so the pages
276 // the first one's count implies are requested up to six ahead and consumed in page order.
277 const ahead: Fiber.Fiber<
278 Effect.Success<ReturnType<typeof readPage>>,
279 CursorAccountUsageInvalidError
280 >[] = [];
281 for (let page = 1; ; page++) {
282 while (ahead.length < Math.min(6, Math.ceil((total ?? 0) / pageSize) - page + 1)) {
283 ahead.push(yield* Effect.forkScoped(readPage(page + ahead.length)));
284 }
285 const next = ahead.shift();
286 const events = yield* next === undefined ? readPage(page) : Fiber.join(next);
287 if (!Array.isArray(events)) return events;
288 const start = normalized.length;
289 const firstTimestamp = object(events[0]).timestamp;
290 // Equal raw events must have equal timestamps; avoid canonicalizing disjoint pages.
291 const mayOverlap =
292 (typeof firstTimestamp !== "string" && typeof firstTimestamp !== "number") ||
293 previousEvents.some((event) => object(event).timestamp === firstTimestamp);
294 const overlap = mayOverlap
295 ? boundaryOverlap(previousEvents.map(canonicalJson), events.map(canonicalJson))
296 : 0;
297 previousEvents = events;
298 for (const raw of events) {
299 const event = object(raw);
300 const usage = object(event.tokenUsage);
301 if (event.tokenUsage === undefined || event.tokenUsage === null) {
302 normalized.push(null);
303 continue;
304 }
305 for (const key of [
306 "inputTokens",
307 "outputTokens",
308 "cacheReadTokens",
309 "cacheWriteTokens",
310 "totalCents",
311 ]) {
312 const value = usage[key];
313 if (
314 value !== undefined &&
315 (typeof value !== "number" || !Number.isFinite(value) || value < 0)
316 ) {
317 return yield* invalid("Invalid account usage totals");
318 }
319 }
320 const timestampMs =
321 typeof event.timestamp === "string" && event.timestamp.trim() !== ""
322 ? Number(event.timestamp)
323 : event.timestamp;
324 if (
325 typeof timestampMs !== "number" ||
326 !Number.isFinite(timestampMs) ||
327 typeof event.model !== "string" ||
328 !event.model
329 )
330 return yield* invalid("Invalid account usage event");
331 if (timestampMs < sinceMs || timestampMs > endDate) {
332 normalized.push(null);
333 continue;
334 }
335 const totals = {
336 uncachedInputTokens: tokens(usage.inputTokens),
337 cachedInputTokens: tokens(usage.cacheReadTokens),
338 cacheCreationTokens: tokens(usage.cacheWriteTokens),
339 outputTokens: tokens(usage.outputTokens),
340 reasoningTokens: 0,
341 };
342 const reportedCostUsd =
343 typeof usage.totalCents === "number" ? usage.totalCents / 100 : null;
344 const sessionId = typeof event.conversationId === "string" ? event.conversationId : "";
345 // No event ID is provided. Preserve identical billed rows with an occurrence index.
346 const key = yield* accountHash(
347 billedEventIdentity(
348 ...(teamId === undefined ? [] : [teamId]),
349 timestampMs,
350 event.model,
351 sessionId,
352 totals,
353 reportedCostUsd,
354 ),
355 );
356 normalized.push({
357 provider: "cursor",
358 timestampMs,
359 model: event.model,
360 rateModel: cursorRateModel(event.model),
361 sessionId,
362 totals,
363 reportedCostUsd,
364 speed: "standard",
365 dedupeKey: key,
366 });
367 }
368 pages.push({ start, end: normalized.length, overlap });
369 if (events.length < pageSize) break;
370 yield* Effect.yieldNow;
371 }
372 const rawCount = normalized.length;
373 if (total !== undefined && rawCount < total)
374 return yield* invalid("Incomplete account usage pages");
375 let removalsRemaining = total === undefined ? 0 : rawCount - total;
376 // The final count proves which boundary copies to remove, including non-token events.
377 for (const page of pages) {
378 const removalCount = Math.min(removalsRemaining, page.overlap);
379 removalsRemaining -= removalCount;
380 for (let index = page.start; index < page.end; index++) {
381 const record = normalized[index];
382 normalized[index] = null;
383 if (index < page.start + removalCount || record == null) continue;
384 const key = record.dedupeKey;
385 const occurrence = occurrences.get(key) ?? 0;
386 occurrences.set(key, occurrence + 1);
387 record.dedupeKey = `cursor-account:${accountKey}:${key}:${occurrence}`;
388 records.push(record);
389 }
390 yield* Effect.yieldNow;
391 }
392 if (removalsRemaining !== 0) return yield* invalid("Inconsistent account usage boundaries");
393 yield* Effect.annotateCurrentSpan({
394 "cursor.usage.pages": pages.length,
395 "cursor.usage.events": rawCount,
396 "cursor.usage.records": records.length,
397 });
398 return {
399 accountKey,
400 records,
401 missing: false,
402 error: null,
403 } satisfies CursorAccountUsageReadResult;
404 });
405
406 const results = yield* Effect.forEach(
407 [undefined, ...teamIds],
408 (teamId) => readScope(teamId).pipe(Effect.scoped),
409 { concurrency: 2 },
410 );
411 const failure = results.find((result) => result.error !== null);
412 if (failure !== undefined) return failure;
413 return {
414 accountKey,
415 records: results.flatMap((result) => result.records),
416 missing: false,
417 error: null,
418 } satisfies CursorAccountUsageReadResult;
419 });
420 return yield* read.pipe(
421 Effect.scoped,
422 Effect.timeoutOrElse({
423 duration: Duration.seconds(60),
424 orElse: () => invalid("Account usage read timed out"),
425 }),
426 Effect.orElseSucceed(
427 () =>
428 ({
429 accountKey,
430 records: [],
431 missing: false,
432 error: "Cursor account usage could not be read.",
433 }) satisfies CursorAccountUsageReadResult,
434 ),
435 );
436 });
437 });