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

usageLimits.ts

107 lines3.9 KB

1import type { ServerProviderUsageWindow } from "@t3tools/contracts";
2import type { CursorSettings } from "../settings.ts";
3import { CURSOR_USAGE_WINDOWS } from "@t3tools/shared/usageLimits";
4import * as DateTime from "effect/DateTime";
5import * as Effect from "effect/Effect";
6import * as Option from "effect/Option";
7import * as Schema from "effect/Schema";
8import * as HttpClient from "effect/http/HttpClient";
9import * as HttpClientRequest from "effect/http/HttpClientRequest";
10import * as HttpClientResponse from "effect/http/HttpClientResponse";
11import {
12 clampPercent,
13 makeUnavailableUsageLimits,
14 makeUsageLimits,
15} from "@t3tools/provider-core/server/usageLimits";
16import { DEFAULT_CURSOR_API_ENDPOINT, exchangeCursorApiKey } from "./apiKey.ts";
17​
18const CursorUsageResponse = Schema.Struct({
19 billingCycleEnd: Schema.optional(Schema.Union([Schema.String, Schema.Number])),
20 planUsage: Schema.optional(
21 Schema.Struct({
22 totalPercentUsed: Schema.optional(Schema.Number),
23 autoPercentUsed: Schema.optional(Schema.Number),
24 apiPercentUsed: Schema.optional(Schema.Number),
25 }),
26 ),
27});
28​
29/** Cursor's dashboard percentages include bonus usage; spend / limit does not. */
30export function cursorUsageResponseToLimits(
31 response: typeof CursorUsageResponse.Type,
32 checkedAt: string,
33) {
34 const reset = DateTime.make(Number(response.billingCycleEnd));
35 const resetsAt =
36 Number(response.billingCycleEnd) > 0 && Option.isSome(reset)
37 ? DateTime.formatIso(reset.value)
38 : undefined;
39 const windows: ServerProviderUsageWindow[] = [];
40 if (response.planUsage) {
41 for (const { id, label } of CURSOR_USAGE_WINDOWS) {
42 const usedPercent = response.planUsage[id];
43 if (usedPercent === undefined || !Number.isFinite(usedPercent)) continue;
44 windows.push({
45 id,
46 kind: "monthly",
47 label,
48 usedPercent: clampPercent(usedPercent),
49 ...(resetsAt ? { resetsAt } : {}),
50 });
51 }
52 }
53 return windows.length > 0
54 ? makeUsageLimits({ checkedAt, windows })
55 : makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" });
57​
58export const readCursorUsageLimits = Effect.fn("readCursorUsageLimits")(function* (
59 settings: Pick<CursorSettings, "apiEndpoint">,
60 environment: NodeJS.ProcessEnv = process.env,
61) {
62 const checkedAt = DateTime.formatIso(yield* DateTime.now);
63 return yield* Effect.gen(function* () {
64 const endpoint = (
65 settings.apiEndpoint?.trim() ||
66 environment.CURSOR_API_ENDPOINT?.trim() ||
67 DEFAULT_CURSOR_API_ENDPOINT
68 ).replace(/\/$/, "");
69 let token = environment.CURSOR_AUTH_TOKEN?.trim();
70 const apiKey = environment.CURSOR_API_KEY?.trim();
71 if (!token && apiKey) {
72 if (endpoint !== DEFAULT_CURSOR_API_ENDPOINT) {
73 return makeUnavailableUsageLimits({
74 checkedAt,
75 reason: "unsupported",
76 message: "Cursor usage for an API key requires the default Cursor endpoint.",
77 });
78 }
79 token = yield* exchangeCursorApiKey(apiKey);
80 }
81 if (!token) return makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" });
82 const client = yield* HttpClient.HttpClient;
83 const response = yield* client.execute(
84 HttpClientRequest.post(`${endpoint}/aiserver.v1.DashboardService/GetCurrentPeriodUsage`).pipe(
85 HttpClientRequest.bearerToken(token),
86 HttpClientRequest.setHeaders({
87 "connect-protocol-version": "1",
88 "x-cursor-client-type": "cli",
89 }),
90 HttpClientRequest.bodyJsonUnsafe({}),
91 ),
92 );
93 const body = yield* HttpClientResponse.schemaBodyJson(CursorUsageResponse)(
94 yield* HttpClientResponse.filterStatusOk(response),
95 );
96 return cursorUsageResponseToLimits(body, checkedAt);
97 }).pipe(
98 Effect.timeout("10 seconds"),
99 Effect.orElseSucceed(() =>
100 makeUnavailableUsageLimits({
101 checkedAt,
102 reason: "probeFailed",
103 message: "Cursor could not read usage limits.",
104 }),
105 ),
106 );
107});