From 6a86762e26d3ff8e42d928c913a78f9c16da711e Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 29 Oct 2026 16:29:48 +0800 Subject: [PATCH] cursor 0.2.31: Included usage only, a plugin option that stops an account once its included pools are used up (#485) A new magpie plugin option, included_only ("Included usage only", off by default), read through input.magpie.option at each usage reading, so a change needs no restart. Modelled on Factory's standard_only (#349). On: Cursor Models and Other Models drive routing (they lose `aside`), and On-demand (fixed or unlimited) and Total are shown with `aside`, so a team member whose on-demand could still pay is no longer kept in routing once an included pool is used up. The Enterprise path does the same: the Enterprise allowance stops the account and On-demand is shown only. Off, or outside magpie, or an option that throws or isn't `true`: the windows are exactly as 0.2.30 gives them. Tests (included-only.test.mjs, new): Team accounts with a member's own fixed limit, an org-wide fixed pool and unlimited on-demand, each with the pools spent, left, and only Cursor Models spent, read with the switch off and on; a fixed budget spent stops either way; no on-demand allowed is unchanged; the switch flipped on one plugin instance between readings; input missing/throwing/non-true; Enterprise unlimited and fixed-with-room; the option's declaration fits host.js's limits (label 60, description 300). Run on mote (mote-run): - HOME=$(mktemp -d) bun test packages/cursor: 344 pass, 0 fail, 20 files - bun scripts/check.mjs: ok Broken by hand (each in mote's copy, included-only + usage tests): - pools keep `aside` with the switch on: 8 fail - fixed On-demand not set aside: 2 fail - Enterprise allowance ignores the switch: 2 fail - Enterprise fixed On-demand not set aside: 1 fail - switch always on: 23 fail - switch read once at plugin start: 1 fail - a truthy non-true value taken as on: 1 fail - option declared under another key: 1 fail Not tried: a real Cursor Team account with the switch on in magpie (none with on-demand here); the dashboard replies are fixtures shaped as usage.test.mjs's. The option label is English only, as every plugin's options are (magpie shows auth.options' label as given). --- packages/cursor/README.md | 15 ++ packages/cursor/included-only.test.mjs | 183 +++++++++++++++++++++++++ packages/cursor/index.mjs | 53 +++++-- packages/cursor/package.json | 2 +- 4 files changed, 241 insertions(+), 12 deletions(-) create mode 100644 packages/cursor/included-only.test.mjs diff --git a/packages/cursor/README.md b/packages/cursor/README.md index b3cbe54..b84e624 100644 --- a/packages/cursor/README.md +++ b/packages/cursor/README.md @@ -265,6 +265,21 @@ reaching its included allowance doesn't count the account as used up. On-demand also shows the team's spend when known, with its limit when it has one. A reached on-demand limit counts the account as used up. +### Included usage only (optional) + +In magpie, open the Cursor provider, turn on **Included usage only** under +**Plugin options**, and save (or set `"pluginOptions": {"cursor": +{"included_only": true}}` in magpie's settings.json). It is off by default, +applies to every Cursor account, and takes effect at each account's next +usage reading. + +When on, Cursor Models and Other Models (an Enterprise account's allowance) +are what keep an account in routing: once one is used up, magpie moves its +models to the next account until the period resets, even when on-demand +could still pay for them. On-demand and Total are still shown but never +keep an account in routing. Use it when on-demand is a shared or paid pool +you don't want spent. When off, on-demand works as described above. + 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). diff --git a/packages/cursor/included-only.test.mjs b/packages/cursor/included-only.test.mjs new file mode 100644 index 0000000..99d4eff --- /dev/null +++ b/packages/cursor/included-only.test.mjs @@ -0,0 +1,183 @@ +// magpie-community/plugins#485: "Included usage only", magpie's plugin +// option (off by default). On, the included pools (Cursor Models and Other +// Models; an Enterprise account's allowance) are what stops an account, and +// On-demand and Total are shown only. Off, on-demand that can still pay keeps +// a spent account in routing, as before. The replies are dashboard fixtures +// shaped as usage.test.mjs's (GetCurrentPeriodUsage, GetHardLimit, +// usage-summary), not a real account driven past its limit. +import "./nonet.mjs" // first: no request leaves this machine +import { afterEach, expect, test } from "bun:test" +import { CursorAuthPlugin } from "./index.mjs" + +const real = globalThis.fetch +afterEach(() => (globalThis.fetch = real)) + +let n = 0 +// a sign-in of its own, so nothing asked for another is remembered for it +const fresh = () => ({ + type: "oauth", + access: ["e30", Buffer.from(JSON.stringify({ sub: "auth0|user_included" + ++n, exp: Math.floor(Date.now() / 1000) + 7200 + n })).toString("base64url"), "sig"].join("."), + refresh: "", + expires: 0, + accountId: "a@b.c", +}) + +const PERIOD = "https://api2.cursor.sh/aiserver.v1.DashboardService/GetCurrentPeriodUsage" +const HARD = "https://api2.cursor.sh/aiserver.v1.DashboardService/GetHardLimit" +const SUMMARY = "https://cursor.com/api/usage-summary" +const BOT = "https://cursor.com/api/dashboard/get-sand-usage-status" + +const provider = { models: Object.fromEntries(["auto", "composer-2.5", "claude-opus-5-5", "gpt-5.6-sol"].map((id) => [id, { id }])) } +const CURSOR = "composer-2.5" // in the Cursor Models pool +const OTHER = "claude-opus-5-5" // in Other Models + +// magpie (input.magpie) with the user's option as it stands now +const magpieWith = (box) => ({ magpie: { option: (p, key) => (p === "cursor" && key === "included_only" ? box.on : undefined) } }) + +const reply = ({ period, hard, summary }) => async (url) => { + url = String(url) + if (url === PERIOD) return Response.json(period) + if (url === HARD) return hard instanceof Response ? hard : Response.json(hard ?? {}) + if (url === SUMMARY) return Response.json(summary ?? {}) + if (url === BOT) return new Response("no", { status: 404 }) + return Response.json({}) +} + +async function read(hooks, replies) { + globalThis.fetch = reply(replies) + const a = fresh() + return (await hooks.auth.usage(async () => a, provider)).windows +} +async function readWith(on, replies) { + return read(await CursorAuthPlugin(magpieWith({ on })), replies) +} + +// counts and stops are how magpie reads the windows +// (internal/provider/plugin_usage.go): a window not aside and used up stops +// each model it counts +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 +} +const stops = (windows, model) => windows.some((w) => !w.aside && w.used >= 100 && counts(w, model)) +const byName = (windows) => Object.fromEntries(windows.map((w) => [w.name, w])) + +const pools = (auto, api) => ({ billingCycleEnd: "1792833042000", planUsage: { autoPercentUsed: auto, apiPercentUsed: api, totalPercentUsed: Math.max(auto, api) } }) +// a Team member's own on-demand limit, $500, $123.45 of it spent +const fixedOwn = { totalSpend: 52000, individualLimit: 50000, individualUsed: 12345, individualRemaining: 37655, limitType: "team", pooledLimit: "0" } +// a Team's org-wide pool (magpie #1868's shape), with room +const fixedPool = { totalSpend: 6334270, pooledLimit: "45120000", pooledUsed: 6334270, pooledRemaining: "38785730", individualUsed: 19855, limitType: "team" } +// a Team member with no limit of their own and no pool: unlimited +const unlimited = { individualUsed: 900, limitType: "team" } +const budgets = [ + ["a fixed on-demand limit of the member's", fixedOwn, {}], + ["a fixed org-wide on-demand pool", fixedPool, { hardLimit: 451200 }], + ["unlimited on-demand", unlimited, { hardLimit: 2000, perUserMonthlyLimitDollars: 0 }], +] + +for (const [what, spendLimitUsage, hard] of budgets) { + test(`Team, ${what}, included pools spent: off keeps the account in routing, on stops it`, async () => { + const replies = { period: { ...pools(100, 100), spendLimitUsage }, hard } + const off = await readWith(false, replies) + expect(off.filter((w) => w.name === "Cursor Models" || w.name === "Other Models").every((w) => w.aside)).toBe(true) + expect(stops(off, CURSOR)).toBe(false) + expect(stops(off, OTHER)).toBe(false) + + const on = await readWith(true, replies) + const w = byName(on) + expect(w["Cursor Models"].aside).toBeUndefined() + expect(w["Other Models"].aside).toBeUndefined() + // On-demand and Total are still on the card, shown only + expect(w["On-demand"]).toBeDefined() + expect(w["On-demand"].aside).toBe(true) + expect(w["Total"].aside).toBe(true) + expect(stops(on, CURSOR)).toBe(true) + expect(stops(on, OTHER)).toBe(true) + // the card reads the same either way, only what routes differs + const strip = (ws) => ws.map(({ aside, ...x }) => x) + expect(strip(on)).toEqual(strip(off)) + }) + + test(`Team, ${what}, included pools left: on or off, the account stays in routing`, async () => { + const replies = { period: { ...pools(40, 70), spendLimitUsage }, hard } + for (const on of [false, true]) { + const ws = await readWith(on, replies) + expect([on, stops(ws, CURSOR), stops(ws, OTHER)]).toEqual([on, false, false]) + expect(byName(ws)["On-demand"]).toBeDefined() + } + }) + + test(`Team, ${what}, only Cursor Models spent: on stops Cursor's models, not the others`, async () => { + const replies = { period: { ...pools(100, 30), spendLimitUsage }, hard } + const on = await readWith(true, replies) + expect(stops(on, CURSOR)).toBe(true) + expect(stops(on, "auto")).toBe(true) + expect(stops(on, OTHER)).toBe(false) + const off = await readWith(false, replies) + expect(stops(off, CURSOR)).toBe(false) + }) +} + +test("a fixed on-demand budget spent with the pools: off and on both stop the account", async () => { + const replies = { period: { ...pools(100, 100), spendLimitUsage: { ...fixedOwn, individualUsed: 50000, individualRemaining: 0 } }, hard: {} } + for (const on of [false, true]) expect([on, stops(await readWith(on, replies), OTHER)]).toEqual([on, true]) +}) + +test("no on-demand allowed: on changes nothing", async () => { + const replies = { period: { ...pools(100, 100), spendLimitUsage: { individualLimit: 0, individualUsed: 0, limitType: "team" } }, hard: { hardLimit: 2000 } } + expect(await readWith(true, replies)).toEqual(await readWith(false, replies)) +}) + +test("the switch is read at each usage reading: a change needs no restart", async () => { + const box = { on: false } + const hooks = await CursorAuthPlugin(magpieWith(box)) + const replies = { period: { ...pools(100, 100), spendLimitUsage: fixedOwn }, hard: {} } + expect(stops(await read(hooks, replies), OTHER)).toBe(false) + box.on = true + expect(stops(await read(hooks, replies), OTHER)).toBe(true) + box.on = false + expect(stops(await read(hooks, replies), OTHER)).toBe(false) +}) + +test("outside magpie, or a switch that can't be read, is off", async () => { + const replies = { period: { ...pools(100, 100), spendLimitUsage: unlimited }, hard: { hardLimit: 2000 } } + for (const input of [undefined, {}, { magpie: {} }, { magpie: { option: () => "true" } }, { magpie: { option: () => { throw new Error("gone") } } }]) { + const ws = await read(await CursorAuthPlugin(input), replies) + expect(stops(ws, OTHER)).toBe(false) + } +}) + +const enterprise = (onDemand, used) => ({ + billingCycleEnd: "2026-11-01T00:00:00.000Z", + membershipType: "enterprise", + limitType: "team", + individualUsage: { overall: { enabled: true, used, limit: 80000 } }, + teamUsage: { onDemand }, +}) + +for (const [what, od] of [["unlimited", { enabled: true, used: 12345, limit: null }], ["a fixed budget with room", { enabled: true, used: 100, limit: 50000 }]]) { + test(`Enterprise, ${what} on-demand: on makes the spent allowance stop the account`, async () => { + const replies = { period: { spendLimitUsage: {} }, summary: enterprise(od, 80000) } + expect(stops(await readWith(false, replies), OTHER)).toBe(false) + const on = await readWith(true, replies) + expect(byName(on)["Enterprise"].aside).toBeUndefined() + expect(byName(on)["On-demand"].aside).toBe(true) + expect(stops(on, OTHER)).toBe(true) + // with room in the allowance, on stops nothing + expect(stops(await readWith(true, { ...replies, summary: enterprise(od, 4000) }), OTHER)).toBe(false) + }) +} + +test("the switch is declared for magpie's provider editor, off by default", async () => { + const hooks = await CursorAuthPlugin() + const o = hooks.auth.options.find((x) => x.key === "included_only") + expect(o).toBeDefined() + expect(o.default).toBeUndefined() + expect(o.label).toBe("Included usage only") + // magpie shows at most 60 and 300 characters (host.js optionsOf) + expect(o.label.length).toBeLessThanOrEqual(60) + expect(o.description.length).toBeLessThanOrEqual(300) + expect(/^[a-z0-9_-]{1,40}$/.test(o.key)).toBe(true) +}) diff --git a/packages/cursor/index.mjs b/packages/cursor/index.mjs index 6d6c339..929fb47 100644 --- a/packages/cursor/index.mjs +++ b/packages/cursor/index.mjs @@ -532,13 +532,21 @@ async function hardLimit(tok) { // dollars, thousands grouped: a team's pool runs to six figures ($451,200.00) const dollars = (n) => "$" + n.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 }) +// INCLUDED_ONLY is the switch (magpie's plugin options, off by default) +// that keeps an account in routing only while its included usage lasts +// (magpie-community/plugins#485): on, the included pools (Cursor Models and +// Other Models; an Enterprise account's allowance) are what stops it, and +// On-demand and Total are shown only, a budget with room or none at all +// keeping nothing in routing. Off, on-demand that can still pay keeps it. +const INCLUDED_ONLY = "included_only" + // enterpriseUsage is the allowance GetCurrentPeriodUsage leaves out on an // Enterprise account. That call answers with only the billing cycle there; // the website's usage-summary has individualUsage.overall, in cents, and // the account's membership. The CLI JWT is also the website's dashboard // session, as botUsage builds it. undefined when the summary says nothing // this can show, so a failed read stays an empty card, as before. -async function enterpriseUsage(tok) { +async function enterpriseUsage(tok, includedOnly = false) { try { const subject = JSON.parse(Buffer.from(tok.split(".")[1], "base64url").toString()).sub if (typeof subject !== "string") return undefined @@ -569,8 +577,9 @@ async function enterpriseUsage(tok) { const unlimited = od?.enabled === true && od.limit === null const fixed = od?.enabled === true && typeof od.limit === "number" && Number.isFinite(od.limit) && od.limit > 0 && spent // Only an explicitly unlimited budget or a measured budget with room - // lets a spent included allowance stay available to magpie's routing. - const aside = unlimited || (fixed && od.used < od.limit) + // lets a spent included allowance stay available to magpie's routing, + // and neither does with INCLUDED_ONLY on. + const aside = !includedOnly && (unlimited || (fixed && od.used < od.limit)) const windows = [{ name: "Enterprise", used: Math.max(0, Math.min(100, (100 * used) / limit)), @@ -589,6 +598,7 @@ async function enterpriseUsage(tok) { limit: od.limit / 100, unit: "USD", ...resets, + ...(includedOnly ? { aside: true } : {}), }) else if (unlimited && spent) windows.push({ name: "On-demand", used: 0, display: dollars(od.used / 100), ...resets, aside: true }) return windows @@ -603,9 +613,11 @@ async function enterpriseUsage(tok) { // Discord: a team that pays for more) is still served when the pools are // spent, so they are shown aside, and its On-demand spend is what can run // out: at its limit (a team member with none of their own: the team's -// pool), or never when it has none. An Enterprise account's period has no -// planUsage; its allowance comes from usage-summary instead. -async function usage(tok, ids) { +// pool), or never when it has none. With includedOnly (INCLUDED_ONLY on) +// the pools are the allowance whatever on-demand allows, and On-demand is +// shown only. An Enterprise account's period has no planUsage; its +// allowance comes from usage-summary instead. +async function usage(tok, ids, includedOnly = false) { const [res, hard] = await Promise.all([ fetch(API + "/aiserver.v1.DashboardService/GetCurrentPeriodUsage", { method: "POST", @@ -620,7 +632,7 @@ async function usage(tok, ids) { const u = data?.planUsage if (!u) { // Prefer measured Enterprise usage before any reset-date-only fallback. - const windows = await enterpriseUsage(tok) + const windows = await enterpriseUsage(tok, includedOnly) return windows ? { windows } : { windows: [] } } const ms = /^[+-]?\d+$/.test(data.billingCycleEnd ?? "") ? Number(data.billingCycleEnd) : 0 @@ -642,10 +654,10 @@ async function usage(tok, ids) { const pool = [...new Set(["auto", ...asked, ...(data.autoBucketModels ?? [])])].filter(inPool) const num = (v) => (typeof v === "number" ? v : 0) const od = onDemandOf(data, hard) - const pooled = od.kind === "fixed" || od.kind === "unlimited" ? { aside: true } : {} + const pooled = !includedOnly && (od.kind === "fixed" || od.kind === "unlimited") ? { aside: true } : {} const onDemand = od.kind === "fixed" - ? [{ name: "On-demand", used: Math.max(0, Math.min(100, (100 * od.usedDollars) / od.limitDollars)), display: `${dollars(od.usedDollars)} / ${dollars(od.limitDollars)}` + (od.mineDollars === undefined ? "" : ` (you: ${dollars(od.mineDollars)})`), ...resets }] + ? [{ name: "On-demand", used: Math.max(0, Math.min(100, (100 * od.usedDollars) / od.limitDollars)), display: `${dollars(od.usedDollars)} / ${dollars(od.limitDollars)}` + (od.mineDollars === undefined ? "" : ` (you: ${dollars(od.mineDollars)})`), ...resets, ...(includedOnly ? { aside: true } : {}) }] : od.kind === "unlimited" ? [{ name: "On-demand", used: 0, display: dollars(od.usedDollars), ...resets, aside: true }] : [] @@ -3172,7 +3184,16 @@ async function answerOf(auth, chat, signal, session = "") { // ---- the plugin --------------------------------------------------------------------------- -export async function CursorAuthPlugin() { +export async function CursorAuthPlugin(input) { + // includedOnly is the user's INCLUDED_ONLY as magpie has it now, read at + // each usage reading so a change needs no restart; false outside magpie + const includedOnly = () => { + try { + return input?.magpie?.option?.(ID, INCLUDED_ONLY) === true + } catch { + return false + } + } return { auth: { provider: ID, @@ -3205,6 +3226,16 @@ 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 own switches (input.magpie.option), read at each usage + // reading + options: [ + { + key: INCLUDED_ONLY, + label: "Included usage only", + description: + "Keeps an account in routing only while its included usage lasts: once Cursor Models or Other Models is used up, magpie moves those models to the next account until the period resets, even if on-demand could pay. On-demand and Total are still shown but never keep an account in routing.", + }, + ], // magpie's: how much of the plan's included usage is gone (the plan // is the one the sign-in read). The built-in's read, clean or not, // neither marked the account nor cleared it. @@ -3215,7 +3246,7 @@ export async function CursorAuthPlugin() { } catch (e) { return { error: e.message, windows: [], signIn: "kept" } } - const [u, plan, bot] = await Promise.all([usage(tok, Object.keys(provider?.models ?? {})), planOf(tok), botUsage(tok)]) + const [u, plan, bot] = await Promise.all([usage(tok, Object.keys(provider?.models ?? {}), includedOnly()), planOf(tok), botUsage(tok)]) // Bot goes among magpie's three menu-bar rings: before Total, and // before an On-demand with no limit, which is only a dollar figure on // a ring that never fills (magpie #2213, Morganwan90). An On-demand diff --git a/packages/cursor/package.json b/packages/cursor/package.json index ec152fb..bcec12d 100644 --- a/packages/cursor/package.json +++ b/packages/cursor/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-cursor-auth", - "version": "0.2.30", + "version": "0.2.31", "description": "Cursor subscriptions (Pro, Pro+, Ultra, Teams) in OpenCode and magpie, through the API cursor-agent talks to", "type": "module", "main": "./index.mjs",