cursor 0.1.1: usage shows as magpie's built-in did — plan, period, windows and what they count, balancecursor

This commit is contained in:
yetone
2026-09-30 23:03:08 +08:00
parent f86746cd6e
commit 0f61665ff8
3 changed files with 175 additions and 2 deletions
+86 -1
View File
@@ -25,6 +25,7 @@
// OpenCode speaks chat completions to it (@ai-sdk/openai-compatible); the
// fetch here answers them.
import http2 from "node:http2"
import { STATUS_CODES } from "node:http"
import { gunzipSync } from "node:zlib"
import { createHash, randomBytes, randomUUID } from "node:crypto"
import { execFile } from "node:child_process"
@@ -318,6 +319,79 @@ async function cliSignIn() {
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
// ---- usage ------------------------------------------------------------------------
//
// How much of the plan's included usage is gone, as magpie's built-in Cursor
// account shows it (internal/provider/cursor_usage.go): the dashboard's
// current period, split into the Cursor Models and Other Models pools.
// statusText is a refused request's status as magpie says it (Go's
// http.StatusText).
const statusText = (s) =>
({ 413: "Request Entity Too Large", 414: "Request URI Too Long", 416: "Requested Range Not Satisfiable", 418: "I'm a teapot", 509: "" })[s] ?? STATUS_CODES[s] ?? ""
const POOL_VARIANT = /-(fast|none|low|medium|high|xhigh|extra-high|max|thinking)$/
// poolBase names a model's family: lower case, without cursor- and the
// effort and speed the CLI adds to it.
function poolBase(model) {
model = String(model).trim().toLowerCase()
if (model.startsWith("cursor-")) model = model.slice("cursor-".length)
for (;;) {
const b = model.replace(POOL_VARIANT, "")
if (b === model) return model
model = b
}
}
// Cursor's autoBucketModels can lag model releases: it still omitted Grok
// 4.6/4.7 when the published Cursor Models pool already included them.
// Keep those documented families alongside the server's exact model list.
// See https://cursor.com/docs/models-and-pricing.
function firstParty(model) {
if (model.startsWith("cursor-")) model = model.slice("cursor-".length)
if (model === "default" || model === "composer" || model.startsWith("composer-")) return true
return ["grok-4.5", "grok-4.6", "grok-4.7"].some((b) => model === b || model.startsWith(b + "-"))
}
// usage is the account's windows this billing period; an enterprise plan
// reports spend instead, and gets none. ids are the models it can be
// asked for, each counted by the pool Cursor bills it to.
async function usage(tok, ids) {
const res = await fetch(API + "/aiserver.v1.DashboardService/GetCurrentPeriodUsage", {
method: "POST",
headers: { Authorization: `Bearer ${tok}`, "Content-Type": "application/json", "Connect-Protocol-Version": "1" },
body: "{}",
signal: AbortSignal.timeout(15_000),
})
if (!res.ok) return { error: statusText(res.status), windows: [] }
const data = await res.json()
const u = data?.planUsage
if (!u) return { windows: [] }
const ms = /^[+-]?\d+$/.test(data.billingCycleEnd ?? "") ? Number(data.billingCycleEnd) : 0
const resets = ms > 0 ? { resetsAt: new Date(ms).toISOString() } : {}
const bucket = new Set((data.autoBucketModels ?? []).map(poolBase))
const inPool = (model) => {
model = poolBase(model)
if (model === "auto") model = "default" // the CLI's Auto is default in Cursor's API
// the server names a family (grok-4.8); the CLI asks for one at an
// effort or speed (grok-4.8-high-fast)
return bucket.has(model) || firstParty(model)
}
// Auto is always one, so the pool's list is never empty (which would
// count every model)
const pool = [...new Set(["auto", ...ids, ...(data.autoBucketModels ?? [])])].filter(inPool)
const num = (v) => (typeof v === "number" ? v : 0)
// the two pools fit the line; the total goes in its tooltip
return {
windows: [
{ name: "Cursor Models", used: num(u.autoPercentUsed), ...resets, models: pool },
{ name: "Other Models", used: num(u.apiPercentUsed), ...resets, notModels: pool },
{ name: "Total", used: num(u.totalPercentUsed), ...resets, aside: true },
],
}
}
// ---- models ----------------------------------------------------------------------
//
// Cursor lists a model once for each effort and speed it serves it at
@@ -1381,6 +1455,17 @@ export async function CursorAuthPlugin() {
{ type: "oauth", label: "cursor-agent's sign-in", authorize: cliSignIn },
{ type: "api", label: "Cursor API key (cursor.com/dashboard → Integrations)" },
],
// magpie's: how much of the plan's included usage is gone (the plan
// is the one the sign-in read)
async usage(getAuth, provider) {
let tok
try {
tok = await tokenOf(await getAuth())
} catch (e) {
return { error: e.message, windows: [] }
}
return usage(tok, Object.keys(provider?.models ?? {}))
},
},
async config(config) {
config.provider ??= {}
@@ -1414,4 +1499,4 @@ export async function CursorAuthPlugin() {
}
// for tests
export const _internal = { splitID, families, byEffort, offered, modelID, conversation, buildRun, decode, exec, fields, pb, pbValue, pbAny, frame, frames, failure, toolsOf, expiry }
export const _internal = { poolBase, splitID, families, byEffort, offered, modelID, conversation, buildRun, decode, exec, fields, pb, pbValue, pbAny, frame, frames, failure, toolsOf, expiry }
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-cursor-auth",
"version": "0.1.0",
"version": "0.1.1",
"description": "Cursor subscriptions (Pro, Pro+, Ultra, Teams) in OpenCode and magpie, through the API cursor-agent talks to",
"type": "module",
"main": "./index.mjs",
+88
View File
@@ -0,0 +1,88 @@
// auth.usage tells what magpie's built-in Cursor account shows
// (internal/provider/cursor_usage.go), against Cursor's replies as its tests
// give them (cursor_usage_test.go).
import { afterEach, expect, test } from "bun:test"
import { CursorAuthPlugin } from "./index.mjs"
const real = globalThis.fetch
afterEach(() => (globalThis.fetch = real))
// a token that runs out in an hour
const jwt = (exp) => ["e30", Buffer.from(JSON.stringify({ exp })).toString("base64url"), "sig"].join(".")
const tok = jwt(Math.floor(Date.now() / 1000) + 3600)
const auth = { type: "oauth", access: tok, refresh: "", expires: 0, accountId: "a@b.c" }
const firstParty = ["grok-4.7-xhigh-fast", "cursor-grok-4.7-high-fast", "cursor-grok-4.6-high-fast", "grok-4.5-fast-high", "auto", "default", "composer-2.5", "COMPOSER-2.5-FAST", "composer"]
const bucketed = ["future-first-party", "grok-4.8-high", "cursor-grok-4.8-xhigh-fast"]
const others = ["claude-opus-5-5", "gpt-5.6-sol", "gemini-3.1-pro", "grok-3", "grok-4.70", "grok-4.80-high", "unknown-model"]
const provider = { models: Object.fromEntries([...firstParty, ...bucketed, ...others].map((id) => [id, { id }])) }
async function run(a, reply) {
const seen = []
globalThis.fetch = async (url, init) => {
seen.push({ url: String(url), method: init.method, headers: init.headers, body: init.body })
return reply()
}
const hooks = await CursorAuthPlugin()
return { u: await hooks.auth.usage(async () => a, provider), seen }
}
// counts is whether a window counts model, as magpie reads the lists
// (internal/provider/plugin_usage.go)
function counts(w, model) {
const m = model.toLowerCase()
if (w.models?.length) return w.models.some((x) => x.toLowerCase() === m)
if (w.notModels?.length) return !w.notModels.some((x) => x.toLowerCase() === m)
return true
}
test("the period's three windows, reset at the cycle's end", async () => {
const { u, seen } = await run(auth, () =>
Response.json({ billingCycleEnd: "1792833042000", planUsage: { autoPercentUsed: 12.5, apiPercentUsed: 40, totalPercentUsed: 20 } }),
)
expect(seen).toEqual([
{
url: "https://api2.cursor.sh/aiserver.v1.DashboardService/GetCurrentPeriodUsage",
method: "POST",
headers: { Authorization: `Bearer ${tok}`, "Content-Type": "application/json", "Connect-Protocol-Version": "1" },
body: "{}",
},
])
const at = new Date(1792833042000).toISOString()
expect(u.windows.map(({ models, notModels, ...w }) => w)).toEqual([
{ name: "Cursor Models", used: 12.5, resetsAt: at },
{ name: "Other Models", used: 40, resetsAt: at },
{ name: "Total", used: 20, resetsAt: at, aside: true },
])
expect(u.error).toBeUndefined()
expect(u.plan).toBeUndefined() // the sign-in's, as magpie's
})
for (const bucket of [["default", "composer-2.5", "cursor-grok-4.5-high", "future-first-party", "Grok-4.8"], undefined]) {
test(`each model counts in the pool magpie puts it in (autoBucketModels ${bucket ? "given" : "left out"})`, async () => {
const { u } = await run(auth, () =>
Response.json({ billingCycleEnd: "1792833042000", planUsage: { autoPercentUsed: 25, apiPercentUsed: 100, totalPercentUsed: 100 }, autoBucketModels: bucket }),
)
const [cursor, other, total] = u.windows
const pool = bucket ? [...firstParty, ...bucketed] : firstParty
const rest = bucket ? others : [...others, ...bucketed]
for (const m of pool) expect([m, counts(cursor, m), counts(other, m)]).toEqual([m, true, false])
for (const m of rest) expect([m, counts(cursor, m), counts(other, m)]).toEqual([m, false, true])
expect(total.models).toBeUndefined()
expect(total.notModels).toBeUndefined()
})
}
test("an enterprise plan's spend is no window", async () => {
expect((await run(auth, () => Response.json({ spendLimitUsage: {} }))).u).toEqual({ windows: [] })
})
test("a refused token is the status magpie says", async () => {
expect((await run(auth, () => new Response("no", { status: 401 }))).u).toEqual({ error: "Unauthorized", windows: [] })
})
test("a run-out sign-in says so, and asks nothing", async () => {
const { u, seen } = await run({ ...auth, access: jwt(1) }, () => Response.json({}))
expect(u).toEqual({ error: "Cursor's sign-in has run out; sign in to Cursor again", windows: [] })
expect(seen).toEqual([])
})