@devries-cameron20 / t3code Mirror · read-only / commits / 497aac20f7
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 17:15 UTC

fix(server): include Cursor team usage in account history (#36237)

Yash Singh committed Nov 13, 2026 at 11:42 UTC 497aac20f766fcfa704b93a5dfd9da8f8263c34b
4 files changed +587 -278
packages/provider-cursor/src/server/CursorAccountReader.ts
+3 -4
@@ -5,7 +5,7 @@ import * as HttpClient from "effect/http/HttpClient";
5 import * as Layer from "effect/Layer";
6
7 import type { CursorCredentialSource } from "./accountCache.ts";
8 -import { readCursorAccountUsage, type CursorAccountUsageReadResult } from "./accountUsage.ts";
8 +import { makeCursorAccountUsageReader, type CursorAccountUsageReadResult } from "./accountUsage.ts";
9
10 export class CursorAccountReader extends Context.Service<
11 CursorAccountReader,
@@ -22,11 +22,10 @@ export const layer = Layer.effect(
22 CursorAccountReader,
23 Effect.gen(function* () {
24 const context = yield* Effect.context<Digest.Digest | HttpClient.HttpClient>();
25 + const read = yield* makeCursorAccountUsageReader;
26 return CursorAccountReader.of({
27 read: Effect.fn("CursorAccountReader.read")(function (credentialSource, sinceMs, untilMs) {
27 - return readCursorAccountUsage(credentialSource, sinceMs, untilMs).pipe(
28 - Effect.provideContext(context),
29 - );
28 + return read(credentialSource, sinceMs, untilMs).pipe(Effect.provideContext(context));
29 }),
30 });
31 }),
packages/provider-cursor/src/server/accountCache.ts
+2 -2
@@ -82,8 +82,8 @@ export function mergeCursorFetch(
82 }
83
84 /** Versioned files isolate caches for different server versions sharing a state directory. */
85 -export const CURSOR_ACCOUNT_CACHE_FILE_NAME = "usage-cursor-account-cache-v1.json";
86 -const CURSOR_ACCOUNT_CACHE_VERSION = 1;
85 +export const CURSOR_ACCOUNT_CACHE_FILE_NAME = "usage-cursor-account-cache-v2.json";
86 +const CURSOR_ACCOUNT_CACHE_VERSION = 2;
87
88 type SerializedRecord = readonly [
89 timestampMs: number,
packages/provider-cursor/src/server/accountUsage.test.ts
+245 -36
@@ -2,6 +2,8 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 import * as Layer from "effect/Layer";
4 import { assert, describe, it } from "@effect/vitest";
5 +import * as Deferred from "effect/Deferred";
6 +import * as Queue from "effect/Queue";
7 import * as Context from "effect/Context";
8 import * as Effect from "effect/Effect";
9 import * as Fiber from "effect/Fiber";
@@ -11,7 +13,10 @@ import * as HttpClientError from "effect/http/HttpClientError";
13 import * as HttpClientResponse from "effect/http/HttpClientResponse";
14 import * as TestClock from "effect/testing/TestClock";
15
14 -import { readCursorAccountUsage } from "./accountUsage.ts";
16 +import * as CursorAccountReader from "./CursorAccountReader.ts";
17 +
18 +import { makeCursorAccountUsageReader } from "./accountUsage.ts";
19 +import type { CursorCredentialSource } from "./accountCache.ts";
20
21 interface DashboardRequest {
22 readonly url: string;
@@ -20,7 +25,10 @@ interface DashboardRequest {
25 readonly headers: Headers;
26 }
27
23 -const dashboard = (answer: (request: DashboardRequest) => Response | Promise<Response>) =>
28 +const dashboard = (
29 + answer: (request: DashboardRequest) => Response | Promise<Response>,
30 + membership = { userId: 1, teamIds: [] as number[] },
31 +) =>
32 HttpClient.make((request, url, signal, fiber) =>
33 Effect.tryPromise({
34 try: async () => {
@@ -36,6 +44,15 @@ const dashboard = (answer: (request: DashboardRequest) => Response | Promise<Res
44 Response.json({ accessToken: request.headers.authorization.slice(7) }),
45 );
46 }
47 + if (url.pathname.endsWith("/GetMe")) {
48 + return HttpClientResponse.fromWeb(request, Response.json({ userId: membership.userId }));
49 + }
50 + if (url.pathname.endsWith("/GetTeams")) {
51 + return HttpClientResponse.fromWeb(
52 + request,
53 + Response.json({ teams: membership.teamIds.map((id) => ({ id })) }),
54 + );
55 + }
56 const response = await answer({
57 url: url.toString(),
58 init: { ...init, signal, body },
@@ -52,13 +69,15 @@ const dashboard = (answer: (request: DashboardRequest) => Response | Promise<Res
69 );
70
71 const readAccountUsage = (
55 - credentialSource: Parameters<typeof readCursorAccountUsage>[0],
72 + credentialSource: CursorCredentialSource,
73 sinceMs: number,
74 endDate: number,
75 answer: (request: DashboardRequest) => Response | Promise<Response>,
76 + membership?: { userId: number; teamIds: number[] },
77 ) =>
60 - readCursorAccountUsage(credentialSource, sinceMs, endDate).pipe(
61 - Effect.provideService(HttpClient.HttpClient, dashboard(answer)),
78 + makeCursorAccountUsageReader.pipe(
79 + Effect.flatMap((read) => read(credentialSource, sinceMs, endDate)),
80 + Effect.provideService(HttpClient.HttpClient, dashboard(answer, membership)),
81 );
82
83 describe("Cursor account history", () => {
@@ -123,6 +142,157 @@ describe("Cursor account history", () => {
142 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
143 );
144
145 + it.effect("includes each team's own-user history alongside personal history", () =>
146 + Effect.gen(function* () {
147 + const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`;
148 + const scopes: unknown[] = [];
149 + const result = yield* readAccountUsage(
150 + { kind: "apiKey", apiKey: accessToken },
151 + 0,
152 + 1781000000000,
153 + async ({ init }) => {
154 + const body = JSON.parse(String(init.body));
155 + scopes.push([body.teamId, body.userId]);
156 + const team = body.teamId !== undefined;
157 + return Response.json({
158 + totalUsageEventsCount: 1,
159 + usageEventsDisplay: [
160 + {
161 + timestamp: "1780000000000",
162 + model: "gpt-5",
163 + conversationId: "same-conversation",
164 + tokenUsage: { cacheReadTokens: team ? 5_000_000 : 10 },
165 + },
166 + ],
167 + });
168 + },
169 + { userId: 42, teamIds: [7, 8, 7] },
170 + );
171 + assert.isNull(result.error);
172 + assert.deepStrictEqual(scopes, [
173 + [undefined, undefined],
174 + [7, 42],
175 + [8, 42],
176 + ]);
177 + assert.strictEqual(
178 + result.records.reduce((sum, row) => sum + row.totals.cachedInputTokens, 0),
179 + 10_000_010,
180 + );
181 + assert.strictEqual(new Set(result.records.map((row) => row.dedupeKey)).size, 3);
182 + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
183 + );
184 +
185 + it.effect("rejects unscoped or incomplete team history without keeping personal totals", () =>
186 + Effect.gen(function* () {
187 + const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`;
188 + for (const userId of [0, 42]) {
189 + const scopes: unknown[] = [];
190 + const result = yield* readAccountUsage(
191 + { kind: "apiKey", apiKey: accessToken },
192 + 0,
193 + 1781000000000,
194 + async ({ init }) => {
195 + const body = JSON.parse(String(init.body));
196 + scopes.push(body.teamId);
197 + return body.teamId === undefined
198 + ? Response.json({
199 + totalUsageEventsCount: 1,
200 + usageEventsDisplay: [
201 + {
202 + timestamp: "1780000000000",
203 + model: "gpt-5",
204 + tokenUsage: { inputTokens: 10 },
205 + },
206 + ],
207 + })
208 + : new Response(null, { status: 403 });
209 + },
210 + { userId, teamIds: [7] },
211 + );
212 + assert.isNotNull(result.error);
213 + assert.deepStrictEqual(result.records, []);
214 + assert.deepStrictEqual(scopes, userId === 0 ? [] : [undefined, 7]);
215 + }
216 + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
217 + );
218 +
219 + it.effect.each([
220 + { exp: undefined, lifetime: "5 minutes" },
221 + { exp: 90, lifetime: "1 minute" },
222 + ] as const)(
223 + "reuses discovery for $lifetime, invalidates rejected auth, and isolates API keys",
224 + ({ exp, lifetime }) =>
225 + Effect.gen(function* () {
226 + const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo", exp })).toString("base64url")}.signature`;
227 + const requests: string[] = [];
228 + let rejected = false;
229 + const client = dashboard(
230 + () => (rejected ? new Response(null, { status: 401 }) : Response.json({})),
231 + { userId: 42, teamIds: [7] },
232 + ).pipe(
233 + HttpClient.mapRequest((request) => {
234 + requests.push(request.url.split("/").at(-1)!);
235 + return request;
236 + }),
237 + );
238 + yield* Effect.gen(function* () {
239 + const reader = yield* CursorAccountReader.CursorAccountReader;
240 + const credential = { kind: "apiKey", apiKey: accessToken } as const;
241 + assert.isNull((yield* reader.read(credential, 0, 1781000000000)).error);
242 + requests.length = 0;
243 + assert.isNull((yield* reader.read(credential, 0, 1781000000000)).error);
244 + assert.deepStrictEqual(requests, ["GetFilteredUsageEvents", "GetFilteredUsageEvents"]);
245 + rejected = true;
246 + assert.isNotNull((yield* reader.read(credential, 0, 1781000000000)).error);
247 + rejected = false;
248 + requests.length = 0;
249 + assert.isNull((yield* reader.read(credential, 0, 1781000000000)).error);
250 + assert.include(requests, "GetTeams");
251 + requests.length = 0;
252 + yield* TestClock.adjust(lifetime);
253 + yield* reader.read(credential, 0, 1781000000000);
254 + assert.include(requests, "GetTeams");
255 + requests.length = 0;
256 + yield* reader.read({ ...credential, apiKey: accessToken + "other" }, 0, 1781000000000);
257 + assert.include(requests, "GetTeams");
258 + }).pipe(
259 + Effect.provide(
260 + CursorAccountReader.layer.pipe(
261 + Layer.provide(Layer.succeed(HttpClient.HttpClient, client)),
262 + ),
263 + ),
264 + );
265 + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
266 + );
267 +
268 + it.effect("starts personal and team reads together without waiting for either response", () =>
269 + Effect.gen(function* () {
270 + const personal = yield* Deferred.make<void>();
271 + const team = yield* Deferred.make<void>();
272 + const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`;
273 + const client = dashboard(() => Response.json({}), { userId: 42, teamIds: [7] }).pipe(
274 + HttpClient.transform((response, request) => {
275 + if (!request.url.endsWith("/GetFilteredUsageEvents")) return response;
276 + const body =
277 + request.body._tag === "Uint8Array"
278 + ? JSON.parse(new TextDecoder().decode(request.body.body))
279 + : {};
280 + const isPersonal = body.teamId === undefined;
281 + return Effect.gen(function* () {
282 + yield* Deferred.succeed(isPersonal ? personal : team, undefined);
283 + yield* Deferred.await(isPersonal ? team : personal);
284 + return yield* response;
285 + });
286 + }),
287 + );
288 + const result = yield* makeCursorAccountUsageReader.pipe(
289 + Effect.flatMap((read) => read({ kind: "apiKey", apiKey: accessToken }, 0, 1781000000000)),
290 + Effect.provideService(HttpClient.HttpClient, client),
291 + );
292 + assert.isNull(result.error);
293 + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
294 + );
295 +
296 it.effect("reads Cursor account history beyond 100 pages", () =>
297 Effect.gen(function* () {
298 const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`;
@@ -341,37 +511,76 @@ describe("readCursorAccountUsage", () => {
511 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
512 );
513
344 - it.effect("reads the pages behind the first together and keeps them in page order", () =>
345 - Effect.gen(function* () {
346 - const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`;
347 - let inFlight = 0;
348 - let mostInFlight = 0;
349 - const result = yield* readAccountUsage(
350 - { kind: "apiKey", apiKey: accessToken },
351 - 0,
352 - 1781000000000,
353 - async ({ page }) => {
354 - inFlight++;
355 - mostInFlight = Math.max(mostInFlight, inFlight);
356 - for (let turn = page; turn < 9; turn++) await Promise.resolve();
357 - inFlight--;
358 - return Response.json({
359 - totalUsageEventsCount: 8001,
360 - usageEventsDisplay: Array.from({ length: page === 9 ? 1 : 1000 }, (_, index) => ({
361 - timestamp: String(1780000000000 + (page - 1) * 1000 + index),
362 - model: "gpt-5",
363 - tokenUsage: { inputTokens: 1 },
364 - })),
365 - });
366 - },
367 - );
368 - assert.isNull(result.error);
369 - assert.strictEqual(mostInFlight, 6);
370 - assert.deepStrictEqual(
371 - result.records.map((record) => record.timestampMs),
372 - Array.from({ length: 8001 }, (_, index) => 1780000000000 + index),
373 - );
374 - }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
514 + it.effect.each([{ queued: false }, { queued: true }])(
515 + "reads concurrent pages in order with a full request deadline after queuing: $queued",
516 + ({ queued }) =>
517 + Effect.gen(function* () {
518 + const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`;
519 + const started = yield* Queue.unbounded<void>();
520 + const firstBatch = yield* Deferred.make<void>();
521 + const secondBatch = yield* Deferred.make<void>();
522 + let delayedRequests = 0;
523 + let inFlight = 0;
524 + let mostInFlight = 0;
525 + const client = dashboard(
526 + async ({ page }) => {
527 + inFlight++;
528 + mostInFlight = Math.max(mostInFlight, inFlight);
529 + for (let turn = page; turn < 9; turn++) await Promise.resolve();
530 + inFlight--;
531 + return Response.json({
532 + totalUsageEventsCount: 8001,
533 + usageEventsDisplay: Array.from({ length: page === 9 ? 1 : 1000 }, (_, index) => ({
534 + timestamp: String(1780000000000 + (page - 1) * 1000 + index),
535 + model: "gpt-5",
536 + tokenUsage: { inputTokens: 1 },
537 + })),
538 + });
539 + },
540 + { userId: 42, teamIds: queued ? [7] : [] },
541 + ).pipe(
542 + HttpClient.transform((response, request) => {
543 + if (!queued || !request.url.endsWith("/GetFilteredUsageEvents")) return response;
544 + const body =
545 + request.body._tag === "Uint8Array"
546 + ? JSON.parse(new TextDecoder().decode(request.body.body))
547 + : {};
548 + if (body.page === 1) return response;
549 + return Effect.gen(function* () {
550 + const batch = delayedRequests++ < 6 ? firstBatch : secondBatch;
551 + yield* Queue.offer(started, undefined);
552 + yield* Deferred.await(batch);
553 + return yield* response;
554 + });
555 + }),
556 + );
557 + const read = yield* Effect.forkChild(
558 + makeCursorAccountUsageReader.pipe(
559 + Effect.flatMap((reader) =>
560 + reader({ kind: "apiKey", apiKey: accessToken }, 0, 1781000000000),
561 + ),
562 + Effect.provideService(HttpClient.HttpClient, client),
563 + ),
564 + );
565 + if (queued) {
566 + yield* Effect.all(Array.from({ length: 6 }, () => Queue.take(started)));
567 + yield* TestClock.adjust("6 seconds");
568 + yield* Deferred.succeed(firstBatch, undefined);
569 + yield* Effect.all(Array.from({ length: 6 }, () => Queue.take(started)));
570 + yield* TestClock.adjust("6 seconds");
571 + yield* Deferred.succeed(secondBatch, undefined);
572 + }
573 + const result = yield* Fiber.join(read);
574 + assert.isNull(result.error);
575 + assert.strictEqual(mostInFlight, 6);
576 + assert.deepStrictEqual(
577 + result.records.map((record) => record.timestampMs),
578 + Array.from(
579 + { length: queued ? 16002 : 8001 },
580 + (_, index) => 1780000000000 + (index % 8001),
581 + ),
582 + );
583 + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
584 );
585
586 it.effect("ends like a page-by-page read when a page fails, leaving no request open", () =>
packages/provider-cursor/src/server/accountUsage.ts
+337 -236
@@ -1,5 +1,9 @@
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";
@@ -47,8 +51,26 @@ const invalid = (reason: string) => Effect.fail(new CursorAccountUsageInvalidErr
51
52 const decodeJson = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown));
53
50 -const pageRequestBody = (page: number, pageSize: number, sinceMs: number, endDate: number) =>
51 - JSON.stringify({ page, pageSize, startDate: String(sinceMs), endDate: String(endDate) });
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
@@ -80,257 +102,336 @@ function boundaryOverlap(previous: readonly string[], current: readonly string[]
102 /** Never forward the access token through a redirect. */
103 const NO_REDIRECT: RequestInit = { redirect: "error" };
104
83 -export const readCursorAccountUsage = Effect.fn("readCursorAccountUsage")(function* (
84 - credentialSource: CursorCredentialSource,
85 - sinceMs: number,
86 - endDate: number,
87 -): Effect.fn.Return<CursorAccountUsageReadResult, never, Digest.Digest | HttpClient.HttpClient> {
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));
92 - const credential = yield* Effect.result(exchangeCursorApiKey(credentialSource.apiKey));
93 - if (Result.isFailure(credential)) {
94 - return {
95 - accountKey: null,
96 - records: [],
97 - missing: false,
98 - error: "Cursor account usage could not be read.",
99 - };
100 - }
101 - const accessToken = credential.success;
102 - let accountKey: string | null = null;
103 - const read = Effect.gen(function* () {
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");
106 - const subject = object(
114 + const authentication = object(
115 yield* decodeJson(payload.success).pipe(
116 Effect.catch(() => invalid("Invalid authentication")),
117 ),
110 - ).sub;
118 + );
119 + const subject = authentication.sub;
120 if (typeof subject !== "string" || !subject) return yield* invalid("Invalid authentication");
112 - accountKey = yield* accountHash(subject);
113 - if (!Number.isFinite(sinceMs) || !Number.isFinite(endDate) || sinceMs < 0 || sinceMs > endDate)
114 - return yield* invalid("Invalid date window");
115 - const pageRequest = HttpClientRequest.post(
116 - `${DEFAULT_CURSOR_API_ENDPOINT}/aiserver.v1.DashboardService/GetFilteredUsageEvents`,
117 - ).pipe(
118 - HttpClientRequest.bearerToken(accessToken),
119 - HttpClientRequest.setHeader("connect-protocol-version", "1"),
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 );
121 - const records: UsageRecord[] = [];
122 - const occurrences = new Map<string, number>();
123 - const normalized: Array<(Omit<UsageRecord, "dedupeKey"> & { dedupeKey: string }) | null> = [];
124 - const pages: Array<{ start: number; end: number; overlap: number }> = [];
125 - let previousEvents: unknown[] = [];
126 - const pageSize = 1000;
127 - let total: number | undefined;
128 - const readPage = Effect.fn("CursorAccountUsage.readPage")(
129 - function* (page: number) {
130 - // A count can include overlapping page boundaries. Allow room to
131 - // reconcile them without imposing a fixed account-size limit.
132 - if (page > (total === undefined ? 1000 : Math.ceil(total / pageSize) * 2 + 1)) {
133 - return yield* invalid("Account usage page limit exceeded");
134 - }
135 - const response = yield* httpClient
136 - .execute(
137 - pageRequest.pipe(
138 - HttpClientRequest.bodyText(
139 - pageRequestBody(page, pageSize, sinceMs, endDate),
140 - "application/json",
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 ),
142 - ),
143 - )
144 - .pipe(
145 - Effect.provideService(FetchHttpClient.RequestInit, NO_REDIRECT),
146 - Effect.mapError(
147 - () => new CursorAccountUsageInvalidError({ reason: "Account usage request failed" }),
148 - ),
149 - );
150 - if (response.status === 401 || response.status === 403) {
151 - return {
152 - accountKey,
153 - records: [],
154 - missing: false,
155 - error: "Sign in to Cursor again to read account usage.",
156 - } satisfies CursorAccountUsageReadResult;
157 - }
158 - if (response.status < 200 || response.status >= 300)
159 - return yield* invalid("Account usage request failed");
160 - const parsed: unknown = yield* response.json.pipe(
161 - Effect.mapError(
162 - () => new CursorAccountUsageInvalidError({ reason: "Invalid account usage page" }),
163 - ),
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 );
165 - if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
166 - return yield* invalid("Invalid account usage page");
167 - }
168 - const body = object(parsed);
169 - const keys = Object.keys(body);
170 - if ("error" in body || "message" in body || "code" in body)
171 - return yield* invalid("Account usage error response");
172 - const count = keys.length === 0 ? 0 : body.totalUsageEventsCount;
173 - const events =
174 - keys.length === 0 || (keys.length === 1 && keys[0] === "totalUsageEventsCount")
175 - ? []
176 - : body.usageEventsDisplay;
177 - if (
178 - (count !== undefined &&
179 - (typeof count !== "number" ||
180 - !Number.isSafeInteger(count) ||
181 - count < 0 ||
182 - (total !== undefined && count !== total))) ||
183 - !Array.isArray(events) ||
184 - events.length > pageSize ||
185 - (count === undefined && !Array.isArray(body.usageEventsDisplay))
186 - ) {
187 - return yield* invalid("Inconsistent account usage page");
188 - }
189 - if (typeof count === "number") total = count;
190 - return events as unknown[];
191 - },
192 - Effect.timeoutOrElse({
193 - duration: Duration.seconds(10),
194 - orElse: () => invalid("Account usage request timed out"),
195 - }),
196 - );
197 - // Cursor caps a page at 1,000 events and takes about a second to answer one, so the pages
198 - // the first one's count implies are requested up to six ahead and consumed in page order.
199 - const ahead: Fiber.Fiber<
200 - Effect.Success<ReturnType<typeof readPage>>,
201 - CursorAccountUsageInvalidError
202 - >[] = [];
203 - for (let page = 1; ; page++) {
204 - while (ahead.length < Math.min(6, Math.ceil((total ?? 0) / pageSize) - page + 1)) {
205 - ahead.push(yield* Effect.forkScoped(readPage(page + ahead.length)));
206 - }
207 - const next = ahead.shift();
208 - const events = yield* next === undefined ? readPage(page) : Fiber.join(next);
209 - if (!Array.isArray(events)) return events;
210 - const start = normalized.length;
211 - const firstTimestamp = object(events[0]).timestamp;
212 - // Equal raw events must have equal timestamps; avoid canonicalizing disjoint pages.
213 - const mayOverlap =
214 - (typeof firstTimestamp !== "string" && typeof firstTimestamp !== "number") ||
215 - previousEvents.some((event) => object(event).timestamp === firstTimestamp);
216 - const overlap = mayOverlap
217 - ? boundaryOverlap(previousEvents.map(canonicalJson), events.map(canonicalJson))
218 - : 0;
219 - previousEvents = events;
220 - for (const raw of events) {
221 - const event = object(raw);
222 - const usage = object(event.tokenUsage);
223 - if (event.tokenUsage === undefined || event.tokenUsage === null) {
224 - normalized.push(null);
225 - continue;
226 - }
227 - for (const key of [
228 - "inputTokens",
229 - "outputTokens",
230 - "cacheReadTokens",
231 - "cacheWriteTokens",
232 - "totalCents",
233 - ]) {
234 - const value = usage[key];
235 - if (
236 - value !== undefined &&
237 - (typeof value !== "number" || !Number.isFinite(value) || value < 0)
238 - ) {
239 - return yield* invalid("Invalid account usage totals");
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 }
242 - const timestampMs =
243 - typeof event.timestamp === "string" && event.timestamp.trim() !== ""
244 - ? Number(event.timestamp)
245 - : event.timestamp;
246 - if (
247 - typeof timestampMs !== "number" ||
248 - !Number.isFinite(timestampMs) ||
249 - typeof event.model !== "string" ||
250 - !event.model
251 - )
252 - return yield* invalid("Invalid account usage event");
253 - if (timestampMs < sinceMs || timestampMs > endDate) {
254 - normalized.push(null);
255 - continue;
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 }
257 - const totals = {
258 - uncachedInputTokens: tokens(usage.inputTokens),
259 - cachedInputTokens: tokens(usage.cacheReadTokens),
260 - cacheCreationTokens: tokens(usage.cacheWriteTokens),
261 - outputTokens: tokens(usage.outputTokens),
262 - reasoningTokens: 0,
263 - };
264 - const reportedCostUsd =
265 - typeof usage.totalCents === "number" ? usage.totalCents / 100 : null;
266 - const sessionId = typeof event.conversationId === "string" ? event.conversationId : "";
267 - // No event ID is provided. Preserve identical billed rows with an occurrence index.
268 - const key = yield* accountHash(
269 - billedEventIdentity(timestampMs, event.model, sessionId, totals, reportedCostUsd),
270 - );
271 - normalized.push({
272 - provider: "cursor",
273 - timestampMs,
274 - model: event.model,
275 - rateModel: cursorRateModel(event.model),
276 - sessionId,
277 - totals,
278 - reportedCostUsd,
279 - speed: "standard",
280 - dedupeKey: key,
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 });
282 - }
283 - pages.push({ start, end: normalized.length, overlap });
284 - if (events.length < pageSize) break;
285 - yield* Effect.yieldNow;
286 - }
287 - const rawCount = normalized.length;
288 - if (total !== undefined && rawCount < total)
289 - return yield* invalid("Incomplete account usage pages");
290 - let removalsRemaining = total === undefined ? 0 : rawCount - total;
291 - // The final count proves which boundary copies to remove, including non-token events.
292 - for (const page of pages) {
293 - const removalCount = Math.min(removalsRemaining, page.overlap);
294 - removalsRemaining -= removalCount;
295 - for (let index = page.start; index < page.end; index++) {
296 - const record = normalized[index];
297 - normalized[index] = null;
298 - if (index < page.start + removalCount || record == null) continue;
299 - const key = record.dedupeKey;
300 - const occurrence = occurrences.get(key) ?? 0;
301 - occurrences.set(key, occurrence + 1);
302 - record.dedupeKey = `cursor-account:${accountKey}:${key}:${occurrence}`;
303 - records.push(record);
304 - }
305 - yield* Effect.yieldNow;
306 - }
307 - if (removalsRemaining !== 0) return yield* invalid("Inconsistent account usage boundaries");
308 - yield* Effect.annotateCurrentSpan({
309 - "cursor.usage.pages": pages.length,
310 - "cursor.usage.events": rawCount,
311 - "cursor.usage.records": records.length,
312 - });
313 - return {
314 - accountKey,
315 - records,
316 - missing: false,
317 - error: null,
318 - } satisfies CursorAccountUsageReadResult;
319 - });
320 - return yield* read.pipe(
321 - Effect.scoped,
322 - Effect.timeoutOrElse({
323 - duration: Duration.seconds(60),
324 - orElse: () => invalid("Account usage read timed out"),
325 - }),
326 - Effect.orElseSucceed(
327 - () =>
328 - ({
398 + return {
399 accountKey,
330 - records: [],
400 + records,
401 missing: false,
332 - error: "Cursor account usage could not be read.",
333 - }) satisfies CursorAccountUsageReadResult,
334 - ),
335 - );
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 });