From 10bf7c43646b904164474cf27d3ada244869a700 Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 3 Oct 2026 21:10:20 +0800 Subject: [PATCH] =?UTF-8?q?cursor=200.1.9:=20a=20step=20that=20calls=20too?= =?UTF-8?q?ls=20reports=20what=20it=20used,=20the=20cache=20included=20(ye?= =?UTF-8?q?tone/magpie#676)=20=E2=80=94=20Cursor=20tells=20a=20turn's=20us?= =?UTF-8?q?age=20(TurnEndedUpdate)=20only=20once=20the=20client=20has=20ru?= =?UTF-8?q?n=20the=20tools=20and=20sent=20their=20results=20in=20the=20sam?= =?UTF-8?q?e=20Run,=20and=20the=20caller=20runs=20them=20after=20the=20Run?= =?UTF-8?q?=20is=20closed,=20so=20a=20tool=20step=20had=20none:=20its=20in?= =?UTF-8?q?put=20was=20estimated=20with=20no=20cache=20(2395=20/=200=20whe?= =?UTF-8?q?re=20Cursor=20counted=204265,=204224=20of=20them=20cached).=20A?= =?UTF-8?q?fter=20the=20calls=20it=20sends=20only=20the=20checkpoint=20(no?= =?UTF-8?q?=20token=20details)=20and=20heartbeats,=20and=20a=20cancelled?= =?UTF-8?q?=20Run=20ends=20with=20an=20error=20and=20no=20usage.=20Every?= =?UTF-8?q?=20Run=20is=20counted=20in=20the=20dashboard's=20usage=20events?= =?UTF-8?q?=20(DashboardService/GetFilteredUsageEvents)=20by=20its=20conve?= =?UTF-8?q?rsation=5Fid,=20input=20apart=20from=20the=20cache=20read=20and?= =?UTF-8?q?=20written,=20as=20TurnEndedUpdate=20does;=20one=20shows=20abou?= =?UTF-8?q?t=202.5=20s=20after=20the=20Run=20closes.=20So=20a=20tool=20ste?= =?UTF-8?q?p=20with=20no=20TurnEnded=20closes=20the=20Run,=20then=20looks?= =?UTF-8?q?=20for=20its=20event=20(after=201.5=20s,=20every=200.5=20s,=20u?= =?UTF-8?q?p=20to=206=20s):=20its=20conversation's,=20no=20older=20than=20?= =?UTF-8?q?the=20Run,=20not=20already=20counted;=20else=20the=20estimate?= =?UTF-8?q?=20as=20before.=20stepusage.test.mjs=20fails=20on=20the=20old?= =?UTF-8?q?=20code=20and=20passes.=20Tried=20with=20the=20real=20Cursor=20?= =?UTF-8?q?account=20through=20a=20sandbox=20magpie's=20plugin=20host:=20g?= =?UTF-8?q?rok-4.7-fast=20tool=20calls=20report=206186=20in,=206144=20cach?= =?UTF-8?q?ed,=20121=20out=20(0.1.8:=205057=20estimated,=200=20cached);=20?= =?UTF-8?q?streamed=20too.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/cursor/README.md | 7 ++- packages/cursor/index.mjs | 95 +++++++++++++++++++++++++--- packages/cursor/package.json | 2 +- packages/cursor/stepusage.test.mjs | 99 ++++++++++++++++++++++++++++++ 4 files changed, 192 insertions(+), 11 deletions(-) create mode 100644 packages/cursor/stepusage.test.mjs diff --git a/packages/cursor/README.md b/packages/cursor/README.md index a40b333..12dacb7 100644 --- a/packages/cursor/README.md +++ b/packages/cursor/README.md @@ -54,7 +54,12 @@ plugin's `fetch` answers them on Cursor's agent API: or not. Cursor's `input_tokens` counts the cached prompt too: the cache read and written is taken out of it, and given as `cached_tokens` and `cache_write_tokens`, so it is counted once; its reasoning tokens are - `reasoning_tokens`. Failures keep their statuses: 401 to sign in again, 429 at the + `reasoning_tokens`. A step that calls tools gets no usage in its Run + (Cursor tells it only once the tools' results come back in the same + Run), so once the Run is closed its usage is read from the dashboard's + usage events, by the Run's conversation id: it shows in about 2.5 s, + and is looked for up to 6 s, after which it is estimated as before. + Failures keep their statuses: 401 to sign in again, 429 at the usage limit, 400 for a prompt too long, 403 for a region refusal. ## Models diff --git a/packages/cursor/index.mjs b/packages/cursor/index.mjs index 2f94573..a4489ff 100644 --- a/packages/cursor/index.mjs +++ b/packages/cursor/index.mjs @@ -1164,6 +1164,59 @@ function usageOf(uf) { return { input: Math.max(inp - cr - cw, 0), output: pbNum(uf, 2), cacheRead: cr, cacheWrite: cw, reasoning: pbNum(uf, 5) } } +// A step that calls the caller's tools has no TurnEndedUpdate: Cursor ends +// the turn, and tells what it used, only once the client has run the tools +// and sent their results in the same Run, and the caller runs them after +// the Run is closed (magpie #676). Before that it sends nothing more than +// the conversation's checkpoint and heartbeats, and a cancelled Run ends +// with an error and no usage either. The dashboard's usage events count +// every Run, by its conversation_id, the uncached input apart from what +// was read from the cache and written to it, as TurnEndedUpdate does; one +// shows about 2.5 s after the Run is closed. STEP_WAIT is how long a step's +// is looked for: first after that long, then every so often until the +// end, after which it is guessed as before. +const STEP_WAIT = { first: 1500, every: 500, until: 6000 } + +// claimed are the usage events already counted, by conversation and time, +// so that two steps of one conversation never count the same one. +const claimed = new Map() + +// stepUsage is the usage of the Run of conversation conv started at since, +// as the dashboard's usage events count it; null when none shows in time. +async function stepUsage(tok, conv, since, signal) { + const end = Date.now() + STEP_WAIT.until + const wait = (ms) => new Promise((r) => { + const t = setTimeout(r, ms) + signal?.addEventListener("abort", () => (clearTimeout(t), r()), { once: true }) + }) + for (const [k, at] of claimed) if (Date.now() - at > 600_000) claimed.delete(k) + await wait(STEP_WAIT.first) + const num = (v) => (Number.isFinite(Number(v)) ? Number(v) : 0) + while (!signal?.aborted) { + try { + const res = await fetch(API + "/aiserver.v1.DashboardService/GetFilteredUsageEvents", { + method: "POST", + headers: await headersFor(tok), + body: JSON.stringify({ teamId: 0, startDate: String(since - 60_000), endDate: String(Date.now() + 60_000), page: 1, pageSize: 50 }), + signal: AbortSignal.timeout(5000), + }) + if (res.status >= 400 && res.status < 500 && res.status !== 429) return null // not this account's to read + const evs = res.ok ? ((await res.json())?.usageEventsDisplay ?? []) : [] + const ev = evs + .filter((e) => e?.conversationId === conv && e.tokenUsage && num(e.timestamp) >= since - 1000 && !claimed.has(conv + "\0" + e.timestamp)) + .sort((a, b) => num(a.timestamp) - num(b.timestamp))[0] + if (ev) { + claimed.set(conv + "\0" + ev.timestamp, Date.now()) + const t = ev.tokenUsage + return { input: num(t.inputTokens), output: num(t.outputTokens), cacheRead: num(t.cacheReadTokens), cacheWrite: num(t.cacheWriteTokens), reasoning: 0 } + } + } catch {} + if (Date.now() + STEP_WAIT.every > end) return null + await wait(STEP_WAIT.every) + } + return null +} + // buildRun is the Run's first message, an AgentClientMessage with its // run_request, and the blobs it names. The conversation state is the // messages and one turn, which the server wants there to sample at all. @@ -1275,7 +1328,11 @@ function open(base, headers, signal) { // runOnce is one Run of the chat on the agent API at base: an async // iterator of the answer's pieces, or the error it failed with before any. async function runOnce({ tok, base, id, tools, conv, convID, signal, maxMode, params }) { - const { first, blobs } = buildRun(conv.msgs, conv.last, tools, id, convID, { maxMode, params }) + // the Run's conversation_id, a new one when nothing names the session: + // its usage event is found by it + const cid = convID || randomUUID() + const since = Date.now() + const { first, blobs } = buildRun(conv.msgs, conv.last, tools, id, cid, { maxMode, params }) const o = await open( base, { @@ -1318,7 +1375,14 @@ async function runOnce({ tok, base, id, tools, conv, convID, signal, maxMode, pa close() return { error: failure(o.status, Buffer.concat(chunks).toString("utf8").slice(0, 1 << 20)) } } - const it = decode(frames(req), { send, blobs, tools, estimate: conv.estimate }) + const it = decode(frames(req), { + send, + blobs, + tools, + estimate: conv.estimate, + close, + stepUsage: () => stepUsage(tok, cid, since, signal), + }) const wrapped = (async function* () { try { yield* it @@ -1344,8 +1408,10 @@ async function runOnce({ tok, base, id, tools, conv, convID, signal, maxMode, pa // decode follows the server's messages into the answer's pieces until the // turn ends, or the model has made its tool calls. -async function* decode(stream, { send, blobs, tools, estimate }) { +async function* decode(stream, { send, blobs, tools, estimate, close, stepUsage }) { let calls = 0 + // ended: Cursor said what the turn used + let ended = false let listed = 0 let said = 0 // wrote: the reply's text alone; a turn of thinking only says nothing @@ -1368,6 +1434,16 @@ async function* decode(stream, { send, blobs, tools, estimate }) { }, } } + // settled is finish once a step that called tools has its usage: the + // dashboard's count, the Run closed first, when the turn didn't end + const settled = async () => { + if (calls > 0 && !ended && stepUsage) { + close?.() + const u = await stepUsage().catch(() => null) + if (u) usage = u + } + return finish() + } const closeExec = (id) => send(pb().bytes(5, pb().bytes(1, pb().varint(1, id))).done()) try { for await (const f of stream) { @@ -1375,7 +1451,7 @@ async function* decode(stream, { send, blobs, tools, estimate }) { const e = failure(200, f.data) if (e.status < 200 || e.status > 299) yield { error: e } else if (wrote === 0 && calls === 0) yield { error: { status: 502, message: "an empty reply" } } - else yield finish() + else yield await settled() return } for (const m of fields(f.data)) { @@ -1405,6 +1481,7 @@ async function* decode(stream, { send, blobs, tools, estimate }) { } case 14: // turn ended, with what it used usage = usageOf(uf) + ended = true if (calls === 0) { // nothing written and nothing called: an empty reply, // which the client asks again, not a finished turn @@ -1415,7 +1492,7 @@ async function* decode(stream, { send, blobs, tools, estimate }) { case 27: // how many tool calls the step makes, sent before them listed = pbNum(uf, 1) if (listed > 0 && calls >= listed) { - yield finish() + yield await settled() return } break @@ -1431,7 +1508,7 @@ async function* decode(stream, { send, blobs, tools, estimate }) { } if (listed > 0 && calls >= listed) { // every call made: the caller runs them - yield finish() + yield await settled() return } break @@ -1457,13 +1534,13 @@ async function* decode(stream, { send, blobs, tools, estimate }) { } } if (calls > 0) { - yield finish() + yield await settled() return } yield { error: { status: 502, message: "the reply broke off: EOF" } } } catch (e) { if (calls > 0 && /EOF/.test(e?.message ?? "")) { - yield finish() + yield await settled() return } yield { error: { status: 502, message: "the reply broke off: " + (e?.message ?? e) } } @@ -1733,4 +1810,4 @@ export async function CursorAuthPlugin() { } // for tests -export const _internal = { catalog, usable, maxRequired, conversationID, usageOf, sessionOf, SESSION, errorResponse, kept, poolBase, splitID, families, byEffort, offered, modelID, conversation, buildRun, decode, exec, fields, pb, pbValue, pbAny, frame, frames, failure, toolsOf, expiry } +export const _internal = { STEP_WAIT, stepUsage, catalog, usable, maxRequired, conversationID, usageOf, sessionOf, SESSION, errorResponse, kept, poolBase, splitID, families, byEffort, offered, modelID, 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 2df0591..7c5fdce 100644 --- a/packages/cursor/package.json +++ b/packages/cursor/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-cursor-auth", - "version": "0.1.8", + "version": "0.1.9", "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/stepusage.test.mjs b/packages/cursor/stepusage.test.mjs new file mode 100644 index 0000000..044811a --- /dev/null +++ b/packages/cursor/stepusage.test.mjs @@ -0,0 +1,99 @@ +// A step that calls the caller's tools has no TurnEndedUpdate before the +// Run is closed, so its usage is the dashboard's usage event of the Run's +// conversation (yetone/magpie#676): read, not guessed with no cache. +import "./nonet.mjs" // first: no request leaves this machine +import { afterEach, expect, test } from "bun:test" +import { _internal } from "./index.mjs" + +const { pb, decode, stepUsage, STEP_WAIT } = _internal + +const real = globalThis.fetch +const wait = { ...STEP_WAIT } +afterEach(() => { + globalThis.fetch = real + Object.assign(STEP_WAIT, wait) +}) + +const update = (num, body) => ({ data: pb().bytes(1, pb().bytes(num, body)).done() }) +// the server's call of the caller's tool cache_probe, as Cursor sends it +const call = { + data: pb() + .bytes(2, pb().varint(1, 7).str(15, "x1").bytes(11, pb().str(1, "magpie-cache_probe").str(3, "call_1").str(5, "cache_probe").done()).done()) + .done(), +} +const listed = update(27, pb().varint(1, 1).done()) + +async function run(frames, opts) { + const out = [] + for await (const p of decode(frames, { send() {}, blobs: new Map(), tools: [], estimate: 2395, ...opts })) out.push(p) + return out +} + +test("a step that calls tools takes the dashboard's count of its Run", async () => { + const seen = [] + const out = await run([update(1, pb().str(1, "probing").done()), listed, call], { + close: () => seen.push("close"), + stepUsage: async () => (seen.push("usage"), { input: 41, output: 133, cacheRead: 4224, cacheWrite: 0, reasoning: 0 }), + }) + // the Run closed before the count is asked for + expect(seen).toEqual(["close", "usage"]) + expect(out.at(-1)).toEqual({ + stop: "tool_calls", + usage: { + prompt_tokens: 4265, + completion_tokens: 133, + total_tokens: 4398, + prompt_tokens_details: { cached_tokens: 4224, cache_write_tokens: 0 }, + }, + }) +}) + +test("a count Cursor gave, or none to be had, is as before", async () => { + let asked = 0 + const stepUsage = async () => (asked++, null) + // the turn ended with fewer calls than listed: its own count + const two = update(27, pb().varint(1, 2).done()) + const end = { end: true, data: Buffer.from("{}") } + let out = await run([two, call, update(14, pb().varint(1, 900).varint(2, 3).varint(3, 800).done()), end], { stepUsage }) + expect(asked).toBe(0) + expect(out.at(-1).usage.prompt_tokens_details.cached_tokens).toBe(800) + // no event in time: the guess + out = await run([listed, call], { stepUsage }) + expect(asked).toBe(1) + expect(out.at(-1).usage.prompt_tokens).toBe(2395) + // a text turn never asks + out = await run([update(1, pb().str(1, "READY").done()), update(14, pb().varint(1, 10).varint(2, 1).done())], { stepUsage }) + expect(asked).toBe(1) + expect(out.at(-1).stop).toBe("stop") +}) + +test("stepUsage finds the Run's event by its conversation and time, once", async () => { + Object.assign(STEP_WAIT, { first: 0, every: 10, until: 200 }) + const since = Date.now() + const conv = "3ca0f6c1-b4a9-4991-9ae4-349bb3951caa" + const ev = (dt, c, t) => ({ timestamp: String(since + dt), model: "grok-4.7-medium-fast", conversationId: c, tokenUsage: t }) + let shows = 2 // the event shows on the third ask + const asks = [] + globalThis.fetch = async (url, init) => { + asks.push({ url: String(url), body: JSON.parse(init.body), auth: init.headers.Authorization }) + return Response.json({ + usageEventsDisplay: [ + ev(2500, "another-conversation", { inputTokens: 9, outputTokens: 9 }), + ev(-30_000, conv, { inputTokens: 8, outputTokens: 8 }), // an earlier Run of it + ...(shows-- > 0 ? [] : [ev(2600, conv, { inputTokens: 41, outputTokens: 261, cacheReadTokens: 4224 })]), + ], + }) + } + expect(await stepUsage("tok", conv, since)).toEqual({ input: 41, output: 261, cacheRead: 4224, cacheWrite: 0, reasoning: 0 }) + expect(asks.length).toBe(3) + expect(asks[0].url).toBe("https://api2.cursor.sh/aiserver.v1.DashboardService/GetFilteredUsageEvents") + expect(asks[0].auth).toBe("Bearer tok") + expect(Number(asks[0].body.startDate)).toBeLessThan(since) + // counted once: another step of the conversation doesn't take it again + expect(await stepUsage("tok", conv, since)).toBe(null) + // an account that can't read the events isn't asked again + asks.length = 0 + globalThis.fetch = async () => (asks.push(1), new Response("{}", { status: 403 })) + expect(await stepUsage("tok", conv, since)).toBe(null) + expect(asks.length).toBe(1) +})