From 00de68a0f86cc3f558042a1ad4557e566cfac3ab Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 31 Oct 2026 04:46:49 +0800 Subject: [PATCH] cursor 0.2.33: free credit (the plan's bonus and credit grants) on the card, with its limits MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CryptoSarom on X (2116260605053321489): "magpie 似乎没法支持 cursor 的赠金读取, 以及赠金使用限制". The card read only the included pools and on-demand. What Cursor exposes, as Cursor 3.x's IDE (workbench.desktop.main.js) and cursor-agent 2026.10.01's schemas have it: - GetCurrentPeriodUsage planUsage.bonusSpend (cents), remainingBonus (bool, no amount) and bonusTooltip: the IDE's "+$X free usage on us" line. - DashboardService/GetUsageLimitStatusAndActiveGrants activeGrants (aiserver.v1.ActiveCreditGrant): totalCents, remainingCents, expiresAtMs, allowedModelIds / allowedModelTags / allowedModelSelections (models it may be spent on), allowedClientTypes ("glass" without "ide" is the IDE's Cloud Agent credits), campaignName. The IDE's "Use your $X free credits" banner reads it; it matches tags lower case with "-" as ".". The card now shows Free usage (bonus spent, "more left" when remainingBonus) and a window per grant (spent / total USD, runsOutAt and runsOut at its expiry, models when limited, "(Cloud Agents only)" when cursor-agent can't spend it). All are aside. Routing: a bonus with some left, or a grant magpie can spend on every model, sets the spent pools aside as on-demand does; a model-limited grant leaves its models out of a spent pool (Cursor Models keeps a non-empty list, or goes aside). With Included usage only on, none of this keeps an account served. A grants read that fails leaves the card as before. Run on mote at this tree: HOME=$(mktemp -d) bun test: 3960 pass, 9 skip, 1 fail (a test of my own, since fixed); then credit/usage/included-only 79 pass 0 fail; bun scripts/check.mjs cursor ok. Broken by hand: the new credit.test.mjs against the old index.mjs, 9 of 9 red. Real account (Premium, merged weekly, cursor-agent's sign-in, read only): GetCurrentPeriodUsage, GetUsageLimitStatusAndActiveGrants, GetCreditGrantsBalance, GetClientVisibleCreditGrants read; it has no bonus and no grant, and the new plugin's card for it is unchanged (Weekly, Grok Bot, On-demand). Those replies are credit.test.mjs's REAL_ fixtures; the #1868 team account's real bonusSpend 14151 now shows "+$141.51 on us". Not tried: a real account with a grant or remainingBonus true (none at hand), so the grant fixtures follow the schema, and whether Cursor really serves a spent pool on bonus is Cursor's word ("free usage beyond what you've purchased"), not a request made past a spent pool. --- packages/cursor/README.md | 13 +++ packages/cursor/credit.test.mjs | 160 ++++++++++++++++++++++++++++++++ packages/cursor/index.mjs | 134 +++++++++++++++++++++++--- packages/cursor/package.json | 2 +- packages/cursor/usage.test.mjs | 2 + 5 files changed, 299 insertions(+), 12 deletions(-) create mode 100644 packages/cursor/credit.test.mjs diff --git a/packages/cursor/README.md b/packages/cursor/README.md index c2e447b..27e28be 100644 --- a/packages/cursor/README.md +++ b/packages/cursor/README.md @@ -259,6 +259,19 @@ own spends the team's pool: On-demand shows the pool's spend and limit, with the member's own spend beside it, and the account is used up when the pool is. +Free credit shows too, as Cursor's own IDE reads it. The plan's bonus +("+$X free usage on us", `GetCurrentPeriodUsage`'s `bonusSpend` and +`remainingBonus`) is Free usage: what was spent from it this period, and +whether more is left; Cursor gives no amount for it. Each credit grant +(`GetUsageLimitStatusAndActiveGrants`' `activeGrants`, the IDE's "Use your +$X free credits") is a window of its own, named by its campaign: spent of +total, when it expires, and its limits. A grant limited to some models +lists them; one only Cursor's Cloud Agents (or another client) may spend +says so in its name, since magpie talks as `cursor-agent`. While a bonus +or a grant magpie can spend has some left, a spent included pool doesn't +count the account used up for the models it pays for. With "Included +usage only" on, free credit is shown only. + An Enterprise account's period has no Cursor Models, Other Models or Total in `GetCurrentPeriodUsage`: Cursor reports its overall allowance through the website's `usage-summary` instead. Magpie shows that as Enterprise, diff --git a/packages/cursor/credit.test.mjs b/packages/cursor/credit.test.mjs new file mode 100644 index 0000000..61b9965 --- /dev/null +++ b/packages/cursor/credit.test.mjs @@ -0,0 +1,160 @@ +// Cursor's free credit (CryptoSarom on X: "magpie 似乎没法支持 cursor 的赠金 +// 读取, 以及赠金使用限制"), as Cursor 3.x's IDE reads it: +// GetCurrentPeriodUsage's planUsage.bonusSpend / remainingBonus / +// bonusTooltip (its "+$X free usage on us" line) and +// DashboardService/GetUsageLimitStatusAndActiveGrants' activeGrants (its +// "Use your $X free … credits" banner), whose allowedModelIds, +// allowedModelTags and allowedClientTypes say what a grant may be spent on. +// +// The plan replies are real bytes: REAL_PERIOD and REAL_GRANTS are a +// Premium (merged, weekly) account's GetCurrentPeriodUsage and +// GetUsageLimitStatusAndActiveGrants, read 2026-10-31 (autoBucketModels +// shortened), and the #1868 team account's planUsage has a bonusSpend. +// No account at hand had a grant, so the grant replies are Connect JSON of +// aiserver.v1.ActiveCreditGrant as the IDE's and cursor-agent 2026.10.01's +// schemas declare it (int64 fields as strings, as REAL_GRANTS' cents are). +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 +const fresh = () => ({ + type: "oauth", + access: ["e30", Buffer.from(JSON.stringify({ sub: "auth0|user_credit" + ++n, exp: Math.floor(Date.now() / 1000) + 7200 + n })).toString("base64url"), "sig"].join("."), + refresh: "", + expires: 0, + accountId: "a@b.c", +}) + +const DASH = "https://api2.cursor.sh/aiserver.v1.DashboardService/" +const PERIOD = DASH + "GetCurrentPeriodUsage" +const PLAN = DASH + "GetPlanInfo" +const HARD = DASH + "GetHardLimit" +const GRANTS = DASH + "GetUsageLimitStatusAndActiveGrants" + +const REAL_PERIOD = {"billingCycleStart":"1793078412396","billingCycleEnd":"1793683212396","planUsage":{"remainingBonus":false,"bonusTooltip":"We work with model providers to give you free usage beyond what you've purchased. Amounts may vary.","autoPercentUsed":7.042253521126761,"apiPercentUsed":0,"totalPercentUsed":7.042253521126761},"spendLimitUsage":{"limitType":"user"},"displayThreshold":200,"enabled":true,"displayMessage":"You've used 7% of your included usage","autoModelSelectedDisplayMessage":"You've used 7% of your included total usage","namedModelSelectedDisplayMessage":"You've used 0% of your included API usage","autoBucketModels":["default","composer-2","composer-2.5","grok-4.7"]} +const REAL_PLAN = {"planInfo":{"planName":"Premium","price":"","billingCycleEnd":"1794547141340","includedUsagePeriod":"INCLUDED_USAGE_PERIOD_WEEKLY","includedUsageResetsAt":"1793683212396"},"isMerged":true} +const REAL_GRANTS = {"usageLimitPolicyStatus":{"canConfigureSpendLimit":true,"canAdjustOnDemand":true,"recommendedOnDemandLimitCents":"10000","onDemandMinCents":"5000","onDemandMaxCents":"20000","creditRequestButtonHidden":false}} + +const provider = { models: Object.fromEntries(["auto", "composer-2.5", "claude-opus-5-5@300k", "claude-opus-5-5@1m", "gpt-5.6-sol"].map((id) => [id, { id }])) } +const at = new Date(1793683212396).toISOString() +const later = Date.now() + 5 * 86400_000 + +async function read(r, on = false) { + const seen = [] + globalThis.fetch = async (url, init) => { + url = String(url) + seen.push({ url, headers: init.headers, body: init.body }) + if (url === PERIOD) return Response.json(r.period) + if (url === PLAN) return Response.json(r.plan ?? {}) + if (url === HARD) return Response.json(r.hard ?? { hardLimit: 0 }) + if (url === GRANTS) return r.grants instanceof Response ? r.grants : Response.json(r.grants ?? REAL_GRANTS) + return new Response("no", { status: 404 }) + } + const hooks = await CursorAuthPlugin({ magpie: { option: (p, k) => (p === "cursor" && k === "included_only" ? on : undefined) } }) + const a = fresh() + return { ...(await hooks.auth.usage(async () => a, provider)), seen } +} + +// how magpie reads the windows (internal/provider/plugin_usage.go, +// routing.go allowanceOf): a window not aside and used up stops each model +// it counts +function counts(w, model) { + if (w.models?.length) return w.models.includes(model) + if (w.notModels?.length) return !w.notModels.includes(model) + return true +} +const stopped = (windows, model) => windows.some((w) => !w.aside && w.used >= 100 && counts(w, model)) + +const spentPools = { billingCycleEnd: "1793683212396", planUsage: { autoPercentUsed: 100, apiPercentUsed: 100, totalPercentUsed: 100 }, autoBucketModels: ["default", "composer-2.5"] } +const grant = (g) => ({ activeGrants: [{ grantId: "1001", totalCents: "2000", remainingCents: "1500", expiresAtMs: String(later), grantType: "promo", showInClient: true, ...g }] }) + +test("the real account with no bonus and no grant shows no free credit, and asks for grants as the IDE does", async () => { + const { windows, seen } = await read({ period: REAL_PERIOD, plan: REAL_PLAN }) + expect(windows.map((w) => w.name)).toEqual(["Weekly"]) + const g = seen.find((r) => r.url === GRANTS) + expect(g.body).toBe("{}") + expect(g.headers["Connect-Protocol-Version"]).toBe("1") +}) + +test("the plan's bonus: its spend is shown, and with some left the spent pools don't stop the account", async () => { + const { windows } = await read({ period: { ...spentPools, planUsage: { ...spentPools.planUsage, bonusSpend: 1234, remainingBonus: true } } }) + expect(windows.find((w) => w.name === "Free usage")).toEqual({ name: "Free usage", used: 0, display: "+$12.34 on us, more left", resetsAt: at, aside: true }) + for (const m of ["composer-2.5", "gpt-5.6-sol"]) expect(stopped(windows, m)).toBe(false) + // none left: the spent pools stop it again + const out = (await read({ period: { ...spentPools, planUsage: { ...spentPools.planUsage, bonusSpend: 1234, remainingBonus: false } } })).windows + expect(out.find((w) => w.name === "Free usage").display).toBe("+$12.34 on us") + for (const m of ["composer-2.5", "gpt-5.6-sol"]) expect(stopped(out, m)).toBe(true) +}) + +test("a grant for every model: remaining of total, its expiry, and the spent pools stay aside while it lasts", async () => { + const { windows } = await read({ period: spentPools, grants: grant({ campaignName: "Launch week" }) }) + expect(windows.find((w) => w.name === "Launch week")).toEqual({ + name: "Launch week", used: 25, display: "$5.00 / $20.00", amount: 5, limit: 20, unit: "USD", + runsOutAt: new Date(later).toISOString(), runsOut: 15, aside: true, + }) + for (const m of ["composer-2.5", "gpt-5.6-sol"]) expect(stopped(windows, m)).toBe(false) + // used up, or expired: the pools are the allowance again + for (const g of [{ remainingCents: "0" }, { expiresAtMs: String(Date.now() - 1000) }]) { + const out = (await read({ period: spentPools, grants: grant(g) })).windows + for (const m of ["composer-2.5", "gpt-5.6-sol"]) expect(stopped(out, m)).toBe(true) + } +}) + +test("a grant limited to some models names them, and keeps only those served past a spent pool", async () => { + for (const g of [{ allowedModelIds: ["claude-opus-5-5"] }, { allowedModelTags: ["opus-5"] }, { allowedModelSelections: [{ modelId: "claude-opus-5-5", maxMode: false }] }]) { + const { windows } = await read({ period: spentPools, grants: grant(g) }) + const w = windows.find((w) => w.name === "Free credit") + // a sized id is asked for by its bare name too + expect(w.models).toEqual(["claude-opus-5-5@300k", "claude-opus-5-5", "claude-opus-5-5@1m"]) + expect(w.aside).toBe(true) + expect(stopped(windows, "claude-opus-5-5@1m")).toBe(false) + expect(stopped(windows, "gpt-5.6-sol")).toBe(true) + expect(stopped(windows, "composer-2.5")).toBe(true) + } + // with room in the pools nothing changes + const room = (await read({ period: { ...spentPools, planUsage: { autoPercentUsed: 10, apiPercentUsed: 10, totalPercentUsed: 10 } }, grants: grant({ allowedModelIds: ["claude-opus-5-5"] }) })).windows + expect(room.find((w) => w.name === "Other Models").notModels).toEqual(["auto", "composer-2.5", "default"]) +}) + +test("a grant on Cursor Models alone keeps a spent Cursor Models pool from stopping them, never counting every model", async () => { + const { windows } = await read({ period: spentPools, grants: grant({ allowedModelIds: ["default", "composer-2.5"] }) }) + const cm = windows.find((w) => w.name === "Cursor Models") + expect(cm.models.length).toBeGreaterThan(0) + expect(stopped(windows, "composer-2.5")).toBe(false) + expect(stopped(windows, "auto")).toBe(false) + expect(stopped(windows, "gpt-5.6-sol")).toBe(true) +}) + +test("a merged plan's spent Weekly leaves out the models a grant pays for", async () => { + const { windows } = await read({ period: spentPools, plan: REAL_PLAN, grants: grant({ allowedModelIds: ["gpt-5.6-sol"] }) }) + expect(stopped(windows, "gpt-5.6-sol")).toBe(false) + expect(stopped(windows, "composer-2.5")).toBe(true) +}) + +test("a grant magpie can't spend (Cloud Agents only, or another client) is shown with its limit and keeps nothing served", async () => { + for (const [clients, name] of [[["glass"], "Free credit (Cloud Agents only)"], [["ide"], "Free credit (ide only)"]]) { + const { windows } = await read({ period: spentPools, grants: grant({ allowedClientTypes: clients }) }) + expect(windows.find((w) => w.name === name)).toBeDefined() + expect(stopped(windows, "composer-2.5")).toBe(true) + } + const cli = (await read({ period: spentPools, grants: grant({ allowedClientTypes: ["ide", "cli"] }) })).windows + expect(stopped(cli, "composer-2.5")).toBe(false) +}) + +test("with Included usage only on, free credit is shown and keeps nothing served", async () => { + const { windows } = await read({ period: { ...spentPools, planUsage: { ...spentPools.planUsage, bonusSpend: 100, remainingBonus: true } }, grants: grant({}) }, true) + expect(windows.some((w) => w.name === "Free credit")).toBe(true) + expect(stopped(windows, "composer-2.5")).toBe(true) +}) + +test("free credit goes after Bot and before Total; a grants read that fails leaves the card as before", async () => { + const { windows } = await read({ period: spentPools, grants: grant({}) }) + expect(windows.map((w) => w.name)).toEqual(["Cursor Models", "Other Models", "Free credit", "Total"]) + const failed = (await read({ period: spentPools, grants: new Response("no", { status: 500 }) })).windows + expect(failed.map((w) => w.name)).toEqual(["Cursor Models", "Other Models", "Total"]) + for (const m of ["composer-2.5", "gpt-5.6-sol"]) expect(stopped(failed, m)).toBe(true) +}) diff --git a/packages/cursor/index.mjs b/packages/cursor/index.mjs index 03e3e96..9e6c8c3 100644 --- a/packages/cursor/index.mjs +++ b/packages/cursor/index.mjs @@ -541,6 +541,99 @@ 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 }) +// ---- free credit ------------------------------------------------------------------ +// +// Cursor gives free usage two ways (CryptoSarom on X, "赠金"), as Cursor +// 3.x's own client reads them: +// +// - the plan's bonus, "+$X free usage on us" under the included usage in +// the IDE's usage tooltip: GetCurrentPeriodUsage's planUsage.bonusSpend +// (cents spent from it this period), remainingBonus (whether any is +// left; no amount is given) and bonusTooltip ("We work with model +// providers to give you free usage beyond what you've purchased. Amounts +// may vary."). It isn't tied to a model. +// - credit grants, the IDE's "Use your $X free … credits" banner: +// DashboardService/GetUsageLimitStatusAndActiveGrants' activeGrants, each +// with totalCents and remainingCents (int64 strings), expiresAtMs, and +// its limits: allowedModelIds, allowedModelTags and allowedModelSelections +// (the models it may be spent on; none listed is every model) and +// allowedClientTypes (the clients that may spend it; none listed is any; +// "glass" without "ide" is the IDE's Cloud Agent credits). magpie talks +// as cursor-agent, clientType "cli". +// +// creditGrants is that reply's activeGrants, [] when it couldn't be read. +async function creditGrants(tok) { + try { + const res = await fetch(API + "/aiserver.v1.DashboardService/GetUsageLimitStatusAndActiveGrants", { + method: "POST", + headers: { Authorization: `Bearer ${tok}`, "Content-Type": "application/json", "Connect-Protocol-Version": "1", ...await teamHeader(tok) }, + body: "{}", + signal: AbortSignal.timeout(15_000), + }) + if (!res.ok) return [] + const g = (await res.json())?.activeGrants + return Array.isArray(g) ? g : [] + } catch { + return [] + } +} + +// tagOf is a model name as the IDE matches a grant's allowedModelTags to +// it: lower case, "-" read as "."; a tag matches a name it is part of. +const tagOf = (s) => String(s).toLowerCase().replace(/-/g, ".") + +// credits are the windows of the account's free credit, and what it lets +// Cursor go on serving once the included usage is spent: all (a bonus or +// grant magpie can spend on every model still has some left) and covers +// (the account's model ids a grant limited to some models still pays +// for). Every credit window is shown only: what stops an account is the +// included usage it outlasts, which usage() sets aside. plan is +// planUsage, resets its period's end, ids the account's model ids. +function credits(plan, grants, ids, resets, now = Date.now()) { + const windows = [] + const covers = new Set() + let all = false + const bonus = Number(plan?.bonusSpend ?? 0) / 100 + if (bonus > 0 || plan?.remainingBonus === true) { + windows.push({ name: "Free usage", used: 0, display: `+${dollars(bonus)} on us` + (plan?.remainingBonus === true ? ", more left" : ""), ...resets, aside: true }) + if (plan?.remainingBonus === true) all = true + } + for (const g of grants) { + const total = Number(g?.totalCents ?? 0) / 100 + const left = Math.max(0, Number(g?.remainingCents ?? 0) / 100) + if (!(total > 0) || !Number.isFinite(total) || !Number.isFinite(left)) continue + const exp = Number(g.expiresAtMs ?? 0) + if (exp > 0 && exp <= now) continue + const clients = (g.allowedClientTypes ?? []).map(String) + const mine = clients.length === 0 || clients.includes("cli") + const named = [...(g.allowedModelIds ?? []), ...(g.allowedModelSelections ?? []).map((m) => m?.modelId).filter(Boolean)].map(String) + const tags = (g.allowedModelTags ?? []).map(String) + const limited = named.length > 0 || tags.length > 0 + const bases = new Set(named.map((m) => (poolBase(m) === "auto" ? "default" : poolBase(m)))) + const fits = (id) => { + const b = poolBase(id) === "auto" ? "default" : poolBase(id) + return bases.has(b) || tags.some((t) => tagOf(id).includes(tagOf(t))) + } + const matched = limited ? ids.filter(fits) : [] + const name = (String(g.campaignName ?? "").trim() || "Free credit") + (mine ? "" : clients.includes("glass") && !clients.includes("ide") ? " (Cloud Agents only)" : ` (${clients.join(", ")} only)`) + windows.push({ + name, + used: Math.max(0, Math.min(100, (100 * (total - left)) / total)), + display: `${dollars(total - left)} / ${dollars(total)}`, + amount: total - left, + limit: total, + unit: "USD", + ...(exp > 0 ? { runsOutAt: new Date(exp).toISOString(), runsOut: left } : {}), + ...(limited ? { models: matched.length ? matched : [...named, ...tags] } : {}), + aside: true, + }) + if (!mine || !(left > 0)) continue + if (!limited) all = true + else for (const id of matched) covers.add(id) + } + return { windows, all, covers } +} + // 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 @@ -638,13 +731,14 @@ async function usage(tok, ids, includedOnly = false, plan = undefined) { }), hardLimit(tok), ]) + const grants = creditGrants(tok) if (!res.ok) return { error: statusText(res.status), windows: [] } const data = await res.json() const u = data?.planUsage if (!u) { // Prefer measured Enterprise usage before any reset-date-only fallback. const windows = await enterpriseUsage(tok, includedOnly) - return windows ? { windows } : { windows: [] } + return { windows: windows ?? [], credits: credits(undefined, await grants, ids, {}).windows } } const ms = /^[+-]?\d+$/.test(data.billingCycleEnd ?? "") ? Number(data.billingCycleEnd) : 0 const resets = ms > 0 ? { resetsAt: new Date(ms).toISOString() } : {} @@ -665,10 +759,16 @@ async function usage(tok, ids, includedOnly = false, plan = undefined) { 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 = !includedOnly && (od.kind === "fixed" || od.kind === "unlimited") ? { aside: true } : {} + // free credit that magpie can spend on every model keeps the account + // served past its included usage, as on-demand that can pay does; one + // limited to some models keeps those models served past a spent pool. + // Neither does with includedOnly. + const free = credits(u, await grants, [...new Set(asked)], resets) + const pooled = !includedOnly && (od.kind === "fixed" || od.kind === "unlimited" || free.all) ? { aside: true } : {} + const covers = includedOnly ? new Set() : free.covers 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, ...(includedOnly ? { aside: true } : {}) }] + ? [{ 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 || free.all ? { aside: true } : {}) }] : od.kind === "unlimited" ? [{ name: "On-demand", used: 0, display: dollars(od.usedDollars), ...resets, aside: true }] : [] @@ -676,23 +776,33 @@ async function usage(tok, ids, includedOnly = false, plan = undefined) { // model draws on, which the dashboard shows as the period's // totalPercentUsed, autoPercentUsed the same and apiPercentUsed 0 always. const info = await plan + // spent is whether a pool no longer pays: then the models a credit still + // pays for are left out of it + const spent = (used) => covers.size > 0 && !pooled.aside && used >= 100 if (info?.merged === true) { const weekly = info.period === "weekly" + const used = num(u.totalPercentUsed) return { windows: [ - { name: weekly ? "Weekly" : info.period === "monthly" ? "Monthly" : "Included", used: num(u.totalPercentUsed), ...resets, ...(weekly ? { span: 604800 } : {}), ...pooled }, + { name: weekly ? "Weekly" : info.period === "monthly" ? "Monthly" : "Included", used, ...resets, ...(weekly ? { span: 604800 } : {}), ...(spent(used) ? { notModels: [...covers] } : {}), ...pooled }, ...onDemand, ], + credits: free.windows, } } - // the two pools fit the line; the total goes in its tooltip + // the two pools fit the line; the total goes in its tooltip. A spent + // Cursor Models pool every model of which a credit pays for is aside: + // an empty models list would count every model. + const auto = num(u.autoPercentUsed), api = num(u.apiPercentUsed) + const cursorModels = spent(auto) ? pool.filter((m) => !covers.has(m)) : pool return { windows: [ - { name: "Cursor Models", used: num(u.autoPercentUsed), ...resets, models: pool, ...pooled }, - { name: "Other Models", used: num(u.apiPercentUsed), ...resets, notModels: pool, ...pooled }, + { name: "Cursor Models", used: auto, ...resets, models: cursorModels.length ? cursorModels : pool, ...(cursorModels.length ? pooled : { aside: true }) }, + { name: "Other Models", used: api, ...resets, notModels: spent(api) ? [...new Set([...pool, ...covers])] : pool, ...pooled }, ...onDemand, { name: "Total", used: num(u.totalPercentUsed), ...resets, aside: true }, ], + credits: free.windows, } } @@ -3257,7 +3367,7 @@ export async function CursorAuthPlugin(input) { key: INCLUDED_ONLY, label: "Included usage only", description: - "Keeps an account in routing only while its included usage lasts: once an included pool (Cursor Models, Other Models, a newer plan's Weekly) is used up, magpie moves its models to the next account until it resets, even if on-demand could pay. On-demand and Total never keep an account in routing.", + "Keeps an account in routing only while its included usage lasts: once an included pool (Cursor Models, Other Models, a newer plan's Weekly) is used up, magpie moves its models to the next account until it resets, even if on-demand or free credit could pay.", }, ], // magpie's: how much of the plan's included usage is gone (the plan @@ -3276,9 +3386,11 @@ export async function CursorAuthPlugin(input) { // 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 // with a limit stays ahead of it: that is what can stop the account. + // Free credit goes after them, with Total: it is shown only. const last = (w) => w.name === "Total" || (w.name === "On-demand" && w.aside) - const windows = [...u.windows.filter((w) => !last(w)), ...bot, ...u.windows.filter(last)] - return { ...u, windows, ...(plan ? { plan } : {}), signIn: "kept" } + const { credits: free = [], ...read } = u + const windows = [...read.windows.filter((w) => !last(w)), ...bot, ...free, ...read.windows.filter(last)] + return { ...read, windows, ...(plan ? { plan } : {}), signIn: "kept" } }, }, // the session the request is part of, for the conversation_id @@ -3320,4 +3432,4 @@ export async function CursorAuthPlugin(input) { } // for tests -export const _internal = { kvReply, listFor, lists, keychain, keychainToken, nativeTransport, onDemandOf,resetH1: () => (h1Until = 0), onH1: () => Date.now() < h1Until, resetTeam: () => { teamRead.at = 0; teamRead.info = null }, expireTeam: () => (teamRead.at = 0),H2, H1, h2Blocked, open, openH1, openH2, STEP_WAIT, stepUsage, usageKey, ledger, owed, flights, misses, unreadable, catalog, usable, request, modelsOf, tokensOf, maxRequired, conversationID, usageOf, sessionOf, SESSION, errorResponse, kept, poolBase, conversation, buildRun, decode, exec, fields, pb, pbValue, pbAny, frame, frames, failure, toolsOf, expiry } +export const _internal = { credits, kvReply, listFor, lists, keychain, keychainToken, nativeTransport, onDemandOf,resetH1: () => (h1Until = 0), onH1: () => Date.now() < h1Until, resetTeam: () => { teamRead.at = 0; teamRead.info = null }, expireTeam: () => (teamRead.at = 0),H2, H1, h2Blocked, open, openH1, openH2, STEP_WAIT, stepUsage, usageKey, ledger, owed, flights, misses, unreadable, catalog, usable, request, modelsOf, tokensOf, maxRequired, conversationID, usageOf, sessionOf, SESSION, errorResponse, kept, poolBase, conversation, buildRun, decode, exec, fields, pb, pbValue, pbAny, frame, frames, failure, toolsOf, expiry } diff --git a/packages/cursor/package.json b/packages/cursor/package.json index 64a2332..61eab19 100644 --- a/packages/cursor/package.json +++ b/packages/cursor/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-cursor-auth", - "version": "0.2.32", + "version": "0.2.33", "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 a69da99..614f26e 100644 --- a/packages/cursor/usage.test.mjs +++ b/packages/cursor/usage.test.mjs @@ -412,6 +412,8 @@ test("a team's org-wide on-demand pool is the allowance: its spend is shown, and { name: "Cursor Models", used: 57.81428571428572, resetsAt: at, aside: true }, { name: "Other Models", used: 100, resetsAt: at, aside: true }, { name: "On-demand", used: (100 * 6334270) / 45120000, display: "$63,342.70 / $451,200.00 (you: $198.55)", resetsAt: at }, + // its bonusSpend: the IDE's "+$141.51 free usage on us" + { name: "Free usage", used: 0, display: "+$141.51 on us", resetsAt: at, aside: true }, { name: "Total", used: 64.604, resetsAt: at, aside: true }, ]) }