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

usageLimits.ts

160 lines6.3 KB

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