Skip to content
TypeScript

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

Serhiy Khvalaaf00cf73e1b9
diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.ts
index 8c09383d56c..218072652cc 100644
--- a/apps/server/src/usage/UsageService.test.ts
+++ b/apps/server/src/usage/UsageService.test.ts
@@ -30,6 +30,7 @@ import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Context from "effect/Context";
import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
import * as Scheduler from "effect/Scheduler";
import * as Schema from "effect/Schema";
import * as TestClock from "effect/testing/TestClock";
@@ -149,6 +150,7 @@ const layerService = (input: {
readonly environment?: NodeJS.ProcessEnv;
readonly platform?: NodeJS.Platform;
readonly hostname?: string;
+ readonly secretStore?: Partial<ServerSecretStore.ServerSecretStore["Service"]>;
}) =>
layerCursorUsageAccounts(
CursorAccountReader.layer.pipe(Layer.provide(CursorKeychain.layer)),
@@ -158,7 +160,12 @@ const layerService = (input: {
Layer.provideMerge(ProviderHostLive.layer),
Layer.provideMerge(CodexUsageHistory.layer.pipe(Layer.provideMerge(Sqlite.layerMemory))),
Layer.provideMerge(Layer.mock(BackgroundPolicy.BackgroundPolicy)({})),
- Layer.provideMerge(Layer.mock(ServerSecretStore.ServerSecretStore)({})),
+ Layer.provideMerge(
+ Layer.mock(ServerSecretStore.ServerSecretStore)({
+ get: () => Effect.succeedNone,
+ ...input.secretStore,
+ }),
+ ),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), NodePath.join(input.home, input.prefix)),
),
@@ -239,10 +246,12 @@ function makeFakeCursor() {
error: null as string | null,
gate: undefined as Deferred.Deferred<void> | undefined,
calls: [] as { readonly sinceMs: number; readonly untilMs: number }[],
+ credentials: [] as unknown[],
};
- const read = (_credential: unknown, sinceMs: number, untilMs: number) =>
+ const read = (credential: unknown, sinceMs: number, untilMs: number) =>
Effect.gen(function* () {
state.calls.push({ sinceMs, untilMs });
+ state.credentials.push(credential);
if (state.gate !== undefined) yield* Deferred.await(state.gate);
const { accountKey, error } = state;
if (error !== null) return { accountKey, records: [], missing: false, error };
@@ -286,6 +295,10 @@ function cursorSource(summary: { readonly sources: readonly UsageSource[] }) {
return summary.sources.find((source) => source.fingerprint.provider === "cursor");
}
+function cursorSources(summary: { readonly sources: readonly UsageSource[] }) {
+ return summary.sources.filter((source) => source.fingerprint.provider === "cursor");
+}
+
const seedCodexHistory = (input: {
id: string;
nativeTurnId?: string;
@@ -1512,11 +1525,6 @@ describe("UsageService", () => {
environment: { AGENT_CLI_CREDENTIAL_STORE: "memory" },
authPath: ["config", "cursor", "auth.json"],
},
- {
- platform: "linux" as const,
- environment: { CURSOR_API_KEY: "different-account" },
- authPath: ["config", "cursor", "auth.json"],
- },
].entries()) {
const authPath = NodePath.join(home, ...testCase.authPath);
yield* Effect.promise(async () => {
@@ -1546,6 +1554,212 @@ describe("UsageService", () => {
}).pipe(Effect.scoped),
);
+ it.live("reads the Cursor account of an API key or T3 sign-in instead of a CLI login", () =>
+ Effect.gen(function* () {
+ const { settings, home } = yield* setup;
+ const signIn = new TextEncoder().encode(
+ encodeUnknownJsonString({
+ version: 1,
+ backendUrl: "https://api2.cursor.sh",
+ apiKey: "signed-in-key",
+ createdAtMs: 0,
+ }),
+ );
+ for (const [index, testCase] of [
+ { environment: { CURSOR_API_KEY: "environment-key" }, stored: Option.none() },
+ { environment: {}, stored: Option.some(signIn) },
+ ].entries()) {
+ const cursor = makeFakeCursor();
+ const summary = yield* Effect.gen(function* () {
+ const service = yield* makeWithCursor(cursor.read);
+ return yield* service.readSummary({ ...WINDOW, awaitRefresh: true });
+ }).pipe(
+ Effect.provide(
+ layerService({
+ prefix: `usage-service-cursor-api-key-${index}`,
+ home,
+ settings,
+ platform: "darwin",
+ environment: testCase.environment,
+ secretStore: { get: () => Effect.succeed(testCase.stored) },
+ }),
+ ),
+ );
+ assert.deepStrictEqual(cursor.state.credentials, [
+ { kind: "apiKey", apiKey: index === 0 ? "environment-key" : "signed-in-key" },
+ ]);
+ assert.strictEqual(cursorSource(summary)?.status, "ok");
+ }
+ }).pipe(Effect.scoped),
+ );
+
+ it.live("does not show a previous Cursor account's history after the API key changes", () =>
+ Effect.gen(function* () {
+ const { settings, home } = yield* setup;
+ yield* TestClock.setTime(CURSOR_NOW);
+ let apiKey = "first-account-key";
+ const signIn = () =>
+ Option.some(
+ new TextEncoder().encode(
+ encodeUnknownJsonString({
+ version: 1,
+ backendUrl: "https://api2.cursor.sh",
+ apiKey,
+ createdAtMs: 0,
+ }),
+ ),
+ );
+ const cursor = makeFakeCursor();
+ cursor.state.events = [{ timestampMs: CURSOR_NOW - 3 * HOUR_MS, outputTokens: 7 }];
+ yield* Effect.gen(function* () {
+ const service = yield* makeWithCursor(cursor.read);
+ const first = yield* service.readSummary({ ...WINDOW, awaitRefresh: true });
+ assert.isTrue(first.buckets.some((bucket) => bucket.provider === "cursor"));
+
+ apiKey = "second-account-key";
+ cursor.state.error = "Cursor account usage could not be read.";
+ const second = yield* service.readSummary({ ...WINDOW, awaitRefresh: true });
+ assert.isFalse(second.buckets.some((bucket) => bucket.provider === "cursor"));
+ }).pipe(
+ Effect.provide(
+ layerService({
+ prefix: "usage-service-cursor-key-change",
+ home,
+ settings,
+ platform: "darwin",
+ environment: {},
+ secretStore: { get: () => Effect.sync(signIn) },
+ }),
+ ),
+ );
+ }).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
+ );
+
+ it.live("keeps a new Cursor key's refresh visible beside a failing key", () =>
+ Effect.gen(function* () {
+ const { settings, home } = yield* setup;
+ const cursor = makeFakeCursor();
+ const started = yield* Deferred.make<void>();
+ const gate = yield* Deferred.make<void>();
+ yield* Effect.gen(function* () {
+ const context = yield* Layer.build(
+ layerCursorUsageAccounts(
+ Layer.succeed(CursorAccountReader.CursorAccountReader, {
+ read: (credential, sinceMs, untilMs) =>
+ (credential as { apiKey?: string }).apiKey === "failing-key"
+ ? Effect.succeed({
+ accountKey: null,
+ records: [],
+ missing: false,
+ error: "Cursor account usage could not be read.",
+ })
+ : Deferred.succeed(started, undefined).pipe(
+ Effect.andThen(Deferred.await(gate)),
+ Effect.andThen(cursor.read(credential, sinceMs, untilMs)),
+ ),
+ }),
+ ),
+ );
+ const accounts = Context.get(context, CursorUsageAccounts.CursorUsageAccounts);
+ const scan = (awaitRefresh: boolean) =>
+ accounts.scan({
+ instances: [
+ {
+ instanceId: ProviderInstanceId.make("cursor"),
+ environment: { CURSOR_API_KEY: "failing-key" },
+ },
+ {
+ instanceId: ProviderInstanceId.make("cursor-work"),
+ environment: { CURSOR_API_KEY: "new-key" },
+ },
+ ],
+ keychainUsageEnabled: false,
+ windowStartMs: 0,
+ retentionCutoffMs: 0,
+ awaitRefresh,
+ });
+ const first = yield* Effect.forkChild(scan(true));
+ yield* Deferred.await(started);
+ const sources = yield* scan(false);
+ assert.isTrue(sources.some((source) => source.refreshing === true));
+ yield* Deferred.succeed(gate, undefined);
+ yield* Fiber.join(first);
+ }).pipe(
+ Effect.provide(
+ layerService({
+ prefix: "usage-service-cursor-new-key",
+ home,
+ settings,
+ platform: "linux",
+ environment: {},
+ }),
+ ),
+ );
+ }).pipe(Effect.scoped),
+ );
+
+ it.live("reports one Cursor source when two API keys belong to the same account", () =>
+ Effect.gen(function* () {
+ const { settings, home } = yield* setup;
+ yield* TestClock.setTime(CURSOR_NOW);
+ const cursor = makeFakeCursor();
+ cursor.state.events = [{ timestampMs: CURSOR_NOW - 3 * HOUR_MS, outputTokens: 7 }];
+ let revoked = false;
+ yield* Effect.gen(function* () {
+ const service = yield* makeWithCursor((credential, sinceMs, untilMs) =>
+ revoked && (credential as { apiKey?: string }).apiKey === "second-key"
+ ? Effect.succeed({
+ accountKey: null,
+ records: [],
+ missing: false,
+ error: "Cursor account usage could not be read.",
+ })
+ : cursor.read(credential, sinceMs, untilMs),
+ );
+ const first = yield* service.readSummary({ ...WINDOW, awaitRefresh: true });
+ assert.strictEqual(cursor.state.credentials.length, 2);
+ assert.deepStrictEqual(
+ cursorSources(first).map((source) => source.distinctSessions),
+ [1],
+ );
+
+ // The revoked key keeps its stale cache, which must not replace the working key's history.
+ revoked = true;
+ cursor.state.events.push({ timestampMs: CURSOR_NOW + 60 * 1000, outputTokens: 5 });
+ yield* TestClock.adjust(Duration.minutes(2));
+ const second = yield* service.readSummary({ ...WINDOW, awaitRefresh: true });
+ assert.deepStrictEqual(
+ cursorSources(second).map((source) => source.status),
+ ["ok"],
+ );
+ assert.strictEqual(totalOutputTokens(second), 12);
+ }).pipe(
+ Effect.provide(
+ layerService({
+ prefix: "usage-service-cursor-shared-account",
+ home,
+ settings: {
+ ...settings,
+ providerInstances: {
+ ...settings.providerInstances,
+ [ProviderInstanceId.make("cursor")]: {
+ driver: ProviderDriverKind.make("cursor"),
+ environment: [{ name: "CURSOR_API_KEY", value: "first-key", sensitive: true }],
+ },
+ [ProviderInstanceId.make("cursor-work")]: {
+ driver: ProviderDriverKind.make("cursor"),
+ environment: [{ name: "CURSOR_API_KEY", value: "second-key", sensitive: true }],
+ },
+ },
+ },
+ platform: "darwin",
+ environment: {},
+ }),
+ ),
+ );
+ }).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
+ );
+
it.live(
"includes OpenCode history but does not substitute desktop usage for an unavailable Cursor account",
() =>
diff --git a/docs/user/usage.md b/docs/user/usage.md
index 71eb1e0fe87..d25bdba81f0 100644
--- a/docs/user/usage.md
+++ b/docs/user/usage.md
@@ -24,12 +24,13 @@ OpenCode reads its SQLite database and older JSON history. Antigravity reads loc
databases, including T3-managed profiles. Set `OPENCODE_DATA_DIR` or `ANTIGRAVITY_DATA_DIR` on the
server to read a different data directory; comma-separated paths read multiple directories.
-Cursor reads account usage from Cursor's dashboard API using the CLI login saved on the server.
+Cursor reads account usage from Cursor's API for the account you signed in with in T3 or set as
+`CURSOR_API_KEY`, or otherwise the CLI login saved on the server.
This includes headless T3 sessions and desktop usage across machines; the same account counts
-once across connected environments. Without an accessible CLI login, T3 shows a
+once across connected environments. Without any of these, T3 shows a
notice instead of incomplete local totals. T3 does not estimate missing tokens from conversation text.
-On macOS, choose **Enable Cursor usage** on Usage to allow T3 to read your existing CLI login
-from Keychain. You can turn it off in **Settings → Providers → Usage providers**. macOS may ask
+On macOS without a T3 sign-in, choose **Enable Cursor usage** on Usage to allow T3 to read your
+existing CLI login from Keychain. You can turn it off in **Settings → Providers → Usage providers**. macOS may ask
you to allow access on the server Mac.
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
in OpenCode with an API key. A Console browser sign-in alone does not report them. You can also add
your Go API key as `OPENCODE_API_KEY` in the OpenCode instance's **Environment variables**, then
refresh provider status. Cursor reports
-its monthly allowance, including separate Auto and API usage, using the CLI login or
-`CURSOR_AUTH_TOKEN`. On macOS, this includes the default Keychain login after you enable Cursor
-usage. Keychain login is used for limits only with Cursor's default API endpoint. If you configure
-a custom Cursor endpoint, use an explicit token or file-based CLI login for limits.
+its monthly allowance, including separate Auto and API usage, for `CURSOR_AUTH_TOKEN` when it is set,
+otherwise for the account you signed in with in T3 or set as `CURSOR_API_KEY`, otherwise for the CLI
+login. On macOS, this includes the default Keychain login after you enable Cursor usage. Sign-in, API key,
+and Keychain login report limits only with Cursor's default API endpoint. If you configure a custom
+Cursor endpoint, use an explicit token or file-based CLI login for limits.
Grok reports the remaining subscription allowance and reset time for its current billing period
after signing in with `grok login`. Explicit `XAI_API_KEY` connections and custom authentication
diff --git a/packages/provider-cursor/src/server/CursorUsageAccounts.ts b/packages/provider-cursor/src/server/CursorUsageAccounts.ts
index 07fa215f2ee..59adc4c6d92 100644
--- a/packages/provider-cursor/src/server/CursorUsageAccounts.ts
+++ b/packages/provider-cursor/src/server/CursorUsageAccounts.ts
@@ -1,11 +1,14 @@
+import type { ProviderInstanceId } from "@t3tools/contracts";
import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
import type { ProviderUsageScan } from "@t3tools/provider-core/server/usage";
import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
import * as HostProcess from "@t3tools/shared/HostProcess";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
+import * as Crypto from "effect/Crypto";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
+import * as Hex from "effect/encoding/Hex";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
@@ -25,6 +28,7 @@ import {
type CursorCredentialSource,
} from "./accountCache.ts";
import * as CursorAccountReader from "./CursorAccountReader.ts";
+import { readStoredCursorApiKey } from "./credentialStore.ts";
const CURSOR_ACCOUNT_READ_ERROR = "Cursor account usage could not be read.";
@@ -36,6 +40,10 @@ export class CursorUsageAccounts extends Context.Service<
CursorUsageAccounts,
{
readonly scan: (input: {
+ readonly instances: ReadonlyArray<{
+ readonly instanceId: ProviderInstanceId;
+ readonly environment: NodeJS.ProcessEnv;
+ }>;
readonly keychainUsageEnabled: boolean;
readonly windowStartMs: number;
readonly retentionCutoffMs: number;
@@ -52,6 +60,7 @@ const make = Effect.gen(function* () {
const accountReader = yield* CursorAccountReader.CursorAccountReader;
const hostEnvironment = yield* HostProcess.Environment;
const platform = yield* HostProcess.Platform;
+ const crypto = yield* Crypto.Crypto;
const cachePath = path.join(host.paths.stateDir, CURSOR_ACCOUNT_CACHE_FILE_NAME);
const caches = new Map<string, CursorAccountCache>();
@@ -187,12 +196,30 @@ const make = Effect.gen(function* () {
awaitRefresh: boolean,
) {
// A Keychain login outlives an uninstalled Cursor, so it also needs Cursor's local directory.
- const localLogin = typeof credential === "string" ? credential : path.dirname(authPath);
- if (!(yield* fileSystem.exists(localLogin).pipe(Effect.orElseSucceed(() => true)))) {
+ const localLogin =
+ typeof credential === "string"
+ ? credential
+ : credential.kind === "keychain"
+ ? path.dirname(authPath)
+ : null;
+ if (
+ localLogin !== null &&
+ !(yield* fileSystem.exists(localLogin).pipe(Effect.orElseSucceed(() => true)))
+ ) {
return null;
}
yield* ensureLoaded;
- const credentialKey = typeof credential === "string" ? credential : "keychain";
+ const credentialKey =
+ typeof credential === "string"
+ ? credential
+ : credential.kind === "apiKey"
+ ? // A fingerprint, so a replaced key never reads the previous account's cache.
+ `api-key:${Hex.encode(
+ yield* crypto
+ .digest("SHA-256", new TextEncoder().encode(credential.apiKey))
+ .pipe(Effect.orDie),
+ )}`
+ : "keychain";
const nowMs = yield* Clock.currentTimeMillis;
const recentFailure = failures.get(credentialKey);
let refreshing = false;
@@ -238,7 +265,13 @@ const make = Effect.gen(function* () {
});
const scan: CursorUsageAccounts["Service"]["scan"] = Effect.fn("CursorUsageAccounts.scan")(
- function* ({ keychainUsageEnabled, windowStartMs, retentionCutoffMs, awaitRefresh }) {
+ function* ({
+ instances,
+ keychainUsageEnabled,
+ windowStartMs,
+ retentionCutoffMs,
+ awaitRefresh,
+ }) {
const home = yield* HostProcess.HomeDirectory;
const userHome =
(platform === "win32" ? hostEnvironment["USERPROFILE"] : hostEnvironment["HOME"]) || home;
@@ -255,11 +288,46 @@ const make = Effect.gen(function* () {
platform === "darwin"
? path.join(userHome, ".cursor", "auth.json")
: path.join(cursorHome, platform === "win32" ? "Cursor" : "cursor", "auth.json");
+ // T3's Cursor sign-in and CURSOR_API_KEY name the account the agent uses, so they win.
+ const apiKeys = yield* Effect.forEach(instances, ({ instanceId, environment }) =>
+ environment.CURSOR_API_KEY?.trim()
+ ? Effect.succeed(environment.CURSOR_API_KEY.trim())
+ : readStoredCursorApiKey(instanceId).pipe(
+ Effect.provideService(ProviderHost.ProviderHost, host),
+ Effect.orElseSucceed(() => undefined),
+ ),
+ );
+ const uniqueApiKeys = [...new Set(apiKeys.filter((apiKey) => apiKey !== undefined))];
+ if (uniqueApiKeys.length > 0) {
+ const sources: ReadonlyArray<ProviderUsageScan | null> = yield* Effect.forEach(
+ uniqueApiKeys,
+ (apiKey) =>
+ accountSource(
+ { kind: "apiKey", apiKey },
+ authPath,
+ windowStartMs,
+ retentionCutoffMs,
+ awaitRefresh,
+ ),
+ );
+ // Keys for one account share its source, and a repeated source would count sessions twice.
+ // A failed key can hold older records, so a current read wins, then a refresh the client
+ // must follow up on.
+ const rank = (source: ProviderUsageScan) =>
+ source.status === "ok" ? 2 : source.refreshing ? 1 : 0;
+ const byAccount = new Map<string, ProviderUsageScan>();
+ for (const source of sources) {
+ if (source === null) continue;
+ const kept = byAccount.get(source.dir);
+ if (kept === undefined || rank(source) > rank(kept)) {
+ byAccount.set(source.dir, source);
+ }
+ }
+ return [...byAccount.values()];
+ }
const credentialStore = hostEnvironment["AGENT_CLI_CREDENTIAL_STORE"];
const loginUnavailable =
- Boolean(hostEnvironment["CURSOR_AUTH_TOKEN"]?.trim()) ||
- Boolean(hostEnvironment["CURSOR_API_KEY"]?.trim()) ||
- credentialStore === "memory";
+ Boolean(hostEnvironment["CURSOR_AUTH_TOKEN"]?.trim()) || credentialStore === "memory";
const useKeychain = platform === "darwin" && credentialStore !== "file";
if (useKeychain && !loginUnavailable && !keychainUsageEnabled) {
return [
diff --git a/packages/provider-cursor/src/server/accountCache.ts b/packages/provider-cursor/src/server/accountCache.ts
index bcbb1ca402b..b2ff2fbd6b3 100644
--- a/packages/provider-cursor/src/server/accountCache.ts
+++ b/packages/provider-cursor/src/server/accountCache.ts
@@ -2,7 +2,10 @@
import { cursorRateModel } from "./accountUsage.ts";
import type { UsageRecord } from "@t3tools/provider-core/server/usage";
-export type CursorCredentialSource = string | { readonly kind: "keychain" };
+export type CursorCredentialSource =
+ | string
+ | { readonly kind: "keychain" }
+ | { readonly kind: "apiKey"; readonly apiKey: string };
export const CURSOR_ACCOUNT_TTL_MS = 60 * 1000;
diff --git a/packages/provider-cursor/src/server/accountUsage.test.ts b/packages/provider-cursor/src/server/accountUsage.test.ts
index 642189484bf..211c24e0902 100644
--- a/packages/provider-cursor/src/server/accountUsage.test.ts
+++ b/packages/provider-cursor/src/server/accountUsage.test.ts
@@ -2,12 +2,14 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
+import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as FetchHttpClient from "effect/http/FetchHttpClient";
import * as HttpClient from "effect/http/HttpClient";
import * as HttpClientError from "effect/http/HttpClientError";
import * as HttpClientResponse from "effect/http/HttpClientResponse";
import * as Path from "effect/Path";
+import * as TestClock from "effect/testing/TestClock";
import * as CursorKeychain from "./CursorKeychain.ts";
import { readCursorAccountUsage } from "./accountUsage.ts";
@@ -284,6 +286,54 @@ describe("Cursor account history", () => {
});
describe("readCursorAccountUsage", () => {
+ it.effect("reads an API key's account history through Cursor's API", () =>
+ Effect.gen(function* () {
+ const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`;
+ const requests: Array<readonly [string, string | null]> = [];
+ const result = yield* readAccountUsage(
+ { kind: "apiKey", apiKey: "api-key" },
+ 0,
+ 1781000000000,
+ ({ url, headers }) => {
+ requests.push([url, headers.get("authorization")]);
+ return url.endsWith("/auth/exchange_user_api_key")
+ ? Response.json({ accessToken })
+ : Response.json({
+ totalUsageEventsCount: 1,
+ usageEventsDisplay: [
+ { timestamp: "1780000000000", model: "gpt-5", tokenUsage: { outputTokens: 4 } },
+ ],
+ });
+ },
+ );
+ assert.isNull(result.error);
+ assert.deepStrictEqual(requests, [
+ ["https://api2.cursor.sh/auth/exchange_user_api_key", "Bearer api-key"],
+ [
+ "https://api2.cursor.sh/aiserver.v1.DashboardService/GetFilteredUsageEvents",
+ `Bearer ${accessToken}`,
+ ],
+ ]);
+ assert.strictEqual(result.records[0]?.totals.outputTokens, 4);
+ }).pipe(Effect.provide(NodeServices.layer)),
+ );
+
+ it.effect("stops waiting for an API key exchange that never answers", () =>
+ Effect.gen(function* () {
+ const read = yield* Effect.forkChild(
+ readAccountUsage(
+ { kind: "apiKey", apiKey: "api-key" },
+ 0,
+ 1781000000000,
+ () => new Promise<Response>(() => {}),
+ ),
+ );
+ yield* TestClock.adjust("10 seconds");
+ const result = yield* Fiber.join(read);
+ assert.strictEqual(result.error, "Cursor account usage could not be read.");
+ }).pipe(Effect.provide(NodeServices.layer)),
+ );
+
it.effect("asks for Keychain approval when the prompt goes unanswered", () =>
Effect.gen(function* () {
const result = yield* readAccountUsage(
diff --git a/packages/provider-cursor/src/server/accountUsage.ts b/packages/provider-cursor/src/server/accountUsage.ts
index 65f1470b94c..21959a4f4de 100644
--- a/packages/provider-cursor/src/server/accountUsage.ts
+++ b/packages/provider-cursor/src/server/accountUsage.ts
@@ -13,6 +13,8 @@ import * as PlatformError from "effect/PlatformError";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
+import type { CursorCredentialSource } from "./accountCache.ts";
+import { DEFAULT_CURSOR_API_ENDPOINT, exchangeCursorApiKey } from "./apiKey.ts";
import * as CursorKeychain from "./CursorKeychain.ts";
function object(value: unknown): Record<string, unknown> {
@@ -90,7 +92,7 @@ const DASHBOARD_USAGE_URL = "https://cursor.com/api/dashboard/get-filtered-usage
const NO_REDIRECT: RequestInit = { redirect: "error" };
export const readCursorAccountUsage = Effect.fn("readCursorAccountUsage")(function* (
- credentialSource: string | { readonly kind: "keychain" },
+ credentialSource: CursorCredentialSource,
sinceMs: number,
endDate: number,
keychainToken: Effect.Effect<
@@ -120,7 +122,14 @@ export const readCursorAccountUsage = Effect.fn("readCursorAccountUsage")(functi
Effect.flatMap(decodeJson),
Effect.map((credentials) => object(credentials).accessToken),
)
- : keychainToken,
+ : credentialSource.kind === "apiKey"
+ ? exchangeCursorApiKey(credentialSource.apiKey).pipe(
+ Effect.provideService(HttpClient.HttpClient, httpClient),
+ Effect.mapError(
+ () => new CursorAccountUsageInvalidError({ reason: "Invalid API key" }),
+ ),
+ )
+ : keychainToken,
);
if (Result.isFailure(credential)) {
const cause = credential.failure;
@@ -136,9 +145,11 @@ export const readCursorAccountUsage = Effect.fn("readCursorAccountUsage")(functi
? null
: typeof credentialSource === "string"
? "Cursor credentials could not be read."
- : CursorKeychain.isCursorKeychainTimeoutError(cause)
- ? "Allow Keychain access on the Mac running T3 Code, then refresh."
- : "Cursor Keychain credentials could not be read.",
+ : credentialSource.kind === "apiKey"
+ ? "Cursor account usage could not be read."
+ : CursorKeychain.isCursorKeychainTimeoutError(cause)
+ ? "Allow Keychain access on the Mac running T3 Code, then refresh."
+ : "Cursor Keychain credentials could not be read.",
};
}
const accessToken = credential.success;
@@ -168,6 +179,21 @@ export const readCursorAccountUsage = Effect.fn("readCursorAccountUsage")(functi
accountKey = yield* accountHash(subject);
if (!Number.isFinite(sinceMs) || !Number.isFinite(endDate) || sinceMs < 0 || sinceMs > endDate)
return yield* invalid("Invalid date window");
+ // The web dashboard rejects API-key tokens; Cursor's RPC API accepts them.
+ const pageRequest =
+ typeof credentialSource !== "string" && credentialSource.kind === "apiKey"
+ ? HttpClientRequest.post(
+ `${DEFAULT_CURSOR_API_ENDPOINT}/aiserver.v1.DashboardService/GetFilteredUsageEvents`,
+ ).pipe(
+ HttpClientRequest.bearerToken(accessToken),
+ HttpClientRequest.setHeader("connect-protocol-version", "1"),
+ )
+ : HttpClientRequest.post(DASHBOARD_USAGE_URL).pipe(
+ HttpClientRequest.setHeaders({
+ Origin: "https://cursor.com",
+ Cookie: `WorkosCursorSessionToken=${encodeURIComponent(`${userId}::${accessToken}`)}`,
+ }),
+ );
const records: UsageRecord[] = [];
const occurrences = new Map<string, number>();
const pages: unknown[][] = [];
@@ -183,11 +209,7 @@ export const readCursorAccountUsage = Effect.fn("readCursorAccountUsage")(functi
}
const response = yield* httpClient
.execute(
- HttpClientRequest.post(DASHBOARD_USAGE_URL).pipe(
- HttpClientRequest.setHeaders({
- Origin: "https://cursor.com",
- Cookie: `WorkosCursorSessionToken=${encodeURIComponent(`${userId}::${accessToken}`)}`,
- }),
+ pageRequest.pipe(
HttpClientRequest.bodyText(
pageRequestBody(page, pageSize, sinceMs, endDate),
"application/json",
diff --git a/packages/provider-cursor/src/server/apiKey.ts b/packages/provider-cursor/src/server/apiKey.ts
new file mode 100644
index 00000000000..06c93e1f3bc
--- /dev/null
+++ b/packages/provider-cursor/src/server/apiKey.ts
@@ -0,0 +1,24 @@
+import * as Effect from "effect/Effect";
+import * as Schema from "effect/Schema";
+import * as HttpClient from "effect/http/HttpClient";
+import * as HttpClientRequest from "effect/http/HttpClientRequest";
+import * as HttpClientResponse from "effect/http/HttpClientResponse";
+
+export const DEFAULT_CURSOR_API_ENDPOINT = "https://api2.cursor.sh";
+
+const ApiKeyExchange = Schema.Struct({ accessToken: Schema.NonEmptyString });
+
+/** Trades a user API key for the access token Cursor's RPCs accept, as `@cursor/sdk` does. */
+export const exchangeCursorApiKey = Effect.fn("exchangeCursorApiKey")(function* (apiKey: string) {
+ const client = yield* HttpClient.HttpClient;
+ const response = yield* client.execute(
+ HttpClientRequest.post(`${DEFAULT_CURSOR_API_ENDPOINT}/auth/exchange_user_api_key`).pipe(
+ HttpClientRequest.bearerToken(apiKey),
+ HttpClientRequest.bodyJsonUnsafe({}),
+ ),
+ );
+ const { accessToken } = yield* HttpClientResponse.schemaBodyJson(ApiKeyExchange)(
+ yield* HttpClientResponse.filterStatusOk(response),
+ );
+ return accessToken;
+}, Effect.timeout("10 seconds"));
diff --git a/packages/provider-cursor/src/server/credentialStore.ts b/packages/provider-cursor/src/server/credentialStore.ts
index d0638132f1b..d995a49f0d2 100644
--- a/packages/provider-cursor/src/server/credentialStore.ts
+++ b/packages/provider-cursor/src/server/credentialStore.ts
@@ -1,5 +1,6 @@
import type { SdkCredentialStore } from "@cursor/sdk";
import { ProviderSetupError, type ProviderInstanceId } from "@t3tools/contracts";
+import * as Clock from "effect/Clock";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
@@ -90,3 +91,22 @@ export const makeCursorCredentialStore = Effect.fn("makeCursorCredentialStore")(
};
return { store, binding: credentials.binding };
});
+
+/** The unexpired API key from this instance's T3 sign-in, read without loading the SDK. */
+export const readStoredCursorApiKey = Effect.fn("readStoredCursorApiKey")(function* (
+ instanceId: ProviderInstanceId,
+) {
+ const stored = yield* (yield* (yield* ProviderHost.ProviderHost).credentials(
+ "cursor",
+ instanceId,
+ )).get;
+ if (Option.isNone(stored)) return undefined;
+ const credentials = yield* decodeCredentials(new TextDecoder().decode(stored.value)).pipe(
+ Effect.option,
+ );
+ if (Option.isNone(credentials)) return undefined;
+ const { apiKey, apiKeyExpiresAtMs } = credentials.value;
+ return apiKeyExpiresAtMs === undefined || apiKeyExpiresAtMs > (yield* Clock.currentTimeMillis)
+ ? apiKey
+ : undefined;
+});
diff --git a/packages/provider-cursor/src/server/driver.ts b/packages/provider-cursor/src/server/driver.ts
index 51c079a51cb..f797e871d3b 100644
--- a/packages/provider-cursor/src/server/driver.ts
+++ b/packages/provider-cursor/src/server/driver.ts
@@ -74,10 +74,11 @@ export const CursorDriver: ProviderDriver<
usage: {
kind: "scan",
provider: "cursor",
- scan: ({ settings, windowStartMs, retentionCutoffMs, awaitRefresh }) =>
+ scan: ({ instances, settings, windowStartMs, retentionCutoffMs, awaitRefresh }) =>
CursorUsageAccounts.CursorUsageAccounts.pipe(
Effect.flatMap((accounts) =>
accounts.scan({
+ instances,
keychainUsageEnabled: settings.cursorKeychainUsageEnabled,
windowStartMs,
retentionCutoffMs,
diff --git a/packages/provider-cursor/src/server/usageLimits.test.ts b/packages/provider-cursor/src/server/usageLimits.test.ts
index 1b4cadf88ae..617616d14bc 100644
--- a/packages/provider-cursor/src/server/usageLimits.test.ts
+++ b/packages/provider-cursor/src/server/usageLimits.test.ts
@@ -182,17 +182,46 @@ describe("Cursor usage limits", () => {
}),
);
- it.effect("does not use a stored login for an explicit API key", () =>
+ it.effect("reads an API key's own account instead of a stored login", () =>
Effect.gen(function* () {
- const limits = yield* withNodeServices(
- readCursorUsageLimits({ apiEndpoint: "" }, { CURSOR_API_KEY: "different-account" }).pipe(
- Effect.provideService(
- HttpClient.HttpClient,
- HttpClient.make(() => Effect.die("must not request usage")),
+ for (const platform of ["linux", "darwin"] as const) {
+ const requests: Array<readonly [string, string | undefined]> = [];
+ const limits = yield* withNodeServices(
+ readCursorUsageLimits({ apiEndpoint: "" }, { CURSOR_API_KEY: "api-key" }, true).pipe(
+ Effect.provideService(HostProcess.Platform, platform),
+ Effect.provideService(
+ FileSystem.FileSystem,
+ FileSystem.makeNoop({
+ readFileString: () => Effect.die("must not read a stored login"),
+ }),
+ ),
+ Effect.provideService(
+ HttpClient.HttpClient,
+ HttpClient.make((request) => {
+ requests.push([request.url, request.headers.authorization]);
+ return Effect.succeed(
+ HttpClientResponse.fromWeb(
+ request,
+ Response.json(
+ request.url.endsWith("/auth/exchange_user_api_key")
+ ? { accessToken: "api-key-access-token" }
+ : { planUsage: { totalPercentUsed: 37 } },
+ ),
+ ),
+ );
+ }),
+ ),
),
- ),
- );
- expect(limits.unavailable?.reason).toBe("unsupported");
+ );
+ expect(requests).toEqual([
+ ["https://api2.cursor.sh/auth/exchange_user_api_key", "Bearer api-key"],
+ [
+ "https://api2.cursor.sh/aiserver.v1.DashboardService/GetCurrentPeriodUsage",
+ "Bearer api-key-access-token",
+ ],
+ ]);
+ expect(limits.windows[0]?.usedPercent).toBe(37);
+ }
}),
);
@@ -246,13 +275,14 @@ describe("Cursor usage limits", () => {
}),
);
- it.effect("does not read Keychain or send its token to a custom endpoint", () =>
+ it.effect("does not send a Keychain login or API key to a custom endpoint", () =>
Effect.gen(function* () {
for (const [apiEndpoint, environment] of [
["http://localhost:3000", {}],
["", { CURSOR_API_ENDPOINT: "http://localhost:3000" }],
["https://cursor-proxy.example", {}],
["", { CURSOR_API_ENDPOINT: "https://cursor-proxy.example" }],
+ ["https://cursor-proxy.example", { CURSOR_API_KEY: "api-key" }],
] as const) {
const limits = yield* withNodeServices(
readCursorUsageLimits({ apiEndpoint }, environment, true).pipe(
diff --git a/packages/provider-cursor/src/server/usageLimits.ts b/packages/provider-cursor/src/server/usageLimits.ts
index 049e646d2c4..87fcecef4e9 100644
--- a/packages/provider-cursor/src/server/usageLimits.ts
+++ b/packages/provider-cursor/src/server/usageLimits.ts
@@ -16,10 +16,10 @@ import {
makeUnavailableUsageLimits,
makeUsageLimits,
} from "@t3tools/provider-core/server/usageLimits";
+import { DEFAULT_CURSOR_API_ENDPOINT, exchangeCursorApiKey } from "./apiKey.ts";
import * as CursorKeychain from "./CursorKeychain.ts";
const CursorCredentials = Schema.Struct({ accessToken: Schema.optional(Schema.String) });
-const DEFAULT_CURSOR_API_ENDPOINT = "https://api2.cursor.sh";
const decodeCredentials = Schema.decodeEffect(Schema.fromJsonString(CursorCredentials));
const CursorUsageResponse = Schema.Struct({
billingCycleEnd: Schema.optional(Schema.Union([Schema.String, Schema.Number])),
@@ -77,19 +77,25 @@ export const readCursorUsageLimits = Effect.fn("readCursorUsageLimits")(function
DEFAULT_CURSOR_API_ENDPOINT
).replace(/\/$/, "");
let token = environment.CURSOR_AUTH_TOKEN?.trim();
- // An explicit API key can name a different account from the stored login.
- if (!token && environment.CURSOR_API_KEY?.trim()) {
- return makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" });
- }
+ const apiKey = environment.CURSOR_API_KEY?.trim();
const credentialStore = environment.AGENT_CLI_CREDENTIAL_STORE;
- if (!token && credentialStore === "memory") {
+ // An API key can name a different account from the stored login, so read the key's own.
+ if (!token && apiKey) {
+ if (endpoint !== DEFAULT_CURSOR_API_ENDPOINT) {
+ return makeUnavailableUsageLimits({
+ checkedAt,
+ reason: "unsupported",
+ message: "Cursor usage for an API key requires the default Cursor endpoint.",
+ });
+ }
+ token = yield* exchangeCursorApiKey(apiKey);
+ } else if (!token && credentialStore === "memory") {
return makeUnavailableUsageLimits({
checkedAt,
reason: "unsupported",
message: "Cursor usage requires a CLI login or CURSOR_AUTH_TOKEN.",
});
- }
- if (!token && platform === "darwin" && credentialStore !== "file") {
+ } else if (!token && platform === "darwin" && credentialStore !== "file") {
if (!allowKeychain) {
return makeUnavailableUsageLimits({
checkedAt,