Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

cursorUsageLimits.ts

140 lines5.3 KB

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