@devries-cameron20 / t3code-1 / commits / af00cf73e1
Fork 0

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

fix(cursor): show Cursor usage after signing in with Cursor (#29419)

Co-authored-by: maria-rcks <maria@kuuro.net>

Serhiy Khvala committed Nov 2, 2026 at 22:46 UTC af00cf73e1b952586b51f77976f913a35154f30c
11 files changed +492 -52
apps/server/src/usage/UsageService.test.ts
+221 -7
@@ -30,6 +30,7 @@ import * as Fiber from "effect/Fiber";
30 import * as FileSystem from "effect/FileSystem";
31 import * as Context from "effect/Context";
32 import * as Layer from "effect/Layer";
33 +import * as Option from "effect/Option";
34 import * as Scheduler from "effect/Scheduler";
35 import * as Schema from "effect/Schema";
36 import * as TestClock from "effect/testing/TestClock";
@@ -149,6 +150,7 @@ const layerService = (input: {
150 readonly environment?: NodeJS.ProcessEnv;
151 readonly platform?: NodeJS.Platform;
152 readonly hostname?: string;
153 + readonly secretStore?: Partial<ServerSecretStore.ServerSecretStore["Service"]>;
154 }) =>
155 layerCursorUsageAccounts(
156 CursorAccountReader.layer.pipe(Layer.provide(CursorKeychain.layer)),
@@ -158,7 +160,12 @@ const layerService = (input: {
160 Layer.provideMerge(ProviderHostLive.layer),
161 Layer.provideMerge(CodexUsageHistory.layer.pipe(Layer.provideMerge(Sqlite.layerMemory))),
162 Layer.provideMerge(Layer.mock(BackgroundPolicy.BackgroundPolicy)({})),
161 - Layer.provideMerge(Layer.mock(ServerSecretStore.ServerSecretStore)({})),
163 + Layer.provideMerge(
164 + Layer.mock(ServerSecretStore.ServerSecretStore)({
165 + get: () => Effect.succeedNone,
166 + ...input.secretStore,
167 + }),
168 + ),
169 Layer.provideMerge(
170 ServerConfig.layerTest(process.cwd(), NodePath.join(input.home, input.prefix)),
171 ),
@@ -239,10 +246,12 @@ function makeFakeCursor() {
246 error: null as string | null,
247 gate: undefined as Deferred.Deferred<void> | undefined,
248 calls: [] as { readonly sinceMs: number; readonly untilMs: number }[],
249 + credentials: [] as unknown[],
250 };
243 - const read = (_credential: unknown, sinceMs: number, untilMs: number) =>
251 + const read = (credential: unknown, sinceMs: number, untilMs: number) =>
252 Effect.gen(function* () {
253 state.calls.push({ sinceMs, untilMs });
254 + state.credentials.push(credential);
255 if (state.gate !== undefined) yield* Deferred.await(state.gate);
256 const { accountKey, error } = state;
257 if (error !== null) return { accountKey, records: [], missing: false, error };
@@ -286,6 +295,10 @@ function cursorSource(summary: { readonly sources: readonly UsageSource[] }) {
295 return summary.sources.find((source) => source.fingerprint.provider === "cursor");
296 }
297
298 +function cursorSources(summary: { readonly sources: readonly UsageSource[] }) {
299 + return summary.sources.filter((source) => source.fingerprint.provider === "cursor");
300 +}
301 +
302 const seedCodexHistory = (input: {
303 id: string;
304 nativeTurnId?: string;
@@ -1512,11 +1525,6 @@ describe("UsageService", () => {
1525 environment: { AGENT_CLI_CREDENTIAL_STORE: "memory" },
1526 authPath: ["config", "cursor", "auth.json"],
1527 },
1515 - {
1516 - platform: "linux" as const,
1517 - environment: { CURSOR_API_KEY: "different-account" },
1518 - authPath: ["config", "cursor", "auth.json"],
1519 - },
1528 ].entries()) {
1529 const authPath = NodePath.join(home, ...testCase.authPath);
1530 yield* Effect.promise(async () => {
@@ -1546,6 +1554,212 @@ describe("UsageService", () => {
1554 }).pipe(Effect.scoped),
1555 );
1556
1557 + it.live("reads the Cursor account of an API key or T3 sign-in instead of a CLI login", () =>
1558 + Effect.gen(function* () {
1559 + const { settings, home } = yield* setup;
1560 + const signIn = new TextEncoder().encode(
1561 + encodeUnknownJsonString({
1562 + version: 1,
1563 + backendUrl: "https://api2.cursor.sh",
1564 + apiKey: "signed-in-key",
1565 + createdAtMs: 0,
1566 + }),
1567 + );
1568 + for (const [index, testCase] of [
1569 + { environment: { CURSOR_API_KEY: "environment-key" }, stored: Option.none() },
1570 + { environment: {}, stored: Option.some(signIn) },
1571 + ].entries()) {
1572 + const cursor = makeFakeCursor();
1573 + const summary = yield* Effect.gen(function* () {
1574 + const service = yield* makeWithCursor(cursor.read);
1575 + return yield* service.readSummary({ ...WINDOW, awaitRefresh: true });
1576 + }).pipe(
1577 + Effect.provide(
1578 + layerService({
1579 + prefix: `usage-service-cursor-api-key-${index}`,
1580 + home,
1581 + settings,
1582 + platform: "darwin",
1583 + environment: testCase.environment,
1584 + secretStore: { get: () => Effect.succeed(testCase.stored) },
1585 + }),
1586 + ),
1587 + );
1588 + assert.deepStrictEqual(cursor.state.credentials, [
1589 + { kind: "apiKey", apiKey: index === 0 ? "environment-key" : "signed-in-key" },
1590 + ]);
1591 + assert.strictEqual(cursorSource(summary)?.status, "ok");
1592 + }
1593 + }).pipe(Effect.scoped),
1594 + );
1595 +
1596 + it.live("does not show a previous Cursor account's history after the API key changes", () =>
1597 + Effect.gen(function* () {
1598 + const { settings, home } = yield* setup;
1599 + yield* TestClock.setTime(CURSOR_NOW);
1600 + let apiKey = "first-account-key";
1601 + const signIn = () =>
1602 + Option.some(
1603 + new TextEncoder().encode(
1604 + encodeUnknownJsonString({
1605 + version: 1,
1606 + backendUrl: "https://api2.cursor.sh",
1607 + apiKey,
1608 + createdAtMs: 0,
1609 + }),
1610 + ),
1611 + );
1612 + const cursor = makeFakeCursor();
1613 + cursor.state.events = [{ timestampMs: CURSOR_NOW - 3 * HOUR_MS, outputTokens: 7 }];
1614 + yield* Effect.gen(function* () {
1615 + const service = yield* makeWithCursor(cursor.read);
1616 + const first = yield* service.readSummary({ ...WINDOW, awaitRefresh: true });
1617 + assert.isTrue(first.buckets.some((bucket) => bucket.provider === "cursor"));
1618 +
1619 + apiKey = "second-account-key";
1620 + cursor.state.error = "Cursor account usage could not be read.";
1621 + const second = yield* service.readSummary({ ...WINDOW, awaitRefresh: true });
1622 + assert.isFalse(second.buckets.some((bucket) => bucket.provider === "cursor"));
1623 + }).pipe(
1624 + Effect.provide(
1625 + layerService({
1626 + prefix: "usage-service-cursor-key-change",
1627 + home,
1628 + settings,
1629 + platform: "darwin",
1630 + environment: {},
1631 + secretStore: { get: () => Effect.sync(signIn) },
1632 + }),
1633 + ),
1634 + );
1635 + }).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
1636 + );
1637 +
1638 + it.live("keeps a new Cursor key's refresh visible beside a failing key", () =>
1639 + Effect.gen(function* () {
1640 + const { settings, home } = yield* setup;
1641 + const cursor = makeFakeCursor();
1642 + const started = yield* Deferred.make<void>();
1643 + const gate = yield* Deferred.make<void>();
1644 + yield* Effect.gen(function* () {
1645 + const context = yield* Layer.build(
1646 + layerCursorUsageAccounts(
1647 + Layer.succeed(CursorAccountReader.CursorAccountReader, {
1648 + read: (credential, sinceMs, untilMs) =>
1649 + (credential as { apiKey?: string }).apiKey === "failing-key"
1650 + ? Effect.succeed({
1651 + accountKey: null,
1652 + records: [],
1653 + missing: false,
1654 + error: "Cursor account usage could not be read.",
1655 + })
1656 + : Deferred.succeed(started, undefined).pipe(
1657 + Effect.andThen(Deferred.await(gate)),
1658 + Effect.andThen(cursor.read(credential, sinceMs, untilMs)),
1659 + ),
1660 + }),
1661 + ),
1662 + );
1663 + const accounts = Context.get(context, CursorUsageAccounts.CursorUsageAccounts);
1664 + const scan = (awaitRefresh: boolean) =>
1665 + accounts.scan({
1666 + instances: [
1667 + {
1668 + instanceId: ProviderInstanceId.make("cursor"),
1669 + environment: { CURSOR_API_KEY: "failing-key" },
1670 + },
1671 + {
1672 + instanceId: ProviderInstanceId.make("cursor-work"),
1673 + environment: { CURSOR_API_KEY: "new-key" },
1674 + },
1675 + ],
1676 + keychainUsageEnabled: false,
1677 + windowStartMs: 0,
1678 + retentionCutoffMs: 0,
1679 + awaitRefresh,
1680 + });
1681 + const first = yield* Effect.forkChild(scan(true));
1682 + yield* Deferred.await(started);
1683 + const sources = yield* scan(false);
1684 + assert.isTrue(sources.some((source) => source.refreshing === true));
1685 + yield* Deferred.succeed(gate, undefined);
1686 + yield* Fiber.join(first);
1687 + }).pipe(
1688 + Effect.provide(
1689 + layerService({
1690 + prefix: "usage-service-cursor-new-key",
1691 + home,
1692 + settings,
1693 + platform: "linux",
1694 + environment: {},
1695 + }),
1696 + ),
1697 + );
1698 + }).pipe(Effect.scoped),
1699 + );
1700 +
1701 + it.live("reports one Cursor source when two API keys belong to the same account", () =>
1702 + Effect.gen(function* () {
1703 + const { settings, home } = yield* setup;
1704 + yield* TestClock.setTime(CURSOR_NOW);
1705 + const cursor = makeFakeCursor();
1706 + cursor.state.events = [{ timestampMs: CURSOR_NOW - 3 * HOUR_MS, outputTokens: 7 }];
1707 + let revoked = false;
1708 + yield* Effect.gen(function* () {
1709 + const service = yield* makeWithCursor((credential, sinceMs, untilMs) =>
1710 + revoked && (credential as { apiKey?: string }).apiKey === "second-key"
1711 + ? Effect.succeed({
1712 + accountKey: null,
1713 + records: [],
1714 + missing: false,
1715 + error: "Cursor account usage could not be read.",
1716 + })
1717 + : cursor.read(credential, sinceMs, untilMs),
1718 + );
1719 + const first = yield* service.readSummary({ ...WINDOW, awaitRefresh: true });
1720 + assert.strictEqual(cursor.state.credentials.length, 2);
1721 + assert.deepStrictEqual(
1722 + cursorSources(first).map((source) => source.distinctSessions),
1723 + [1],
1724 + );
1725 +
1726 + // The revoked key keeps its stale cache, which must not replace the working key's history.
1727 + revoked = true;
1728 + cursor.state.events.push({ timestampMs: CURSOR_NOW + 60 * 1000, outputTokens: 5 });
1729 + yield* TestClock.adjust(Duration.minutes(2));
1730 + const second = yield* service.readSummary({ ...WINDOW, awaitRefresh: true });
1731 + assert.deepStrictEqual(
1732 + cursorSources(second).map((source) => source.status),
1733 + ["ok"],
1734 + );
1735 + assert.strictEqual(totalOutputTokens(second), 12);
1736 + }).pipe(
1737 + Effect.provide(
1738 + layerService({
1739 + prefix: "usage-service-cursor-shared-account",
1740 + home,
1741 + settings: {
1742 + ...settings,
1743 + providerInstances: {
1744 + ...settings.providerInstances,
1745 + [ProviderInstanceId.make("cursor")]: {
1746 + driver: ProviderDriverKind.make("cursor"),
1747 + environment: [{ name: "CURSOR_API_KEY", value: "first-key", sensitive: true }],
1748 + },
1749 + [ProviderInstanceId.make("cursor-work")]: {
1750 + driver: ProviderDriverKind.make("cursor"),
1751 + environment: [{ name: "CURSOR_API_KEY", value: "second-key", sensitive: true }],
1752 + },
1753 + },
1754 + },
1755 + platform: "darwin",
1756 + environment: {},
1757 + }),
1758 + ),
1759 + );
1760 + }).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
1761 + );
1762 +
1763 it.live(
1764 "includes OpenCode history but does not substitute desktop usage for an unavailable Cursor account",
1765 () =>
docs/user/usage.md
+10 -8
@@ -24,12 +24,13 @@ OpenCode reads its SQLite database and older JSON history. Antigravity reads loc
24 databases, including T3-managed profiles. Set `OPENCODE_DATA_DIR` or `ANTIGRAVITY_DATA_DIR` on the
25 server to read a different data directory; comma-separated paths read multiple directories.
26
27 -Cursor reads account usage from Cursor's dashboard API using the CLI login saved on the server.
27 +Cursor reads account usage from Cursor's API for the account you signed in with in T3 or set as
28 +`CURSOR_API_KEY`, or otherwise the CLI login saved on the server.
29 This includes headless T3 sessions and desktop usage across machines; the same account counts
29 -once across connected environments. Without an accessible CLI login, T3 shows a
30 +once across connected environments. Without any of these, T3 shows a
31 notice instead of incomplete local totals. T3 does not estimate missing tokens from conversation text.
31 -On macOS, choose **Enable Cursor usage** on Usage to allow T3 to read your existing CLI login
32 -from Keychain. You can turn it off in **Settings → Providers → Usage providers**. macOS may ask
32 +On macOS without a T3 sign-in, choose **Enable Cursor usage** on Usage to allow T3 to read your
33 +existing CLI login from Keychain. You can turn it off in **Settings → Providers → Usage providers**. macOS may ask
34 you to allow access on the server Mac.
35
36 Usage includes each configured account's history, including disabled accounts. Custom homes follow
@@ -159,10 +160,11 @@ belong to the remote server. Limits need an OpenCode Go API key, or an OpenCode
160 in OpenCode with an API key. A Console browser sign-in alone does not report them. You can also add
161 your Go API key as `OPENCODE_API_KEY` in the OpenCode instance's **Environment variables**, then
162 refresh provider status. Cursor reports
162 -its monthly allowance, including separate Auto and API usage, using the CLI login or
163 -`CURSOR_AUTH_TOKEN`. On macOS, this includes the default Keychain login after you enable Cursor
164 -usage. Keychain login is used for limits only with Cursor's default API endpoint. If you configure
165 -a custom Cursor endpoint, use an explicit token or file-based CLI login for limits.
163 +its monthly allowance, including separate Auto and API usage, for `CURSOR_AUTH_TOKEN` when it is set,
164 +otherwise for the account you signed in with in T3 or set as `CURSOR_API_KEY`, otherwise for the CLI
165 +login. On macOS, this includes the default Keychain login after you enable Cursor usage. Sign-in, API key,
166 +and Keychain login report limits only with Cursor's default API endpoint. If you configure a custom
167 +Cursor endpoint, use an explicit token or file-based CLI login for limits.
168
169 Grok reports the remaining subscription allowance and reset time for its current billing period
170 after signing in with `grok login`. Explicit `XAI_API_KEY` connections and custom authentication
packages/provider-cursor/src/server/CursorUsageAccounts.ts
+75 -7
@@ -1,11 +1,14 @@
1 +import type { ProviderInstanceId } from "@t3tools/contracts";
2 import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
3 import type { ProviderUsageScan } from "@t3tools/provider-core/server/usage";
4 import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
5 import * as HostProcess from "@t3tools/shared/HostProcess";
6 import * as Clock from "effect/Clock";
7 import * as Context from "effect/Context";
8 +import * as Crypto from "effect/Crypto";
9 import * as Deferred from "effect/Deferred";
10 import * as Effect from "effect/Effect";
11 +import * as Hex from "effect/encoding/Hex";
12 import * as Fiber from "effect/Fiber";
13 import * as FileSystem from "effect/FileSystem";
14 import * as Layer from "effect/Layer";
@@ -25,6 +28,7 @@ import {
28 type CursorCredentialSource,
29 } from "./accountCache.ts";
30 import * as CursorAccountReader from "./CursorAccountReader.ts";
31 +import { readStoredCursorApiKey } from "./credentialStore.ts";
32
33 const CURSOR_ACCOUNT_READ_ERROR = "Cursor account usage could not be read.";
34
@@ -36,6 +40,10 @@ export class CursorUsageAccounts extends Context.Service<
40 CursorUsageAccounts,
41 {
42 readonly scan: (input: {
43 + readonly instances: ReadonlyArray<{
44 + readonly instanceId: ProviderInstanceId;
45 + readonly environment: NodeJS.ProcessEnv;
46 + }>;
47 readonly keychainUsageEnabled: boolean;
48 readonly windowStartMs: number;
49 readonly retentionCutoffMs: number;
@@ -52,6 +60,7 @@ const make = Effect.gen(function* () {
60 const accountReader = yield* CursorAccountReader.CursorAccountReader;
61 const hostEnvironment = yield* HostProcess.Environment;
62 const platform = yield* HostProcess.Platform;
63 + const crypto = yield* Crypto.Crypto;
64
65 const cachePath = path.join(host.paths.stateDir, CURSOR_ACCOUNT_CACHE_FILE_NAME);
66 const caches = new Map<string, CursorAccountCache>();
@@ -187,12 +196,30 @@ const make = Effect.gen(function* () {
196 awaitRefresh: boolean,
197 ) {
198 // A Keychain login outlives an uninstalled Cursor, so it also needs Cursor's local directory.
190 - const localLogin = typeof credential === "string" ? credential : path.dirname(authPath);
191 - if (!(yield* fileSystem.exists(localLogin).pipe(Effect.orElseSucceed(() => true)))) {
199 + const localLogin =
200 + typeof credential === "string"
201 + ? credential
202 + : credential.kind === "keychain"
203 + ? path.dirname(authPath)
204 + : null;
205 + if (
206 + localLogin !== null &&
207 + !(yield* fileSystem.exists(localLogin).pipe(Effect.orElseSucceed(() => true)))
208 + ) {
209 return null;
210 }
211 yield* ensureLoaded;
195 - const credentialKey = typeof credential === "string" ? credential : "keychain";
212 + const credentialKey =
213 + typeof credential === "string"
214 + ? credential
215 + : credential.kind === "apiKey"
216 + ? // A fingerprint, so a replaced key never reads the previous account's cache.
217 + `api-key:${Hex.encode(
218 + yield* crypto
219 + .digest("SHA-256", new TextEncoder().encode(credential.apiKey))
220 + .pipe(Effect.orDie),
221 + )}`
222 + : "keychain";
223 const nowMs = yield* Clock.currentTimeMillis;
224 const recentFailure = failures.get(credentialKey);
225 let refreshing = false;
@@ -238,7 +265,13 @@ const make = Effect.gen(function* () {
265 });
266
267 const scan: CursorUsageAccounts["Service"]["scan"] = Effect.fn("CursorUsageAccounts.scan")(
241 - function* ({ keychainUsageEnabled, windowStartMs, retentionCutoffMs, awaitRefresh }) {
268 + function* ({
269 + instances,
270 + keychainUsageEnabled,
271 + windowStartMs,
272 + retentionCutoffMs,
273 + awaitRefresh,
274 + }) {
275 const home = yield* HostProcess.HomeDirectory;
276 const userHome =
277 (platform === "win32" ? hostEnvironment["USERPROFILE"] : hostEnvironment["HOME"]) || home;
@@ -255,11 +288,46 @@ const make = Effect.gen(function* () {
288 platform === "darwin"
289 ? path.join(userHome, ".cursor", "auth.json")
290 : path.join(cursorHome, platform === "win32" ? "Cursor" : "cursor", "auth.json");
291 + // T3's Cursor sign-in and CURSOR_API_KEY name the account the agent uses, so they win.
292 + const apiKeys = yield* Effect.forEach(instances, ({ instanceId, environment }) =>
293 + environment.CURSOR_API_KEY?.trim()
294 + ? Effect.succeed(environment.CURSOR_API_KEY.trim())
295 + : readStoredCursorApiKey(instanceId).pipe(
296 + Effect.provideService(ProviderHost.ProviderHost, host),
297 + Effect.orElseSucceed(() => undefined),
298 + ),
299 + );
300 + const uniqueApiKeys = [...new Set(apiKeys.filter((apiKey) => apiKey !== undefined))];
301 + if (uniqueApiKeys.length > 0) {
302 + const sources: ReadonlyArray<ProviderUsageScan | null> = yield* Effect.forEach(
303 + uniqueApiKeys,
304 + (apiKey) =>
305 + accountSource(
306 + { kind: "apiKey", apiKey },
307 + authPath,
308 + windowStartMs,
309 + retentionCutoffMs,
310 + awaitRefresh,
311 + ),
312 + );
313 + // Keys for one account share its source, and a repeated source would count sessions twice.
314 + // A failed key can hold older records, so a current read wins, then a refresh the client
315 + // must follow up on.
316 + const rank = (source: ProviderUsageScan) =>
317 + source.status === "ok" ? 2 : source.refreshing ? 1 : 0;
318 + const byAccount = new Map<string, ProviderUsageScan>();
319 + for (const source of sources) {
320 + if (source === null) continue;
321 + const kept = byAccount.get(source.dir);
322 + if (kept === undefined || rank(source) > rank(kept)) {
323 + byAccount.set(source.dir, source);
324 + }
325 + }
326 + return [...byAccount.values()];
327 + }
328 const credentialStore = hostEnvironment["AGENT_CLI_CREDENTIAL_STORE"];
329 const loginUnavailable =
260 - Boolean(hostEnvironment["CURSOR_AUTH_TOKEN"]?.trim()) ||
261 - Boolean(hostEnvironment["CURSOR_API_KEY"]?.trim()) ||
262 - credentialStore === "memory";
330 + Boolean(hostEnvironment["CURSOR_AUTH_TOKEN"]?.trim()) || credentialStore === "memory";
331 const useKeychain = platform === "darwin" && credentialStore !== "file";
332 if (useKeychain && !loginUnavailable && !keychainUsageEnabled) {
333 return [
packages/provider-cursor/src/server/accountCache.ts
+4 -1
@@ -2,7 +2,10 @@
2 import { cursorRateModel } from "./accountUsage.ts";
3 import type { UsageRecord } from "@t3tools/provider-core/server/usage";
4
5 -export type CursorCredentialSource = string | { readonly kind: "keychain" };
5 +export type CursorCredentialSource =
6 + | string
7 + | { readonly kind: "keychain" }
8 + | { readonly kind: "apiKey"; readonly apiKey: string };
9
10 export const CURSOR_ACCOUNT_TTL_MS = 60 * 1000;
11
packages/provider-cursor/src/server/accountUsage.test.ts
+50
@@ -2,12 +2,14 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { assert, describe, it } from "@effect/vitest";
3 import * as Context from "effect/Context";
4 import * as Effect from "effect/Effect";
5 +import * as Fiber from "effect/Fiber";
6 import * as FileSystem from "effect/FileSystem";
7 import * as FetchHttpClient from "effect/http/FetchHttpClient";
8 import * as HttpClient from "effect/http/HttpClient";
9 import * as HttpClientError from "effect/http/HttpClientError";
10 import * as HttpClientResponse from "effect/http/HttpClientResponse";
11 import * as Path from "effect/Path";
12 +import * as TestClock from "effect/testing/TestClock";
13
14 import * as CursorKeychain from "./CursorKeychain.ts";
15 import { readCursorAccountUsage } from "./accountUsage.ts";
@@ -284,6 +286,54 @@ describe("Cursor account history", () => {
286 });
287
288 describe("readCursorAccountUsage", () => {
289 + it.effect("reads an API key's account history through Cursor's API", () =>
290 + Effect.gen(function* () {
291 + const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`;
292 + const requests: Array<readonly [string, string | null]> = [];
293 + const result = yield* readAccountUsage(
294 + { kind: "apiKey", apiKey: "api-key" },
295 + 0,
296 + 1781000000000,
297 + ({ url, headers }) => {
298 + requests.push([url, headers.get("authorization")]);
299 + return url.endsWith("/auth/exchange_user_api_key")
300 + ? Response.json({ accessToken })
301 + : Response.json({
302 + totalUsageEventsCount: 1,
303 + usageEventsDisplay: [
304 + { timestamp: "1780000000000", model: "gpt-5", tokenUsage: { outputTokens: 4 } },
305 + ],
306 + });
307 + },
308 + );
309 + assert.isNull(result.error);
310 + assert.deepStrictEqual(requests, [
311 + ["https://api2.cursor.sh/auth/exchange_user_api_key", "Bearer api-key"],
312 + [
313 + "https://api2.cursor.sh/aiserver.v1.DashboardService/GetFilteredUsageEvents",
314 + `Bearer ${accessToken}`,
315 + ],
316 + ]);
317 + assert.strictEqual(result.records[0]?.totals.outputTokens, 4);
318 + }).pipe(Effect.provide(NodeServices.layer)),
319 + );
320 +
321 + it.effect("stops waiting for an API key exchange that never answers", () =>
322 + Effect.gen(function* () {
323 + const read = yield* Effect.forkChild(
324 + readAccountUsage(
325 + { kind: "apiKey", apiKey: "api-key" },
326 + 0,
327 + 1781000000000,
328 + () => new Promise<Response>(() => {}),
329 + ),
330 + );
331 + yield* TestClock.adjust("10 seconds");
332 + const result = yield* Fiber.join(read);
333 + assert.strictEqual(result.error, "Cursor account usage could not be read.");
334 + }).pipe(Effect.provide(NodeServices.layer)),
335 + );
336 +
337 it.effect("asks for Keychain approval when the prompt goes unanswered", () =>
338 Effect.gen(function* () {
339 const result = yield* readAccountUsage(
packages/provider-cursor/src/server/accountUsage.ts
+32 -10
@@ -13,6 +13,8 @@ import * as PlatformError from "effect/PlatformError";
13 import * as Result from "effect/Result";
14 import * as Schema from "effect/Schema";
15
16 +import type { CursorCredentialSource } from "./accountCache.ts";
17 +import { DEFAULT_CURSOR_API_ENDPOINT, exchangeCursorApiKey } from "./apiKey.ts";
18 import * as CursorKeychain from "./CursorKeychain.ts";
19
20 function object(value: unknown): Record<string, unknown> {
@@ -90,7 +92,7 @@ const DASHBOARD_USAGE_URL = "https://cursor.com/api/dashboard/get-filtered-usage
92 const NO_REDIRECT: RequestInit = { redirect: "error" };
93
94 export const readCursorAccountUsage = Effect.fn("readCursorAccountUsage")(function* (
93 - credentialSource: string | { readonly kind: "keychain" },
95 + credentialSource: CursorCredentialSource,
96 sinceMs: number,
97 endDate: number,
98 keychainToken: Effect.Effect<
@@ -120,7 +122,14 @@ export const readCursorAccountUsage = Effect.fn("readCursorAccountUsage")(functi
122 Effect.flatMap(decodeJson),
123 Effect.map((credentials) => object(credentials).accessToken),
124 )
123 - : keychainToken,
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,9 +145,11 @@ export const readCursorAccountUsage = Effect.fn("readCursorAccountUsage")(functi
145 ? null
146 : typeof credentialSource === "string"
147 ? "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.",
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;
@@ -168,6 +179,21 @@ export const readCursorAccountUsage = Effect.fn("readCursorAccountUsage")(functi
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[][] = [];
@@ -183,11 +209,7 @@ export const readCursorAccountUsage = Effect.fn("readCursorAccountUsage")(functi
209 }
210 const response = yield* httpClient
211 .execute(
186 - HttpClientRequest.post(DASHBOARD_USAGE_URL).pipe(
187 - HttpClientRequest.setHeaders({
188 - Origin: "https://cursor.com",
189 - Cookie: `WorkosCursorSessionToken=${encodeURIComponent(`${userId}::${accessToken}`)}`,
190 - }),
212 + pageRequest.pipe(
213 HttpClientRequest.bodyText(
214 pageRequestBody(page, pageSize, sinceMs, endDate),
215 "application/json",
packages/provider-cursor/src/server/apiKey.ts new
+24
@@ -0,0 +1,24 @@
1 +import * as Effect from "effect/Effect";
2 +import * as Schema from "effect/Schema";
3 +import * as HttpClient from "effect/http/HttpClient";
4 +import * as HttpClientRequest from "effect/http/HttpClientRequest";
5 +import * as HttpClientResponse from "effect/http/HttpClientResponse";
6 +
7 +export const DEFAULT_CURSOR_API_ENDPOINT = "https://api2.cursor.sh";
8 +
9 +const ApiKeyExchange = Schema.Struct({ accessToken: Schema.NonEmptyString });
10 +
11 +/** Trades a user API key for the access token Cursor's RPCs accept, as `@cursor/sdk` does. */
12 +export const exchangeCursorApiKey = Effect.fn("exchangeCursorApiKey")(function* (apiKey: string) {
13 + const client = yield* HttpClient.HttpClient;
14 + const response = yield* client.execute(
15 + HttpClientRequest.post(`${DEFAULT_CURSOR_API_ENDPOINT}/auth/exchange_user_api_key`).pipe(
16 + HttpClientRequest.bearerToken(apiKey),
17 + HttpClientRequest.bodyJsonUnsafe({}),
18 + ),
19 + );
20 + const { accessToken } = yield* HttpClientResponse.schemaBodyJson(ApiKeyExchange)(
21 + yield* HttpClientResponse.filterStatusOk(response),
22 + );
23 + return accessToken;
24 +}, Effect.timeout("10 seconds"));
packages/provider-cursor/src/server/credentialStore.ts
+20
@@ -1,5 +1,6 @@
1 import type { SdkCredentialStore } from "@cursor/sdk";
2 import { ProviderSetupError, type ProviderInstanceId } from "@t3tools/contracts";
3 +import * as Clock from "effect/Clock";
4 import * as Effect from "effect/Effect";
5 import * as FileSystem from "effect/FileSystem";
6 import * as Option from "effect/Option";
@@ -90,3 +91,22 @@ export const makeCursorCredentialStore = Effect.fn("makeCursorCredentialStore")(
91 };
92 return { store, binding: credentials.binding };
93 });
94 +
95 +/** The unexpired API key from this instance's T3 sign-in, read without loading the SDK. */
96 +export const readStoredCursorApiKey = Effect.fn("readStoredCursorApiKey")(function* (
97 + instanceId: ProviderInstanceId,
98 +) {
99 + const stored = yield* (yield* (yield* ProviderHost.ProviderHost).credentials(
100 + "cursor",
101 + instanceId,
102 + )).get;
103 + if (Option.isNone(stored)) return undefined;
104 + const credentials = yield* decodeCredentials(new TextDecoder().decode(stored.value)).pipe(
105 + Effect.option,
106 + );
107 + if (Option.isNone(credentials)) return undefined;
108 + const { apiKey, apiKeyExpiresAtMs } = credentials.value;
109 + return apiKeyExpiresAtMs === undefined || apiKeyExpiresAtMs > (yield* Clock.currentTimeMillis)
110 + ? apiKey
111 + : undefined;
112 +});
packages/provider-cursor/src/server/driver.ts
+2 -1
@@ -74,10 +74,11 @@ export const CursorDriver: ProviderDriver<
74 usage: {
75 kind: "scan",
76 provider: "cursor",
77 - scan: ({ settings, windowStartMs, retentionCutoffMs, awaitRefresh }) =>
77 + scan: ({ instances, settings, windowStartMs, retentionCutoffMs, awaitRefresh }) =>
78 CursorUsageAccounts.CursorUsageAccounts.pipe(
79 Effect.flatMap((accounts) =>
80 accounts.scan({
81 + instances,
82 keychainUsageEnabled: settings.cursorKeychainUsageEnabled,
83 windowStartMs,
84 retentionCutoffMs,
packages/provider-cursor/src/server/usageLimits.test.ts
+40 -10
@@ -182,17 +182,46 @@ describe("Cursor usage limits", () => {
182 }),
183 );
184
185 - it.effect("does not use a stored login for an explicit API key", () =>
185 + it.effect("reads an API key's own account instead of a stored login", () =>
186 Effect.gen(function* () {
187 - const limits = yield* withNodeServices(
188 - readCursorUsageLimits({ apiEndpoint: "" }, { CURSOR_API_KEY: "different-account" }).pipe(
189 - Effect.provideService(
190 - HttpClient.HttpClient,
191 - HttpClient.make(() => Effect.die("must not request usage")),
187 + for (const platform of ["linux", "darwin"] as const) {
188 + const requests: Array<readonly [string, string | undefined]> = [];
189 + const limits = yield* withNodeServices(
190 + readCursorUsageLimits({ apiEndpoint: "" }, { CURSOR_API_KEY: "api-key" }, true).pipe(
191 + Effect.provideService(HostProcess.Platform, platform),
192 + Effect.provideService(
193 + FileSystem.FileSystem,
194 + FileSystem.makeNoop({
195 + readFileString: () => Effect.die("must not read a stored login"),
196 + }),
197 + ),
198 + Effect.provideService(
199 + HttpClient.HttpClient,
200 + HttpClient.make((request) => {
201 + requests.push([request.url, request.headers.authorization]);
202 + return Effect.succeed(
203 + HttpClientResponse.fromWeb(
204 + request,
205 + Response.json(
206 + request.url.endsWith("/auth/exchange_user_api_key")
207 + ? { accessToken: "api-key-access-token" }
208 + : { planUsage: { totalPercentUsed: 37 } },
209 + ),
210 + ),
211 + );
212 + }),
213 + ),
214 ),
193 - ),
194 - );
195 - expect(limits.unavailable?.reason).toBe("unsupported");
215 + );
216 + expect(requests).toEqual([
217 + ["https://api2.cursor.sh/auth/exchange_user_api_key", "Bearer api-key"],
218 + [
219 + "https://api2.cursor.sh/aiserver.v1.DashboardService/GetCurrentPeriodUsage",
220 + "Bearer api-key-access-token",
221 + ],
222 + ]);
223 + expect(limits.windows[0]?.usedPercent).toBe(37);
224 + }
225 }),
226 );
227
@@ -246,13 +275,14 @@ describe("Cursor usage limits", () => {
275 }),
276 );
277
249 - it.effect("does not read Keychain or send its token to a custom endpoint", () =>
278 + it.effect("does not send a Keychain login or API key to a custom endpoint", () =>
279 Effect.gen(function* () {
280 for (const [apiEndpoint, environment] of [
281 ["http://localhost:3000", {}],
282 ["", { CURSOR_API_ENDPOINT: "http://localhost:3000" }],
283 ["https://cursor-proxy.example", {}],
284 ["", { CURSOR_API_ENDPOINT: "https://cursor-proxy.example" }],
285 + ["https://cursor-proxy.example", { CURSOR_API_KEY: "api-key" }],
286 ] as const) {
287 const limits = yield* withNodeServices(
288 readCursorUsageLimits({ apiEndpoint }, environment, true).pipe(
packages/provider-cursor/src/server/usageLimits.ts
+14 -8
@@ -16,10 +16,10 @@ import {
16 makeUnavailableUsageLimits,
17 makeUsageLimits,
18 } from "@t3tools/provider-core/server/usageLimits";
19 +import { DEFAULT_CURSOR_API_ENDPOINT, exchangeCursorApiKey } from "./apiKey.ts";
20 import * as CursorKeychain from "./CursorKeychain.ts";
21
22 const CursorCredentials = Schema.Struct({ accessToken: Schema.optional(Schema.String) });
22 -const DEFAULT_CURSOR_API_ENDPOINT = "https://api2.cursor.sh";
23 const decodeCredentials = Schema.decodeEffect(Schema.fromJsonString(CursorCredentials));
24 const CursorUsageResponse = Schema.Struct({
25 billingCycleEnd: Schema.optional(Schema.Union([Schema.String, Schema.Number])),
@@ -77,19 +77,25 @@ export const readCursorUsageLimits = Effect.fn("readCursorUsageLimits")(function
77 DEFAULT_CURSOR_API_ENDPOINT
78 ).replace(/\/$/, "");
79 let token = environment.CURSOR_AUTH_TOKEN?.trim();
80 - // An explicit API key can name a different account from the stored login.
81 - if (!token && environment.CURSOR_API_KEY?.trim()) {
82 - return makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" });
83 - }
80 + const apiKey = environment.CURSOR_API_KEY?.trim();
81 const credentialStore = environment.AGENT_CLI_CREDENTIAL_STORE;
85 - if (!token && credentialStore === "memory") {
82 + // An API key can name a different account from the stored login, so read the key's own.
83 + if (!token && apiKey) {
84 + if (endpoint !== DEFAULT_CURSOR_API_ENDPOINT) {
85 + return makeUnavailableUsageLimits({
86 + checkedAt,
87 + reason: "unsupported",
88 + message: "Cursor usage for an API key requires the default Cursor endpoint.",
89 + });
90 + }
91 + token = yield* exchangeCursorApiKey(apiKey);
92 + } else if (!token && credentialStore === "memory") {
93 return makeUnavailableUsageLimits({
94 checkedAt,
95 reason: "unsupported",
96 message: "Cursor usage requires a CLI login or CURSOR_AUTH_TOKEN.",
97 });
91 - }
92 - if (!token && platform === "darwin" && credentialStore !== "file") {
98 + } else if (!token && platform === "darwin" && credentialStore !== "file") {
99 if (!allowKeychain) {
100 return makeUnavailableUsageLimits({
101 checkedAt,