@caph42/pi-cursor-provider 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/usage.ts ADDED
@@ -0,0 +1,257 @@
1
+ /**
2
+ * Cursor billing-period usage, as magpie's account card reads it.
3
+ *
4
+ * Ported from magpie's Cursor provider (MIT):
5
+ * https://github.com/magpie-community/plugins/tree/main/packages/cursor
6
+ * Plan lookup uses the shared Connect client. Period, hard limit, and Grok
7
+ * Bot stay on their own fetches so a refused dashboard call is a report,
8
+ * not a thrown request.
9
+ */
10
+ import { STATUS_CODES } from "node:http"
11
+ import { API, unary } from "./client.ts"
12
+
13
+ export const WEBSITE = "https://cursor.com"
14
+
15
+ const PLAN_TTL = 3600_000
16
+ const plans = new Map<string, { plan: string; at: number }>()
17
+
18
+ export type UsageWindow = {
19
+ name: string
20
+ used: number
21
+ resetsAt?: string
22
+ display?: string
23
+ aside?: boolean
24
+ models?: string[]
25
+ notModels?: string[]
26
+ span?: number
27
+ }
28
+
29
+ export type UsageReport = { plan?: string; windows: UsageWindow[]; error?: string }
30
+
31
+ export type OnDemandKind = "fixed" | "unlimited" | "disabled" | "unavailable"
32
+
33
+ export type OnDemand = {
34
+ kind: OnDemandKind
35
+ usedDollars: number
36
+ limitDollars?: number
37
+ mineDollars?: number
38
+ }
39
+
40
+ type Spend = {
41
+ individualUsed?: number
42
+ individualLimit?: number
43
+ limitType?: string
44
+ pooledLimit?: string | number
45
+ pooledUsed?: number
46
+ }
47
+
48
+ type Period = {
49
+ billingCycleEnd?: string
50
+ planUsage?: { autoPercentUsed?: number; apiPercentUsed?: number; totalPercentUsed?: number }
51
+ autoBucketModels?: string[]
52
+ spendLimitUsage?: Spend
53
+ }
54
+
55
+ type HardLimit = { hardLimit?: number; noUsageBasedAllowed?: boolean }
56
+
57
+ const statusText = (s: number) =>
58
+ ({ 413: "Request Entity Too Large", 414: "Request URI Too Long", 416: "Requested Range Not Satisfiable", 418: "I'm a teapot", 509: "" })[s] ??
59
+ STATUS_CODES[s] ??
60
+ ""
61
+
62
+ const POOL_VARIANT = /-(fast|none|low|medium|high|xhigh|extra-high|max|thinking)$/
63
+
64
+ function poolBase(model: string) {
65
+ model = String(model).trim().toLowerCase().replace(/@[^@]*$/, "")
66
+ if (model.startsWith("cursor-")) model = model.slice("cursor-".length)
67
+ for (;;) {
68
+ const b = model.replace(POOL_VARIANT, "")
69
+ if (b === model) return model
70
+ model = b
71
+ }
72
+ }
73
+
74
+ function firstParty(model: string) {
75
+ model = model.replace(/@[^@]*$/, "")
76
+ if (model.startsWith("cursor-")) model = model.slice("cursor-".length)
77
+ if (model === "default" || model === "composer" || model.startsWith("composer-")) return true
78
+ return ["grok-4.5", "grok-4.6", "grok-4.7"].some((b) => model === b || model.startsWith(b + "-"))
79
+ }
80
+
81
+ /** What Cursor still serves after included usage is spent. */
82
+ export function onDemandOf(data: { spendLimitUsage?: Spend } | undefined, hard: HardLimit | undefined): OnDemand {
83
+ const s = data?.spendLimitUsage
84
+ const usedDollars = Number(s?.individualUsed ?? 0) / 100
85
+ const own =
86
+ s?.individualLimit === undefined
87
+ ? undefined
88
+ : Number(s.individualLimit) > 0
89
+ ? { kind: "fixed" as const, usedDollars, limitDollars: Number(s.individualLimit) / 100 }
90
+ : { kind: "disabled" as const, usedDollars }
91
+ if (s?.limitType === "team") {
92
+ if (own) return own
93
+ if (hard && (hard.noUsageBasedAllowed || !(Number(hard.hardLimit) > 0))) return { kind: "disabled", usedDollars }
94
+ const pool = Number(s.pooledLimit ?? 0)
95
+ if (pool > 0) return { kind: "fixed", usedDollars: Number(s.pooledUsed ?? 0) / 100, limitDollars: pool / 100, mineDollars: usedDollars }
96
+ return hard ? { kind: "unlimited", usedDollars } : { kind: "unavailable", usedDollars }
97
+ }
98
+ if (!hard) return own ?? { kind: "unavailable", usedDollars }
99
+ if (hard.noUsageBasedAllowed) return { kind: "disabled", usedDollars }
100
+ const limit = Number(hard.hardLimit ?? 0)
101
+ if (limit >= 2147483647) return { kind: "unlimited", usedDollars }
102
+ return limit > 0 ? { kind: "fixed", usedDollars, limitDollars: limit } : { kind: "disabled", usedDollars }
103
+ }
104
+
105
+ async function hardLimit(tok: string): Promise<HardLimit | undefined> {
106
+ try {
107
+ const res = await fetch(API + "/aiserver.v1.DashboardService/GetHardLimit", {
108
+ method: "POST",
109
+ headers: { Authorization: `Bearer ${tok}`, "Content-Type": "application/json", "Connect-Protocol-Version": "1" },
110
+ body: "{}",
111
+ signal: AbortSignal.timeout(15_000),
112
+ })
113
+ return res.ok ? ((await res.json()) ?? undefined) : undefined
114
+ } catch {
115
+ return undefined
116
+ }
117
+ }
118
+
119
+ const dollars = (n: number) => "$" + n.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })
120
+
121
+ async function periodUsage(tok: string, ids: string[]): Promise<UsageReport> {
122
+ const [res, hard] = await Promise.all([
123
+ fetch(API + "/aiserver.v1.DashboardService/GetCurrentPeriodUsage", {
124
+ method: "POST",
125
+ headers: { Authorization: `Bearer ${tok}`, "Content-Type": "application/json", "Connect-Protocol-Version": "1" },
126
+ body: "{}",
127
+ signal: AbortSignal.timeout(15_000),
128
+ }),
129
+ hardLimit(tok),
130
+ ])
131
+ if (!res.ok) return { error: statusText(res.status), windows: [] }
132
+ const data = (await res.json()) as Period
133
+ const u = data?.planUsage
134
+ if (!u) return { windows: [] }
135
+ const ms = /^[+-]?\d+$/.test(data.billingCycleEnd ?? "") ? Number(data.billingCycleEnd) : 0
136
+ const resets = ms > 0 ? { resetsAt: new Date(ms).toISOString() } : {}
137
+ const bucket = new Set((data.autoBucketModels ?? []).map(poolBase))
138
+ const inPool = (model: string) => {
139
+ model = poolBase(model)
140
+ if (model === "auto") model = "default"
141
+ return bucket.has(model) || firstParty(model)
142
+ }
143
+ const asked = ids.flatMap((id) => [id, id.replace(/@[^@]*$/, "")])
144
+ const pool = [...new Set(["auto", ...asked, ...(data.autoBucketModels ?? [])])].filter(inPool)
145
+ const num = (v: unknown) => (typeof v === "number" ? v : 0)
146
+ const od = onDemandOf(data, hard)
147
+ const pooled = od.kind === "fixed" || od.kind === "unlimited" ? { aside: true } : {}
148
+ const onDemand: UsageWindow[] =
149
+ od.kind === "fixed" && od.limitDollars
150
+ ? [
151
+ {
152
+ name: "On-demand",
153
+ used: Math.max(0, Math.min(100, (100 * od.usedDollars) / od.limitDollars)),
154
+ display: `${dollars(od.usedDollars)} / ${dollars(od.limitDollars)}` + (od.mineDollars === undefined ? "" : ` (you: ${dollars(od.mineDollars)})`),
155
+ ...resets,
156
+ },
157
+ ]
158
+ : od.kind === "unlimited"
159
+ ? [{ name: "On-demand", used: 0, display: dollars(od.usedDollars), ...resets, aside: true }]
160
+ : []
161
+ return {
162
+ windows: [
163
+ { name: "Cursor Models", used: num(u.autoPercentUsed), ...resets, models: pool, ...pooled },
164
+ { name: "Other Models", used: num(u.apiPercentUsed), ...resets, notModels: pool, ...pooled },
165
+ ...onDemand,
166
+ { name: "Total", used: num(u.totalPercentUsed), ...resets, aside: true },
167
+ ],
168
+ }
169
+ }
170
+
171
+ async function planOf(tok: string): Promise<string> {
172
+ const had = plans.get(tok)
173
+ if (had && Date.now() - had.at < PLAN_TTL) return had.plan
174
+ try {
175
+ const body = await unary(API, "aiserver.v1.DashboardService/GetPlanInfo", tok)
176
+ const plan = String(body?.planInfo?.planName ?? "").trim()
177
+ if (plan) plans.set(tok, { plan, at: Date.now() })
178
+ return plan || had?.plan || ""
179
+ } catch {
180
+ return had?.plan ?? ""
181
+ }
182
+ }
183
+
184
+ async function botUsage(tok: string): Promise<UsageWindow[]> {
185
+ try {
186
+ const subject = JSON.parse(Buffer.from(tok.split(".")[1] ?? "", "base64url").toString()).sub
187
+ if (typeof subject !== "string") return []
188
+ const user = subject.split("|").filter(Boolean).at(-1)
189
+ if (!user || !/^[a-zA-Z0-9._-]+$/.test(user)) return []
190
+ const res = await fetch(WEBSITE + "/api/dashboard/get-sand-usage-status", {
191
+ method: "POST",
192
+ headers: {
193
+ "Content-Type": "application/json",
194
+ Accept: "application/json",
195
+ Origin: WEBSITE,
196
+ Cookie: "WorkosCursorSessionToken=" + encodeURIComponent(user + "::" + tok),
197
+ },
198
+ body: "{}",
199
+ redirect: "error",
200
+ signal: AbortSignal.timeout(5_000),
201
+ })
202
+ if (!res.ok) return []
203
+ const data = (await res.json()) as {
204
+ includedLimitZero?: boolean
205
+ hasNonZeroIncludedLimit?: boolean
206
+ sandTrialExpiresAt?: string
207
+ usagePercent?: number
208
+ nextResetTimestampUtc?: string
209
+ }
210
+ const paid = typeof data?.includedLimitZero === "boolean" ? !data.includedLimitZero : data?.hasNonZeroIncludedLimit === true
211
+ const trial = !paid && typeof data?.sandTrialExpiresAt === "string" && Date.parse(data.sandTrialExpiresAt) > Date.now()
212
+ if ((!paid && !trial) || typeof data?.usagePercent !== "number" || !Number.isFinite(data.usagePercent)) return []
213
+ const reset = paid && typeof data.nextResetTimestampUtc === "string" ? Date.parse(data.nextResetTimestampUtc) : NaN
214
+ return [
215
+ {
216
+ name: trial ? "Grok Bot (trial)" : "Grok Bot",
217
+ used: Math.max(0, Math.min(100, data.usagePercent)),
218
+ aside: true,
219
+ ...(Number.isFinite(reset) ? { resetsAt: new Date(reset).toISOString(), span: 604800 } : {}),
220
+ },
221
+ ]
222
+ } catch {
223
+ return []
224
+ }
225
+ }
226
+
227
+ /** Plan name plus the billing-period windows. GetPlanInfo is cached for about an hour per token. */
228
+ export async function fetchUsage(tok: string, modelIds: string[]): Promise<UsageReport> {
229
+ const [u, plan, bot] = await Promise.all([periodUsage(tok, modelIds), planOf(tok), botUsage(tok)])
230
+ const last = (w: UsageWindow) => w.name === "Total" || (w.name === "On-demand" && w.aside)
231
+ const windows = [...u.windows.filter((w) => !last(w)), ...bot, ...u.windows.filter(last)]
232
+ return { ...u, windows, ...(plan ? { plan } : {}) }
233
+ }
234
+
235
+ function percent(n: number) {
236
+ if (!Number.isFinite(n)) return "0%"
237
+ return `${Math.round(n * 100) / 100}%`
238
+ }
239
+
240
+ /** Text for `/cursor.usage`. */
241
+ export function formatUsage(report: UsageReport): string {
242
+ if (report.error && report.windows.length === 0 && !report.plan) return report.error
243
+ const lines: string[] = []
244
+ if (report.plan) lines.push(`Plan: ${report.plan}`)
245
+ for (const w of report.windows) {
246
+ const body = w.display ?? percent(w.used)
247
+ const reset = w.resetsAt ? ` (resets ${w.resetsAt})` : ""
248
+ lines.push(`${w.name}: ${body}${reset}`)
249
+ }
250
+ if (report.error) lines.push(report.error)
251
+ if (!lines.length) return "No Cursor usage was reported."
252
+ return lines.join("\n")
253
+ }
254
+
255
+ export function clearPlanCache() {
256
+ plans.clear()
257
+ }