diff --git a/packages/cursor/README.md b/packages/cursor/README.md index ad20d0f..a858e5a 100644 --- a/packages/cursor/README.md +++ b/packages/cursor/README.md @@ -124,9 +124,19 @@ minutes), the way pi-cursor-sdk lists Cursor's catalog: and `service_tier` counting as for a listed model. The list doesn't show these ids: pick the `@` model for a window that is the model's. +## Usage + +magpie shows Cursor Models, Other Models and Total for the billing period. +Accounts with a Grok Bot allowance also show its usage and reset time; +active trials are labelled separately. A spent Bot allowance doesn't stop +Cursor requests. + +Sign in to the Cursor account linked in Grok Bot. A linked SuperGrok +subscription grants Bot access without a paid Cursor plan; see +[Grok Bot plans and billing](https://cursor.com/help/grok-bot/plans). + ## Not included -- Usage and plan limits. - Web search: Cursor's own web search is refused like its other tools. - Switching between several accounts. OpenCode keeps one sign-in per provider. diff --git a/packages/cursor/index.mjs b/packages/cursor/index.mjs index 1ad6ae8..e066c37 100644 --- a/packages/cursor/index.mjs +++ b/packages/cursor/index.mjs @@ -422,6 +422,43 @@ async function usage(tok, ids) { } } +// Grok Bot's separate allowance, using the CLI JWT as a dashboard session. +async function botUsage(tok) { + try { + const subject = JSON.parse(Buffer.from(tok.split(".")[1], "base64url").toString()).sub + if (typeof subject !== "string") return [] + const user = subject.split("|").filter(Boolean).at(-1) + if (!user || !/^[a-zA-Z0-9._-]+$/.test(user)) return [] + const res = await fetch(WEBSITE + "/api/dashboard/get-sand-usage-status", { + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "application/json", + Origin: WEBSITE, + Cookie: "WorkosCursorSessionToken=" + encodeURIComponent(user + "::" + tok), + }, + body: "{}", + redirect: "error", + signal: AbortSignal.timeout(5_000), + }) + if (!res.ok) return [] + const data = await res.json() + const paid = typeof data?.includedLimitZero === "boolean" + ? !data.includedLimitZero : data?.hasNonZeroIncludedLimit === true + const trial = !paid && typeof data?.sandTrialExpiresAt === "string" && Date.parse(data.sandTrialExpiresAt) > Date.now() + if ((!paid && !trial) || typeof data?.usagePercent !== "number" || !Number.isFinite(data.usagePercent)) return [] + const reset = paid && typeof data.nextResetTimestampUtc === "string" ? Date.parse(data.nextResetTimestampUtc) : NaN + return [{ + name: trial ? "Grok Bot (trial)" : "Grok Bot", + used: Math.max(0, Math.min(100, data.usagePercent)), + aside: true, // Bot exhaustion must not stop Cursor model requests. + ...(Number.isFinite(reset) ? { resetsAt: new Date(reset).toISOString(), span: 604800 } : {}), + }] + } catch { + return [] + } +} + // ---- models ---------------------------------------------------------------------- // // The list is Cursor's model picker (AiService/AvailableModels, asked as the @@ -2158,8 +2195,10 @@ export async function CursorAuthPlugin() { } catch (e) { return { error: e.message, windows: [], signIn: "kept" } } - const [u, plan] = await Promise.all([usage(tok, Object.keys(provider?.models ?? {})), planOf(tok)]) - return { ...u, ...(plan ? { plan } : {}), signIn: "kept" } + const [u, plan, bot] = await Promise.all([usage(tok, Object.keys(provider?.models ?? {})), planOf(tok), botUsage(tok)]) + // Put Bot before Total for magpie's three menu-bar rings. + const windows = [...u.windows.filter((w) => !w.aside), ...bot, ...u.windows.filter((w) => w.aside)] + return { ...u, windows, ...(plan ? { plan } : {}), signIn: "kept" } }, }, // the session the request is part of, for the conversation_id diff --git a/packages/cursor/package.json b/packages/cursor/package.json index ac282c4..dcadb4d 100644 --- a/packages/cursor/package.json +++ b/packages/cursor/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-cursor-auth", - "version": "0.2.4", + "version": "0.2.5", "description": "Cursor subscriptions (Pro, Pro+, Ultra, Teams) in OpenCode and magpie, through the API cursor-agent talks to", "type": "module", "main": "./index.mjs", diff --git a/packages/cursor/usage.test.mjs b/packages/cursor/usage.test.mjs index e2b8420..bb99860 100644 --- a/packages/cursor/usage.test.mjs +++ b/packages/cursor/usage.test.mjs @@ -24,8 +24,13 @@ const provider = { models: Object.fromEntries([...firstParty, ...bucketed, ...ot 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(String(url)) + seen.push({ url: String(url), method: init.method, headers: init.headers, body: init.body, ...(init.redirect ? { redirect: init.redirect } : {}) }) + const res = await reply(String(url)) + if (String(url) === BOT && res.status === 307 && res.headers.has("Location")) { + if (init.redirect === "error") throw new TypeError("redirect refused") + return Response.json(paidBot) + } + return res } const hooks = await CursorAuthPlugin() return { u: await hooks.auth.usage(async () => a, provider), seen } @@ -156,3 +161,56 @@ test("a model list Cursor couldn't give fails, not shrinks to the configured few const configured = { models: { auto: { id: "auto" } } } await expect(hooks.provider.models(configured, { auth: fresh() })).rejects.toThrow() }) + +const BOT = "https://cursor.com/api/dashboard/get-sand-usage-status" +const botAuth = () => ({ ...fresh(), access: ["e30", Buffer.from(JSON.stringify({ sub: "auth0|user_test", exp: Math.floor(Date.now() / 1000) + 7200 + ++n })).toString("base64url"), "sig"].join(".") }) +const reset = "2030-01-08T00:00:00.000Z" +const paidBot = { includedLimitZero: false, usagePercent: 42, nextResetTimestampUtc: reset } +const period = { planUsage: { autoPercentUsed: 12, apiPercentUsed: 34, totalPercentUsed: 20 } } +const botRun = (data, monthly = period, account = botAuth()) => run(account, (url) => { + if (url === PLAN) return Response.json({}) + if (url === BOT) { + if (data instanceof Error) throw data + return data instanceof Response ? data : Response.json(data) + } + return Response.json(monthly) +}) + +test("Bot uses the dashboard session and appears before Total without gating Cursor models", async () => { + const a = botAuth() + const { u, seen } = await botRun(paidBot, period, a) + expect(u.windows.map((w) => w.name)).toEqual(["Cursor Models", "Other Models", "Grok Bot", "Total"]) + expect(u.windows[2]).toEqual({ name: "Grok Bot", used: 42, aside: true, resetsAt: reset, span: 604800 }) + expect(seen.find((r) => r.url === BOT)).toMatchObject({ method: "POST", body: "{}", headers: { Cookie: "WorkosCursorSessionToken=" + encodeURIComponent("user_test::" + a.access) } }) +}) + +test("Bot grants work without Cursor monthly usage, with current or legacy allowance flags", async () => { + expect((await botRun({ ...paidBot, hasNonZeroIncludedLimit: false }, {})).u.windows).toEqual([ + { name: "Grok Bot", used: 42, aside: true, resetsAt: reset, span: 604800 }, + ]) + expect((await botRun({ hasNonZeroIncludedLimit: true, usagePercent: 0 }, {})).u.windows).toEqual([{ name: "Grok Bot", used: 0, aside: true }]) +}) + +test("an exhausted trial stays visible, without treating expiry as a reset", async () => { + const trial = { includedLimitZero: true, sandTrialExpiresAt: "2099-01-01T00:00:00Z", usagePercent: 100, nextResetTimestampUtc: reset } + expect((await botRun(trial)).u.windows[2]).toEqual({ name: "Grok Bot (trial)", used: 100, aside: true }) + expect((await botRun({ ...trial, sandTrialExpiresAt: "2000-01-01T00:00:00Z" })).u.windows.map((w) => w.name)).toEqual(["Cursor Models", "Other Models", "Total"]) +}) + +test("absent or failed Bot readings preserve Cursor usage and sign-in", async () => { + const normal = (await run(fresh(), (url) => Response.json(url === PLAN ? {} : period))).u + for (const data of [null, {}, { ...paidBot, includedLimitZero: true, hasNonZeroIncludedLimit: true }, { ...paidBot, usagePercent: null }, new Response("", { status: 403 }), new Response("not JSON"), new Error("network unavailable")]) + expect((await botRun(data)).u).toEqual(normal) +}) + +test("Bot usage is clamped", async () => { + for (const [usagePercent, used] of [[130, 100], [-5, 0]]) + expect((await botRun({ ...paidBot, usagePercent })).u.windows[2]).toEqual({ name: "Grok Bot", used, aside: true, resetsAt: reset, span: 604800 }) +}) + +test("Bot login redirects are refused", async () => { + const normal = (await run(botAuth(), (url) => Response.json(url === PLAN ? {} : period))).u + const { u, seen } = await botRun(new Response(null, { status: 307, headers: { Location: "https://cursor.com/login?returnTo=dashboard" } })) + expect(u).toEqual(normal) + expect(seen.find((r) => r.url === BOT)).toMatchObject({ redirect: "error" }) +}) diff --git a/packages/grok/README.md b/packages/grok/README.md index c358f88..f6887d0 100644 --- a/packages/grok/README.md +++ b/packages/grok/README.md @@ -87,3 +87,7 @@ read 0% used while its requests come back 429. After a 429 the card shows a spent "Rate limit" window until the reset it named (`Retry-After`, or a `*ratelimit*reset*` header). When it named none, the window stays until a request goes through, or for 5 minutes. + +Grok Bot's separate allowance is shown by the [Cursor plugin](../cursor/README.md#usage). +Sign in there with the Cursor account linked in Grok Bot, including for +access through SuperGrok.