Open History to see the last commit
1import * as NodeOS from "node:os";
2import type { CursorSettings, ServerProviderUsageWindow } from "@t3tools/contracts";
3import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
4import { CURSOR_USAGE_WINDOWS } from "@t3tools/shared/usageLimits";
5import * as DateTime from "effect/DateTime";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Option from "effect/Option";
9import * as Path from "effect/Path";
10import * as Schema from "effect/Schema";
11import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
12import {
13 clampPercent,
14 makeUnavailableUsageLimits,
15 makeUsageLimits,
16} from "./providerUsageLimits.ts";
17import { readMacCursorAccessToken } from "./cursorKeychainToken.ts";
18
19const CursorCredentials = Schema.Struct({ accessToken: Schema.optional(Schema.String) });
20const DEFAULT_CURSOR_API_ENDPOINT = "https://api2.cursor.sh";
21const decodeCredentials = Schema.decodeEffect(Schema.fromJsonString(CursorCredentials));
22const CursorUsageResponse = Schema.Struct({
23 billingCycleEnd: Schema.optional(Schema.Union([Schema.String, Schema.Number])),
24 planUsage: Schema.optional(
25 Schema.Struct({
26 totalPercentUsed: Schema.optional(Schema.Number),
27 autoPercentUsed: Schema.optional(Schema.Number),
28 apiPercentUsed: Schema.optional(Schema.Number),
29 }),
30 ),
31});
32
33/** Cursor's dashboard percentages include bonus usage; spend / limit does not. */
34export function cursorUsageResponseToLimits(
35 response: typeof CursorUsageResponse.Type,
36 checkedAt: string,
37) {
38 const reset = DateTime.make(Number(response.billingCycleEnd));
39 const resetsAt =
40 Number(response.billingCycleEnd) > 0 && Option.isSome(reset)
41 ? DateTime.formatIso(reset.value)
42 : undefined;
43 const windows: ServerProviderUsageWindow[] = [];
44 if (response.planUsage) {
45 for (const { id, label } of CURSOR_USAGE_WINDOWS) {
46 const usedPercent = response.planUsage[id];
47 if (usedPercent === undefined || !Number.isFinite(usedPercent)) continue;
48 windows.push({
49 id,
50 kind: "monthly",
51 label,
52 usedPercent: clampPercent(usedPercent),
53 ...(resetsAt ? { resetsAt } : {}),
54 });
55 }
56 }
57 return windows.length > 0
58 ? makeUsageLimits({ checkedAt, windows })
59 : makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" });
60}
61
62export const readCursorUsageLimits = Effect.fn("readCursorUsageLimits")(function* (
63 settings: Pick<CursorSettings, "apiEndpoint">,
64 environment: NodeJS.ProcessEnv = process.env,
65 allowKeychain = false,
66 keychainToken: () => Promise<string | null> = readMacCursorAccessToken,
67) {
68 const checkedAt = DateTime.formatIso(yield* DateTime.now);
69 return yield* Effect.gen(function* () {
70 const fs = yield* FileSystem.FileSystem;
71 const path = yield* Path.Path;
72 const platform = yield* HostProcessPlatform;
73 const endpoint = (
74 settings.apiEndpoint?.trim() ||
75 environment.CURSOR_API_ENDPOINT?.trim() ||
76 DEFAULT_CURSOR_API_ENDPOINT
77 ).replace(/\/$/, "");
78 let token = environment.CURSOR_AUTH_TOKEN?.trim();
79 // An explicit API key can name a different account from the stored login.
80 if (!token && environment.CURSOR_API_KEY?.trim()) {
81 return makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" });
82 }
83 const credentialStore = environment.AGENT_CLI_CREDENTIAL_STORE;
84 if (!token && credentialStore === "memory") {
85 return makeUnavailableUsageLimits({
86 checkedAt,
87 reason: "unsupported",
88 message: "Cursor usage requires a CLI login or CURSOR_AUTH_TOKEN.",
89 });
90 }
91 if (!token && platform === "darwin" && credentialStore !== "file") {
92 if (!allowKeychain) {
93 return makeUnavailableUsageLimits({
94 checkedAt,
95 reason: "unsupported",
96 message: "Enable Cursor account usage in T3 Code to read its Keychain login.",
97 });
98 }
99 if (endpoint !== DEFAULT_CURSOR_API_ENDPOINT) {
100 return makeUnavailableUsageLimits({
101 checkedAt,
102 reason: "unsupported",
103 message: "Cursor account usage requires the default Cursor endpoint when using Keychain.",
104 });
105 }
106 token = (yield* Effect.tryPromise(keychainToken))?.trim();
107 } else if (!token) {
108 const home =
109 (platform === "win32" ? environment.USERPROFILE : environment.HOME) || NodeOS.homedir();
110 const directory =
111 platform === "win32"
112 ? path.join(environment.APPDATA || path.join(home, "AppData", "Roaming"), "Cursor")
113 : platform === "darwin"
114 ? path.join(home, ".cursor")
115 : path.join(environment.XDG_CONFIG_HOME || path.join(home, ".config"), "cursor");
116 const credentials = yield* fs.readFileString(path.join(directory, "auth.json")).pipe(
117 Effect.catchTags({
118 PlatformError: (error) =>
119 error.reason._tag === "NotFound" ? Effect.succeed("{}") : Effect.fail(error),
120 }),
121 Effect.flatMap(decodeCredentials),
122 );
123 token = credentials.accessToken?.trim();
124 }
125 if (!token) return makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" });
126 const client = yield* HttpClient.HttpClient;
127 const response = yield* client.execute(
128 HttpClientRequest.post(`${endpoint}/aiserver.v1.DashboardService/GetCurrentPeriodUsage`).pipe(
129 HttpClientRequest.bearerToken(token),
130 HttpClientRequest.setHeaders({
131 "connect-protocol-version": "1",
132 "x-cursor-client-type": "cli",
133 }),
134 HttpClientRequest.bodyJsonUnsafe({}),
135 ),
136 );
137 const body = yield* HttpClientResponse.schemaBodyJson(CursorUsageResponse)(
138 yield* HttpClientResponse.filterStatusOk(response),
139 );
140 return cursorUsageResponseToLimits(body, checkedAt);
141 }).pipe(
142 Effect.timeout("10 seconds"),
143 Effect.orElseSucceed(() =>
144 makeUnavailableUsageLimits({
145 checkedAt,
146 reason: "probeFailed",
147 message: "Cursor could not read usage limits.",
148 }),
149 ),
150 );
151});