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

usageLimits.ts

152 lines6.0 KB

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