cursor 0.1.3: the card names the plan as cursor-agent about does (GetPlanInfo's planName, kept an hour); only a token or session run out is a 401, as magpie marks the account lapsed on one; errors no longer start with "Cursor: ", which magpie adds; a model list Cursor couldn't give fails instead of shrinking to the configured few
This commit is contained in:
+41
-19
@@ -207,6 +207,23 @@ async function whoIs(tok) {
|
||||
}
|
||||
}
|
||||
|
||||
// plans are the plan each token's account is on, as `cursor-agent about`
|
||||
// names it (GetPlanInfo's planName, magpie's card title), asked again after
|
||||
// an hour.
|
||||
const plans = new Map()
|
||||
const PLAN_TTL = 3600_000
|
||||
async function planOf(tok) {
|
||||
const had = plans.get(tok)
|
||||
if (had && Date.now() - had.at < PLAN_TTL) return had.plan
|
||||
try {
|
||||
const plan = String((await unary(API, "aiserver.v1.DashboardService/GetPlanInfo", tok))?.planInfo?.planName ?? "").trim()
|
||||
if (plan) plans.set(tok, { plan, at: Date.now() })
|
||||
return plan || had?.plan || ""
|
||||
} catch {
|
||||
return had?.plan ?? ""
|
||||
}
|
||||
}
|
||||
|
||||
// exchanged are API keys' tokens, by the key's hash.
|
||||
const exchanged = new Map()
|
||||
|
||||
@@ -222,9 +239,9 @@ async function keyToken(key) {
|
||||
body: "{}",
|
||||
signal: AbortSignal.timeout(15_000),
|
||||
}).catch((e) => {
|
||||
throw Object.assign(new Error("Cursor: couldn't reach the API: " + e.message), { status: 502 })
|
||||
throw Object.assign(new Error("couldn't reach Cursor's API: " + e.message), { status: 502 })
|
||||
})
|
||||
if (res.status >= 500) throw Object.assign(new Error(`Cursor: exchange_user_api_key: HTTP ${res.status}`), { status: 502 })
|
||||
if (res.status >= 500) throw Object.assign(new Error(`exchange_user_api_key: HTTP ${res.status}`), { status: 502 })
|
||||
const j = res.ok ? await res.json().catch(() => null) : null
|
||||
if (!j?.accessToken) throw new AuthError("Cursor didn't take this API key")
|
||||
exchanged.set(h, { tok: j.accessToken, exp: expiry(j.accessToken) })
|
||||
@@ -830,15 +847,21 @@ function failure(status, text) {
|
||||
return statusOf(status, f.code ?? "", msg)
|
||||
}
|
||||
|
||||
// signInExpired is a message of a token or session run out; a trial, a
|
||||
// plan or a link run out is no lapsed sign-in, and magpie marks the
|
||||
// account lapsed on a 401.
|
||||
const signInExpired = (low) => low.includes("expired") && /token|session|sign[- ]?in|log[- ]?in|auth|credential/.test(low)
|
||||
|
||||
// statusOf is the status and words for Cursor's error of this code and
|
||||
// message. A region the team isn't served in says so, not to sign in.
|
||||
function statusOf(status, code, msg) {
|
||||
msg ||= `HTTP ${status}`
|
||||
const low = msg.toLowerCase()
|
||||
const out = (status, message) => ({ status, message: "Cursor: " + message })
|
||||
// magpie names the provider before the message itself
|
||||
const out = (status, message) => ({ status, message })
|
||||
if (regional(msg)) return out(403, msg + " — Cursor serves your team only in some regions and turned this request away; signing in again won't change that")
|
||||
if (code === "permission_denied") return out(403, msg)
|
||||
if (code === "unauthenticated" || status === 401 || low.includes("expired")) return out(401, msg + " — sign in to Cursor again")
|
||||
if (code === "unauthenticated" || status === 401 || signInExpired(low)) return out(401, msg + " — sign in to Cursor again")
|
||||
if (code === "resource_exhausted" || low.includes("quota") || low.includes("rate limit") || low.includes("usage limit"))
|
||||
return out(429, "usage limit reached: " + msg)
|
||||
if (low.includes("too long") || low.includes("context length") || low.includes("too many tokens"))
|
||||
@@ -1077,7 +1100,7 @@ function open(base, headers, signal) {
|
||||
if (done) return
|
||||
done = true
|
||||
session.destroy()
|
||||
resolve({ error: { status: 502, message: "Cursor: " + (e?.message ?? String(e)) } })
|
||||
resolve({ error: { status: 502, message: e?.message ?? String(e) } })
|
||||
}
|
||||
session.on("error", fail)
|
||||
const req = session.request({
|
||||
@@ -1152,7 +1175,7 @@ async function runOnce({ tok, base, id, tools, conv, signal }) {
|
||||
// an error comes before anything of the answer: out of quota, a model the
|
||||
// plan doesn't have — answered with its own status
|
||||
const head = await wrapped.next()
|
||||
if (head.done) return { error: { status: 502, message: "Cursor: an empty reply" } }
|
||||
if (head.done) return { error: { status: 502, message: "an empty reply" } }
|
||||
if (head.value.error) {
|
||||
await wrapped.return()
|
||||
return { error: head.value.error }
|
||||
@@ -1192,7 +1215,7 @@ async function* decode(stream, { send, blobs, tools, estimate }) {
|
||||
if (f.end) {
|
||||
const e = failure(200, f.data)
|
||||
if (e.status < 200 || e.status > 299) yield { error: e }
|
||||
else if (said === 0 && calls === 0) yield { error: { status: 502, message: "Cursor: an empty reply" } }
|
||||
else if (said === 0 && calls === 0) yield { error: { status: 502, message: "an empty reply" } }
|
||||
else yield finish()
|
||||
return
|
||||
}
|
||||
@@ -1275,13 +1298,13 @@ async function* decode(stream, { send, blobs, tools, estimate }) {
|
||||
yield finish()
|
||||
return
|
||||
}
|
||||
yield { error: { status: 502, message: "Cursor: the reply broke off: EOF" } }
|
||||
yield { error: { status: 502, message: "the reply broke off: EOF" } }
|
||||
} catch (e) {
|
||||
if (calls > 0 && /EOF/.test(e?.message ?? "")) {
|
||||
yield finish()
|
||||
return
|
||||
}
|
||||
yield { error: { status: 502, message: "Cursor: the reply broke off: " + (e?.message ?? e) } }
|
||||
yield { error: { status: 502, message: "the reply broke off: " + (e?.message ?? e) } }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1347,7 +1370,7 @@ async function answer(auth, chat, signal) {
|
||||
try {
|
||||
tok = await tokenOf(auth)
|
||||
} catch (e) {
|
||||
return errorResponse({ status: e.status ?? 401, message: e.message.startsWith("Cursor") ? e.message : "Cursor: " + e.message })
|
||||
return errorResponse({ status: e.status ?? 401, message: e.message })
|
||||
}
|
||||
const model = String(chat.model ?? "")
|
||||
let raw = []
|
||||
@@ -1439,13 +1462,13 @@ export async function CursorAuthPlugin() {
|
||||
async fetch(input, init = {}) {
|
||||
const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url
|
||||
if (!/\/chat\/completions$/.test(new URL(url).pathname))
|
||||
return errorResponse({ status: 404, message: "Cursor: only chat completions are served" })
|
||||
return errorResponse({ status: 404, message: "only chat completions are served" })
|
||||
let chat
|
||||
try {
|
||||
const b = init.body ?? (input instanceof Request ? await input.clone().text() : undefined)
|
||||
chat = JSON.parse(typeof b === "string" ? b : new TextDecoder().decode(b))
|
||||
} catch {
|
||||
return errorResponse({ status: 400, message: "Cursor: a request that isn't JSON" })
|
||||
return errorResponse({ status: 400, message: "a request that isn't JSON" })
|
||||
}
|
||||
return answer((await getAuth()) ?? auth, chat, init.signal ?? (input instanceof Request ? input.signal : undefined))
|
||||
},
|
||||
@@ -1465,7 +1488,8 @@ export async function CursorAuthPlugin() {
|
||||
} catch (e) {
|
||||
return { error: e.message, windows: [] }
|
||||
}
|
||||
return usage(tok, Object.keys(provider?.models ?? {}))
|
||||
const [u, plan] = await Promise.all([usage(tok, Object.keys(provider?.models ?? {})), planOf(tok)])
|
||||
return plan ? { ...u, plan } : u
|
||||
},
|
||||
},
|
||||
async config(config) {
|
||||
@@ -1488,12 +1512,10 @@ export async function CursorAuthPlugin() {
|
||||
id: ID,
|
||||
async models(provider, { auth } = {}) {
|
||||
if (!auth) return provider.models
|
||||
try {
|
||||
const tok = await tokenOf(auth)
|
||||
return Object.fromEntries(offered(await usable(tok)).map((m) => [m.id, runtimeModel(m)]))
|
||||
} catch {
|
||||
return provider.models
|
||||
}
|
||||
// a list Cursor couldn't give is a failure, not the few models
|
||||
// configured: magpie keeps the list it had
|
||||
const tok = await tokenOf(auth)
|
||||
return Object.fromEntries(offered(await usable(tok)).map((m) => [m.id, runtimeModel(m)]))
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-cursor-auth",
|
||||
"version": "0.1.2",
|
||||
"version": "0.1.3",
|
||||
"description": "Cursor subscriptions (Pro, Pro+, Ultra, Teams) in OpenCode and magpie, through the API cursor-agent talks to",
|
||||
"type": "module",
|
||||
"main": "./index.mjs",
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// (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"
|
||||
import { CursorAuthPlugin, _internal } from "./index.mjs"
|
||||
|
||||
const real = globalThis.fetch
|
||||
afterEach(() => (globalThis.fetch = real))
|
||||
@@ -11,6 +11,9 @@ afterEach(() => (globalThis.fetch = real))
|
||||
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" }
|
||||
// a sign-in of its own, so no plan asked before is remembered for it
|
||||
let n = 0
|
||||
const fresh = () => ({ ...auth, access: jwt(Math.floor(Date.now() / 1000) + 7200 + ++n) })
|
||||
|
||||
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"]
|
||||
@@ -21,7 +24,7 @@ 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()
|
||||
return reply(String(url))
|
||||
}
|
||||
const hooks = await CursorAuthPlugin()
|
||||
return { u: await hooks.auth.usage(async () => a, provider), seen }
|
||||
@@ -36,18 +39,21 @@ function counts(w, model) {
|
||||
return true
|
||||
}
|
||||
|
||||
const PERIOD = "https://api2.cursor.sh/aiserver.v1.DashboardService/GetCurrentPeriodUsage"
|
||||
const PLAN = "https://api2.cursor.sh/aiserver.v1.DashboardService/GetPlanInfo"
|
||||
|
||||
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 } }),
|
||||
const { u, seen } = await run(auth, (url) =>
|
||||
url === PLAN
|
||||
? Response.json({ planInfo: { planName: "Pro" } })
|
||||
: 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: "{}",
|
||||
},
|
||||
])
|
||||
expect(seen.find((r) => r.url === PERIOD)).toEqual({
|
||||
url: PERIOD,
|
||||
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 },
|
||||
@@ -55,7 +61,27 @@ test("the period's three windows, reset at the cycle's end", async () => {
|
||||
{ name: "Total", used: 20, resetsAt: at, aside: true },
|
||||
])
|
||||
expect(u.error).toBeUndefined()
|
||||
expect(u.plan).toBeUndefined() // the sign-in's, as magpie's
|
||||
})
|
||||
|
||||
test("the card names the plan as cursor-agent about does (GetPlanInfo's planName), asked once an hour", async () => {
|
||||
const a = fresh()
|
||||
const reply = (url) =>
|
||||
url === PLAN ? Response.json({ planInfo: { planName: "Pro+" } }) : Response.json({ planUsage: { autoPercentUsed: 1, apiPercentUsed: 2, totalPercentUsed: 3 } })
|
||||
const first = await run(a, reply)
|
||||
expect(first.u.plan).toBe("Pro+")
|
||||
const plan = first.seen.find((r) => r.url === PLAN)
|
||||
expect(plan.method).toBe("POST")
|
||||
expect(plan.headers.Authorization).toBe(`Bearer ${a.access}`)
|
||||
const again = await run(a, reply)
|
||||
expect(again.u.plan).toBe("Pro+")
|
||||
expect(again.seen.map((r) => r.url)).toEqual([PERIOD])
|
||||
})
|
||||
|
||||
test("a plan Cursor doesn't say leaves the card's plan out", async () => {
|
||||
const a = fresh()
|
||||
const { u } = await run(a, (url) => (url === PLAN ? new Response("no", { status: 500 }) : Response.json({ planUsage: { autoPercentUsed: 1 } })))
|
||||
expect(u.plan).toBeUndefined()
|
||||
expect(u.windows.length).toBe(3)
|
||||
})
|
||||
|
||||
for (const bucket of [["default", "composer-2.5", "cursor-grok-4.5-high", "future-first-party", "Grok-4.8"], undefined]) {
|
||||
@@ -74,11 +100,11 @@ for (const bucket of [["default", "composer-2.5", "cursor-grok-4.5-high", "futur
|
||||
}
|
||||
|
||||
test("an enterprise plan's spend is no window", async () => {
|
||||
expect((await run(auth, () => Response.json({ spendLimitUsage: {} }))).u).toEqual({ windows: [] })
|
||||
expect((await run(fresh(), () => 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: [] })
|
||||
expect((await run(fresh(), () => new Response("no", { status: 401 }))).u).toEqual({ error: "Unauthorized", windows: [] })
|
||||
})
|
||||
|
||||
test("a run-out sign-in says so, and asks nothing", async () => {
|
||||
@@ -86,3 +112,27 @@ test("a run-out sign-in says so, and asks nothing", async () => {
|
||||
expect(u).toEqual({ error: "Cursor's sign-in has run out; sign in to Cursor again", windows: [] })
|
||||
expect(seen).toEqual([])
|
||||
})
|
||||
|
||||
// magpie marks a plugin's account lapsed on any 401, so only a sign-in
|
||||
// that is gone says 401
|
||||
test("an expired token is a lapsed sign-in; an expired trial is not", () => {
|
||||
const { failure } = _internal
|
||||
const says = (msg) => failure(400, JSON.stringify({ code: "failed_precondition", message: msg }))
|
||||
expect(says("Your access token has expired").status).toBe(401)
|
||||
expect(says("Session expired, please log in again").status).toBe(401)
|
||||
expect(says("Your free trial has expired").status).toBe(502)
|
||||
expect(says("This link has expired").status).toBe(502)
|
||||
})
|
||||
|
||||
// the gateway names the provider before a plugin's error
|
||||
test("an error doesn't name Cursor again", () => {
|
||||
const f = _internal.failure(429, JSON.stringify({ code: "resource_exhausted", message: "slow down" }))
|
||||
expect(f).toEqual({ status: 429, message: "usage limit reached: slow down" })
|
||||
})
|
||||
|
||||
test("a model list Cursor couldn't give fails, not shrinks to the configured few", async () => {
|
||||
globalThis.fetch = async () => new Response("down", { status: 503 })
|
||||
const hooks = await CursorAuthPlugin()
|
||||
const configured = { models: { auto: { id: "auto" } } }
|
||||
await expect(hooks.provider.models(configured, { auth: fresh() })).rejects.toThrow()
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user