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