From f73ba656b299167f9c01804987f3dbe8b098fb5a Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 10 Nov 2026 11:57:54 +0800 Subject: [PATCH] cursor: auth.calls lists the account's calls made outside magpie (0.2.44, WaiooT on X) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit magpie's Usage page counts only what went through magpie, so Cursor's editor and cursor-agent use was missing ("求支持统计cursor的使用情况"). auth.calls reads GetFilteredUsageEvents page by page from the time magpie asks for and gives each of the account's own events: id, time, model, tokens (input uncached; cache read/write apart), cost (totalCents / 100) and conversation. A team's other members (owningUser vs GetMe's userId) and the conversations this plugin ran itself (kept 40 days in $XDG_DATA_HOME/opencode-cursor-auth/conversations.json, written temp-and-rename) are left out. A refused page fails the reading. Run: bun test in packages/cursor on mote (410 pass), scripts/check.mjs. calls.test.mjs's fixtures carry the field names of a real Pro account's reply. Real account: the hook read 43 events (30 days) from the owner's Cursor sign-in, tokens and costs as the dashboard has them. Broken by hand: without the own-conversation and owningUser filters the first calls test goes red. Not tried: a team account with other members; Cursor's editor (none installed here), so an editor event's shape is taken as the same. --- packages/cursor/README.md | 16 ++++ packages/cursor/calls.test.mjs | 99 +++++++++++++++++++++++++ packages/cursor/index.mjs | 129 ++++++++++++++++++++++++++++++++- packages/cursor/package.json | 2 +- 4 files changed, 243 insertions(+), 3 deletions(-) create mode 100644 packages/cursor/calls.test.mjs diff --git a/packages/cursor/README.md b/packages/cursor/README.md index 0f51edf..8960c8b 100644 --- a/packages/cursor/README.md +++ b/packages/cursor/README.md @@ -328,6 +328,22 @@ 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. +### Calls outside magpie + +`auth.calls` gives magpie the account's own calls made outside it (Cursor's +editor, `cursor-agent`, anything else), so its Usage page counts them. They +come from the dashboard's usage events +(`DashboardService/GetFilteredUsageEvents`, read page by page from the time +magpie asks for): each event's id, time, model, tokens (input is the +uncached part; cache reads and writes are apart) and cost in USD +(`tokenUsage.totalCents`). On a team, other members' events are left out +(`owningUser` against `GetMe`'s `userId`). So are the events of the +conversations this plugin ran itself, which magpie counted already: their +ids are kept for 40 days in +`$XDG_DATA_HOME/opencode-cursor-auth/conversations.json` +(`~/.local/share/…` without it). Cursor's events don't say which client +made them, so the editor and `cursor-agent` are counted together. + ### Included usage only (optional) In magpie, open the Cursor provider, turn on **Included usage only** under diff --git a/packages/cursor/calls.test.mjs b/packages/cursor/calls.test.mjs new file mode 100644 index 0000000..f7ad9a2 --- /dev/null +++ b/packages/cursor/calls.test.mjs @@ -0,0 +1,99 @@ +// auth.calls lists the account's own calls that didn't go through magpie, +// for magpie's Usage page, from GetFilteredUsageEvents as Cursor answers it +// (fields as a real Pro account's reply has them, 2026-11). +import "./nonet.mjs" // first: no request leaves this machine +import { afterAll, afterEach, expect, test } from "bun:test" +import { mkdtempSync, readFileSync, rmSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" + +const data = mkdtempSync(join(tmpdir(), "cursor-calls-")) +process.env.XDG_DATA_HOME = data +const { CursorAuthPlugin, _internal } = await import("./index.mjs") + +const real = globalThis.fetch +afterEach(() => (globalThis.fetch = real)) +afterAll(() => rmSync(data, { recursive: true, force: true })) + +const jwt = (exp) => ["e30", Buffer.from(JSON.stringify({ exp, sub: "calls-" + Math.random() })).toString("base64url"), "sig"].join(".") +const auth = () => ({ type: "oauth", access: jwt(Math.floor(Date.now() / 1000) + 3600), refresh: "", expires: 0 }) + +const EVENTS = "https://api2.cursor.sh/aiserver.v1.DashboardService/GetFilteredUsageEvents" +const ME = "https://api2.cursor.sh/aiserver.v1.DashboardService/GetMe" + +const event = (id, at, conv, extra = {}) => ({ + timestamp: String(at), + model: "grok-4.7-medium", + kind: "USAGE_EVENT_KIND_INCLUDED_IN_PRO", + requestsCosts: 0.1, + isTokenBasedCall: true, + tokenUsage: { inputTokens: 1200, outputTokens: 300, cacheReadTokens: 45000, totalCents: 0.415 }, + owningUser: "9573301", + isChargeable: true, + isHeadless: false, + conversationId: conv, + chargedCents: 0.415, + usageEventId: id, + ...extra, +}) + +function serve(pages) { + const seen = [] + globalThis.fetch = async (url, init) => { + seen.push({ url: String(url), body: init.body ? JSON.parse(init.body) : undefined }) + if (String(url) === ME) return Response.json({ userId: 9573301, email: "a@b.c" }) + if (String(url) === EVENTS) { + const b = JSON.parse(init.body) + return Response.json(pages[b.page - 1] ?? { usageEventsDisplay: [] }) + } + return Response.json({}) + } + return seen +} + +test("the account's own events from since on, less its other members' and this plugin's own conversations", async () => { + const since = Date.now() - 86_400_000 + _internal.ownConversation("conv-magpie") + const seen = serve([ + { + totalUsageEventsCount: 4, + usageEventsDisplay: [ + event("ev-2", since + 2000, "conv-editor"), + event("ev-1", since + 1000, "conv-editor", { tokenUsage: { inputTokens: 10, outputTokens: 5, cacheReadTokens: 7, cacheWriteTokens: 3, totalCents: 1.5 } }), + event("ev-3", since + 3000, "conv-magpie"), + event("ev-4", since + 4000, "conv-teammate", { owningUser: "111" }), + event("ev-old", since - 5000, "conv-editor"), + ], + }, + ]) + const hooks = await CursorAuthPlugin() + const { calls } = await hooks.auth.calls(async () => auth(), {}, { since }) + expect(calls).toEqual([ + { rid: "ev-1", t: since + 1000, model: "grok-4.7-medium", in: 10, out: 5, cache_read: 7, cache_write: 3, cost: 0.015, session: "conv-editor" }, + { rid: "ev-2", t: since + 2000, model: "grok-4.7-medium", in: 1200, out: 300, cache_read: 45000, cache_write: 0, cost: 0.00415, session: "conv-editor" }, + ]) + const ask = seen.find((r) => r.url === EVENTS) + expect(ask.body.startDate).toBe(String(since)) + expect(ask.body.page).toBe(1) +}) + +test("every page is read, up to the total", async () => { + const since = Date.now() - 86_400_000 + const page = (from, n) => ({ totalUsageEventsCount: 150, usageEventsDisplay: Array.from({ length: n }, (_, i) => event("p" + (from + i), since + 10 + from + i, "c")) }) + const seen = serve([page(0, 100), page(100, 50)]) + const { calls } = await (await CursorAuthPlugin()).auth.calls(async () => auth(), {}, { since }) + expect(calls.length).toBe(150) + expect(seen.filter((r) => r.url === EVENTS).map((r) => r.body.page)).toEqual([1, 2]) +}) + +test("a reply Cursor refuses fails the reading", async () => { + globalThis.fetch = async (url) => (String(url) === EVENTS ? new Response("{}", { status: 503 }) : Response.json({ userId: 1 })) + await expect((await CursorAuthPlugin()).auth.calls(async () => auth(), {}, { since: Date.now() - 1000 })).rejects.toThrow() +}) + +test("this plugin's own conversations are kept on disk, for the next start", async () => { + _internal.ownConversation("conv-kept") + await new Promise((r) => setTimeout(r, 1500)) + const kept = JSON.parse(readFileSync(join(data, "opencode-cursor-auth", "conversations.json"), "utf8")) + expect(typeof kept["conv-kept"]).toBe("number") +}) diff --git a/packages/cursor/index.mjs b/packages/cursor/index.mjs index ff1a82c..046597c 100644 --- a/packages/cursor/index.mjs +++ b/packages/cursor/index.mjs @@ -36,7 +36,7 @@ import { gunzipSync } from "node:zlib" import { Duplex } from "node:stream" import { createHash, randomBytes, randomUUID } from "node:crypto" import { execFile } from "node:child_process" -import { readFile, stat, readdir, realpath } from "node:fs/promises" +import { readFile, stat, readdir, realpath, writeFile, mkdir, rename } from "node:fs/promises" import { homedir, platform, tmpdir } from "node:os" import { basename, dirname, join } from "node:path" @@ -2748,11 +2748,128 @@ function nativeTransport(req, close, fail, limits = NATIVE_LIMITS) { } } +// ---- the account's calls, for magpie's Usage page --------------------------- + +// mine are the conversation_ids this plugin's own Runs used, with when each +// was last used: their usage events are calls magpie's gateway counted +// already, so calls leaves them out. They are kept OWN_KEEP, in a file of +// the plugin's own, so a restart still knows them. +const OWN_KEEP = 40 * 86_400_000 +const mine = { ids: new Map(), read: null, timer: null, file: () => join(process.env.XDG_DATA_HOME || join(homedir(), ".local", "share"), "opencode-cursor-auth", "conversations.json") } +function readMine() { + mine.read ??= readFile(mine.file(), "utf8") + .then((t) => { + const kept = JSON.parse(t) + for (const [id, at] of Object.entries(kept && typeof kept === "object" ? kept : {})) + if (typeof at === "number" && !mine.ids.has(id)) mine.ids.set(id, at) + }) + .catch(() => {}) + return mine.read +} +function saveMine() { + if (mine.timer) return + mine.timer = setTimeout(async () => { + mine.timer = null + await readMine() + const now = Date.now() + for (const [id, at] of mine.ids) if (now - at > OWN_KEEP) mine.ids.delete(id) + const file = mine.file() + try { + await mkdir(dirname(file), { recursive: true }) + const tmp = file + "." + process.pid + ".tmp" + await writeFile(tmp, JSON.stringify(Object.fromEntries(mine.ids))) + await rename(tmp, file) + } catch {} + }, 1000) + mine.timer.unref?.() +} +function ownConversation(cid) { + mine.ids.set(cid, Date.now()) + saveMine() +} + +// mes are each token's account id (GetMe's userId), asked once an hour: a +// team's events can be other members', which calls leaves out +const mes = new Map() +async function meOf(tok) { + const had = mes.get(tok) + if (had && Date.now() - had.at < 3600_000) return had.id + try { + const me = await unary(API, "aiserver.v1.DashboardService/GetMe", tok) + const id = me?.userId == null ? "" : String(me.userId) + mes.set(tok, { id, at: Date.now() }) + return id + } catch { + return had?.id ?? "" + } +} + +// CALLS_PAGE is how many events one GetFilteredUsageEvents page asks for, +// and CALLS_PAGES how many pages one reading reads at most +const CALLS_PAGE = 100 +const CALLS_PAGES = 50 + +// callsOf are the account's own usage events from since on, as the +// dashboard's Usage page lists them (GetFilteredUsageEvents), less the ones +// of this plugin's own conversations: the calls the account made from +// Cursor's editor, cursor-agent or anything else not through magpie. Each +// has its event id (rid), time, model, tokens (in is the uncached rest, as +// magpie counts it), its cost in USD and its conversation. A page Cursor +// won't give fails the reading: magpie asks again from the same time. +async function callsOf(tok, since, signal) { + await readMine() + const me = await meOf(tok) + const num = (v) => (Number.isFinite(Number(v)) ? Number(v) : 0) + const out = [] + const end = Date.now() + for (let page = 1; page <= CALLS_PAGES; page++) { + const res = await fetch(API + "/aiserver.v1.DashboardService/GetFilteredUsageEvents", { + method: "POST", + headers: await headersFor(tok), + body: JSON.stringify({ ...await teamBody(tok), startDate: String(since), endDate: String(end), page, pageSize: CALLS_PAGE }), + signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(15_000)]) : AbortSignal.timeout(15_000), + }) + const text = await res.text() + if (!res.ok) { + const f = failure(res.status, text) + const e = new Error(f.message) + e.status = f.status + throw e + } + const body = JSON.parse(text || "{}") + const evs = body?.usageEventsDisplay ?? [] + for (const ev of evs) { + const t = ev?.tokenUsage + const at = num(ev?.timestamp) + if (!t || !at || at < since) continue + if (me && ev.owningUser != null && String(ev.owningUser) !== me) continue + if (ev.conversationId && mine.ids.has(ev.conversationId)) continue + const rid = String(ev.usageEventId ?? "") || `${ev.conversationId ?? ""}:${at}:${ev.model ?? ""}` + const cents = t.totalCents ?? ev.chargedCents + out.push({ + rid, + t: at, + model: String(ev.model ?? ""), + in: num(t.inputTokens), + out: num(t.outputTokens), + cache_read: num(t.cacheReadTokens), + cache_write: num(t.cacheWriteTokens), + ...(cents == null ? {} : { cost: num(cents) / 100 }), + ...(ev.conversationId ? { session: String(ev.conversationId) } : {}), + }) + } + const total = num(body?.totalUsageEventsCount) + if (evs.length < CALLS_PAGE || (total && page * CALLS_PAGE >= total)) break + } + return out.sort((a, b) => a.t - b.t) +} + // runNative opens a session-owned Run. Its background decoder survives the end // of each Chat segment; only terminal completion, failure, or cancellation // releases the transport. async function runNative({ tok, base, id, tools, conv, convID, signal, maxMode, params, native }) { const cid = convID || randomUUID() + ownConversation(cid) const since = Date.now() // Transport shutdown precedes final debt collection. Keep its cancellation // separate, and return any undelivered collection through the ledger's carry. @@ -2919,6 +3036,7 @@ async function runOnce({ tok, base, id, tools, conv, convID, signal, maxMode, pa // the Run's conversation_id, a new one when nothing names the session: // its usage event is found by it const cid = convID || randomUUID() + ownConversation(cid) const since = Date.now() // how its usage is counted: a debt of the conversation's is collected // while it goes, which only a conversation_id that names the session @@ -3670,6 +3788,13 @@ export async function CursorAuthPlugin(input) { const windows = [...read.windows.filter((w) => !last(w)), ...bot, ...free, ...read.windows.filter(last)] return { ...read, windows, ...(plan ? { plan } : {}), signIn: "kept" } }, + // magpie's: the account's calls from since (ms) on that didn't go + // through magpie, for its Usage page (callsOf). A failure is thrown: + // magpie reads them again from the same time. + async calls(getAuth, provider, { since = Date.now() - 30 * 86_400_000, signal } = {}) { + const tok = await tokenOf(await getAuth()) + return { calls: await callsOf(tok, Math.max(0, Number(since) || 0), signal) } + }, }, // the session the request is part of, for the conversation_id // (conversationID): magpie and OpenCode name it here, and the loader's @@ -3710,4 +3835,4 @@ export async function CursorAuthPlugin(input) { } // for tests -export const _internal = { slugFor, fromCatalog, 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 } +export const _internal = { mine, ownConversation, callsOf, slugFor, fromCatalog, 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 6256d5f..080f54a 100644 --- a/packages/cursor/package.json +++ b/packages/cursor/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-cursor-auth", - "version": "0.2.43", + "version": "0.2.44", "description": "Cursor subscriptions (Pro, Pro+, Ultra, Teams) in OpenCode and magpie, through the API cursor-agent talks to", "type": "module", "main": "./opencode.mjs",