From 288c6bc9c9adb3adadc2eab6f7768ff333aa6afb Mon Sep 17 00:00:00 2001 From: yetone Date: Wed, 7 Oct 2026 03:17:08 +0800 Subject: [PATCH] =?UTF-8?q?cursor=200.1.10:=20far=20from=20Cursor=20a=20co?= =?UTF-8?q?nversation's=20tool=20steps=20add=20up=20to=20what=20Cursor=20c?= =?UTF-8?q?ounted,=20cache=20included=20(yetone/magpie#1053,=20#33).=20The?= =?UTF-8?q?=20tool-step=20usage-event=20wait=20of=200.1.9=20(first=20ask?= =?UTF-8?q?=20at=201.5=20s,=20every=200.5=20s,=20up=20to=206=20s)=20never?= =?UTF-8?q?=20met=20an=20event=20on=20the=20reporter's=20network=20(Window?= =?UTF-8?q?s,=20mainland=20China:=20a=20GetFilteredUsageEvents=20round=20t?= =?UTF-8?q?rip=20of=20~4.2=20s,=20the=20event=204=E2=80=935=20s=20after=20?= =?UTF-8?q?the=20Run=20closes),=20so=20tool=20steps=20were=20counted=20as?= =?UTF-8?q?=20their=20whole=20prompt=20estimated=20with=20no=20cache=20(fa?= =?UTF-8?q?ble=2013/13=20steps,=200%=20cached;=20opus=2027%)=20where=20Cur?= =?UTF-8?q?sor=20counted=2095=E2=80=9399%,=20and=20every=20tool=20step=20w?= =?UTF-8?q?aited=20the=20full=206=20s.=20A=20tool=20step's=20Run=20is=20no?= =?UTF-8?q?w=20owed=20by=20its=20conversation=20(only=20when=20a=20convers?= =?UTF-8?q?ation=5Fid=20names=20the=20session):=20the=20step=20counts=20ev?= =?UTF-8?q?ery=20event=20of=20the=20conversation's=20owed=20Runs=20that=20?= =?UTF-8?q?shows=20within=20the=20same=20wait,=20its=20own=20or=20earlier?= =?UTF-8?q?=20ones,=20and=20says=200=20used=20when=20none=20has;=20the=20c?= =?UTF-8?q?onversation's=20next=20Runs=20collect=20the=20rest=20in=20the?= =?UTF-8?q?=20background=20from=205=20s=20after=20the=20owed=20Run=20close?= =?UTF-8?q?d,=20and=20a=20step=20that=20ends=20the=20turn=20waits=20for=20?= =?UTF-8?q?whatever=20is=20still=20owed=20(in-flight=20collections,=20then?= =?UTF-8?q?=20a=20poll=20for=20the=20rest).=20Events=20are=20claimed=20onc?= =?UTF-8?q?e,=20by=20count,=20so=20the=20conversation's=20prompt,=20cache?= =?UTF-8?q?=20read,=20cache=20write=20and=20output=20add=20up=20to=20Curso?= =?UTF-8?q?r's=20dashboard,=20some=20of=20it=20a=20step=20late.=20After=20?= =?UTF-8?q?3=20steps=20in=20a=20row=20left=20something=20owed=20an=20accou?= =?UTF-8?q?nt's=20tool=20steps=20stop=20waiting=20(asked=20again=20every?= =?UTF-8?q?=2010th).=20A=20Run=20that=20fails=20after=20collecting=20gives?= =?UTF-8?q?=20it=20back;=20an=20account=20that=20can't=20read=20its=20even?= =?UTF-8?q?ts=20(4xx)=20and=20a=20Run=20with=20no=20session=20id=20are=20e?= =?UTF-8?q?stimated=20as=20before.=20latency.test.mjs=20runs=20whole=20con?= =?UTF-8?q?versations=20through=20the=20plugin=20against=20a=20fake=20Curs?= =?UTF-8?q?or=20with=20the=20reporter's=20latency=20scaled=201/20=20and=20?= =?UTF-8?q?the=20reporter's=20literal=20events=20(in=202=20/=20cacheRead?= =?UTF-8?q?=2063457=20/=20cacheWrite=203081,=20in=202=20/=2066538=20/=2014?= =?UTF-8?q?756,=20in=204=20/=2067872=20/=202392):=20on=200.1.9=20the=203-s?= =?UTF-8?q?tep=20conversation=20sums=20to=20137936=20prompt=20/=20131329?= =?UTF-8?q?=20cached=20instead=20of=20218104=20/=20197867,=20and=20skipped?= =?UTF-8?q?=20steps=20still=20wait=20the=20full=20window=20(292=20ms=20>?= =?UTF-8?q?=20150);=20both=20pass=20now,=2020=20of=2020=20runs,=20and=20st?= =?UTF-8?q?epusage=20+=20latency=20pass=20with=20--rerun-each=2020.=20HOME?= =?UTF-8?q?=3D$(mktemp=20-d)=20bun=20test:=20682=20pass,=200=20fail;=20che?= =?UTF-8?q?ck.mjs=20cursor=20passes.=20Not=20tried=20with=20a=20real=20Cur?= =?UTF-8?q?sor=20account=20on=20a=20high-latency=20network.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/cursor/README.md | 10 +- packages/cursor/index.mjs | 243 +++++++++++++++++++++++++---- packages/cursor/latency.test.mjs | 233 +++++++++++++++++++++++++++ packages/cursor/package.json | 2 +- packages/cursor/stepusage.test.mjs | 38 +++++ 5 files changed, 497 insertions(+), 29 deletions(-) create mode 100644 packages/cursor/latency.test.mjs diff --git a/packages/cursor/README.md b/packages/cursor/README.md index 12dacb7..f25d392 100644 --- a/packages/cursor/README.md +++ b/packages/cursor/README.md @@ -58,7 +58,15 @@ plugin's `fetch` answers them on Cursor's agent API: (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. + and is looked for up to 6 s. Far from Cursor it shows later than that + (yetone/magpie#1053), so the step says 0 used and the conversation owes + it: its next steps collect the event in the background and count it + with their own, and a step that ends the turn waits for what is still + owed, so the conversation adds up to what Cursor counted. An account + whose events miss the wait 3 steps in a row stops waiting for them. + With nothing naming the session (so no later step to collect it), or + an account that can't read its usage events, the step 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. diff --git a/packages/cursor/index.mjs b/packages/cursor/index.mjs index a4489ff..bbed100 100644 --- a/packages/cursor/index.mjs +++ b/packages/cursor/index.mjs @@ -1174,47 +1174,218 @@ function usageOf(uf) { // 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 } +// end (each ask given `ask` to answer). +// +// Far from Cursor none shows in that time (yetone/magpie#1053: a round +// trip of 4.2 s, the event 4–5 s after the Run closes), and waiting longer +// would hold every tool step longer. So a tool step's Run is owed by its +// conversation (owed): the step counts every event of the conversation's +// owed Runs that has shown by the end of its wait, its own or earlier +// ones, and what hasn't shown is collected by the conversation's next +// steps, in the background from `owedAt` after the Run closed. A step +// whose count is still owed says 0 used; the conversation's steps add up +// to what Cursor counted, some of it a step or two late. A step that ends +// the turn waits for what is still owed, as nothing may follow it soon. +// After `skipAfter` steps in a row of an account's left something owed, +// its steps stop waiting (but every `retryEvery`th), and leave it to the +// next. A debt not collected in `owedFor` is let go. With no +// conversation_id naming the session nothing later could collect a Run's +// event: its step looks for it as before, and is guessed without it. +const STEP_WAIT = { first: 1500, every: 500, until: 6000, ask: 5000, skipAfter: 3, retryEvery: 10, owedAt: 5000, owedFor: 600_000 } // 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) { +// owed are what each conversation still owes, by conversation_id: n Runs +// whose events are to be counted, the earliest started at since, looked +// for from ready on; and carry, a count collected that no step gave out. +const owed = new Map() + +// flights are each conversation's collections still going, which a step +// that ends the turn waits for. +const flights = new Map() + +// unreadable are the accounts (by token) whose usage events Cursor won't +// give (a 4xx), for owedFor: their steps are guessed, as before, and owe +// nothing. misses are how many steps in a row of an account's left +// something owed. +const unreadable = new Map() +const misses = new Map() +const tokKey = (tok) => createHash("sha256").update(tok).digest("hex") +function canRead(tok) { + const at = unreadable.get(tokKey(tok)) + if (at === undefined) return true + if (Date.now() - at < STEP_WAIT.owedFor) return false + unreadable.delete(tokKey(tok)) + return true +} + +const ZERO = () => ({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0, reasoning: 0 }) +function addUsage(a, b) { + if (!b) return a + if (!a) return { ...b } + for (const k of Object.keys(a)) a[k] += b[k] ?? 0 + return a +} + +// owe adds to conversation conv's debt. +function owe(conv, { since = Date.now(), n = 0, ready = Date.now(), carry = null }) { + for (const [k, d] of owed) if (Date.now() - d.since > STEP_WAIT.owedFor) owed.delete(k) + if (n <= 0 && !carry) return + const d = owed.get(conv) + if (!d) return void owed.set(conv, { since, n, ready, carry: carry && { ...carry } }) + d.since = Math.min(d.since, since) + d.n += n + d.ready = Math.min(d.ready, ready) + d.carry = addUsage(d.carry, carry) +} + +// usageEvents are the dashboard's events of conversation conv from since +// on, the `want` oldest not counted yet, summed: usage (null when none), +// how many were found (got), and refused when the account can't read them. +// Polling, they are looked for as STEP_WAIT says, from `first` on, until +// all show; else asked for once. +async function usageEvents(tok, conv, since, want, { poll = false, first = STEP_WAIT.first, 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) + for (const [k, at] of claimed) if (Date.now() - at > 2 * STEP_WAIT.owedFor) claimed.delete(k) const num = (v) => (Number.isFinite(Number(v)) ? Number(v) : 0) + let usage = null + let got = 0 + if (poll) await wait(first) 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), + signal: AbortSignal.timeout(STEP_WAIT.ask), }) - if (res.status >= 400 && res.status < 500 && res.status !== 429) return null // not this account's to read + if (res.status >= 400 && res.status < 500 && res.status !== 429) { + // not this account's to read + unreadable.set(tokKey(tok), Date.now()) + return { usage, got, refused: true } + } const evs = res.ok ? ((await res.json())?.usageEventsDisplay ?? []) : [] - const ev = evs + const found = 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) { + .sort((a, b) => num(a.timestamp) - num(b.timestamp)) + .slice(0, want - got) + for (const ev of found) { 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 } + usage = addUsage(usage ?? ZERO(), { input: num(t.inputTokens), output: num(t.outputTokens), cacheRead: num(t.cacheReadTokens), cacheWrite: num(t.cacheWriteTokens) }) + got++ } + if (got >= want) break } catch {} - if (Date.now() + STEP_WAIT.every > end) return null + if (!poll || Date.now() + STEP_WAIT.every > end) break await wait(STEP_WAIT.every) } - return null + return { usage, got, refused: false } +} + +// 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) { + return (await usageEvents(tok, conv, since, 1, { poll: true, signal })).usage +} + +// collect takes conversation conv's debt and asks for its events (polling +// when poll): what was carried and what was found (usage), and whether +// any is still owed (short), which is owed on. What comes back once the +// Run that asked is over (over() true) is carried to the next instead. +function collect(tok, conv, { poll = false, first, signal, over = () => false } = {}) { + const d = owed.get(conv) + if (!d) return Promise.resolve({ usage: null, short: false }) + owed.delete(conv) + const p = (async () => { + let r = { usage: null, got: 0 } + if (d.n > 0 && canRead(tok)) r = await usageEvents(tok, conv, d.since, d.n, { poll, first, signal }).catch(() => r) + const short = d.n > r.got && canRead(tok) + if (short) owe(conv, { since: d.since, n: d.n - r.got, ready: d.ready }) + const usage = addUsage(d.carry, r.usage) + if (!over()) return { usage, short } + owe(conv, { carry: usage }) + return { usage: null, short } + })() + const set = flights.get(conv) ?? new Set() + flights.set(conv, set.add(p)) + p.finally(() => { + set.delete(p) + if (!set.size && flights.get(conv) === set) flights.delete(conv) + }) + return p +} + +// ledger is how a Run of conversation conv, started at since, has its +// usage counted, for decode; kept when the conversation_id names the +// session, so that a later Run of it can collect what this one owes. A +// debt the conversation has is collected in the background. own() is a +// step's count once it has called tools: its Run owed, what has shown of +// the debt by the end of the wait (or at once, when the account's never +// show in time); false when nothing has, null when the step is to be +// guessed (not kept, and its event not found, or an account that can't +// read its events). owed(final) is what the Run collected otherwise, +// all that can be had when final. done() ends the Run: what was collected +// and not given out goes back. +function ledger(tok, conv, since, signal, kept) { + const key = tokKey(tok) + let pending = null // collected, not given out yet + let over = false + const gather = (opts) => + collect(tok, conv, { ...opts, over: () => over }).then((r) => { + pending = addUsage(pending, r.usage) + return r + }) + let collecting = null + const debt = kept ? owed.get(conv) : undefined + const timer = debt ? setTimeout(() => (collecting = gather()), Math.max(0, debt.ready - Date.now())) : null + timer?.unref?.() + const take = () => { + const u = pending + pending = null + return u + } + return { + async own() { + if (!canRead(tok)) return null + const m = misses.get(key) ?? 0 + const waits = m < STEP_WAIT.skipAfter || m % STEP_WAIT.retryEvery === 0 + if (!kept) { + const r = waits ? await usageEvents(tok, conv, since, 1, { poll: true, signal }).catch(() => ({})) : {} + if (r.usage) misses.delete(key) + else if (!r.refused) misses.set(key, m + 1) + return r.usage ?? null + } + owe(conv, { since, n: 1, ready: Date.now() + STEP_WAIT.owedAt }) + if (waits) { + const r = await gather({ poll: true, signal }) + if (!canRead(tok)) return null + if (r.short) misses.set(key, m + 1) + else misses.delete(key) + } else misses.set(key, m + 1) + return take() ?? false + }, + async owed(final) { + if (!kept) return null + if (final) { + await collecting + await Promise.all([...(flights.get(conv) ?? [])]) + if (owed.has(conv)) await gather({ poll: owed.get(conv).n > 0, first: 0, signal }) + } + return take() + }, + done() { + over = true + clearTimeout(timer) + if (pending) owe(conv, { carry: take() }) + }, + } } // buildRun is the Run's first message, an AgentClientMessage with its @@ -1332,6 +1503,10 @@ async function runOnce({ tok, base, id, tools, conv, convID, signal, maxMode, pa // its usage event is found by it const cid = convID || randomUUID() 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 + // could have run up + const book = ledger(tok, cid, since, signal, !!convID) const { first, blobs } = buildRun(conv.msgs, conv.last, tools, id, cid, { maxMode, params }) const o = await open( base, @@ -1348,7 +1523,7 @@ async function runOnce({ tok, base, id, tools, conv, convID, signal, maxMode, pa }, signal, ) - if (o.error) return o + if (o.error) return book.done(), o const { session, req } = o let closed = false const send = (msg) => { @@ -1373,6 +1548,7 @@ async function runOnce({ tok, base, id, tools, conv, convID, signal, maxMode, pa for await (const c of req) chunks.push(c) } catch {} close() + book.done() return { error: failure(o.status, Buffer.concat(chunks).toString("utf8").slice(0, 1 << 20)) } } const it = decode(frames(req), { @@ -1381,19 +1557,21 @@ async function runOnce({ tok, base, id, tools, conv, convID, signal, maxMode, pa tools, estimate: conv.estimate, close, - stepUsage: () => stepUsage(tok, cid, since, signal), + stepUsage: book.own, + owedUsage: book.owed, }) const wrapped = (async function* () { try { yield* it } finally { close() + book.done() } })() // an error comes before anything of the answer: out of quota, a model the // plan doesn't have — answered with its own status const head = await wrapped.next() - if (head.done) return { error: { status: 502, message: "an empty reply" } } + if (head.done) return book.done(), { error: { status: 502, message: "an empty reply" } } if (head.value.error) { await wrapped.return() return { error: head.value.error } @@ -1408,7 +1586,7 @@ 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, close, stepUsage }) { +async function* decode(stream, { send, blobs, tools, estimate, close, stepUsage, owedUsage }) { let calls = 0 // ended: Cursor said what the turn used let ended = false @@ -1417,11 +1595,19 @@ async function* decode(stream, { send, blobs, tools, estimate, close, stepUsage // wrote: the reply's text alone; a turn of thinking only says nothing let wrote = 0 let usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, reasoning: 0 } - const finish = () => { - if (!usage.output) usage.output = Math.floor((said + 3) / 4) + // counted: the step's usage is the dashboard's events, its own counted + // with it or by a later step (ledger), never guessed + let counted = false + // finish is the step's end, with what earlier steps owed (more), which + // is no reason not to guess the step's own + const finish = (more) => { + if (!counted && !usage.output) usage.output = Math.floor((said + 3) / 4) // a guess only when Cursor counted nothing: a prompt read whole from - // the cache leaves no uncached rest, and is no reason to guess - if (!usage.input && !usage.cacheRead && !usage.cacheWrite) usage.input = estimate + // the cache leaves no uncached rest, and is no reason to guess; nor is + // a prompt counted from the events + if (!counted && !usage.input && !usage.cacheRead && !usage.cacheWrite) usage.input = estimate + // the events' output is their steps', counted here as their prompt is + if (more) for (const k of ["input", "output", "cacheRead", "cacheWrite"]) usage[k] += more[k] const prompt = usage.input + usage.cacheRead + usage.cacheWrite return { stop: calls > 0 ? "tool_calls" : "stop", @@ -1435,14 +1621,17 @@ async function* decode(stream, { send, blobs, tools, estimate, close, stepUsage } } // 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 + // dashboard's count, the Run closed first, when the turn didn't end (or + // owed); and with what the conversation's earlier steps owed, which a + // step that ends the turn waits for const settled = async () => { if (calls > 0 && !ended && stepUsage) { close?.() const u = await stepUsage().catch(() => null) if (u) usage = u + counted = u === false || !!u } - return finish() + return finish(owedUsage ? await owedUsage(calls === 0).catch(() => null) : null) } const closeExec = (id) => send(pb().bytes(5, pb().bytes(1, pb().varint(1, id))).done()) try { @@ -1485,7 +1674,7 @@ async function* decode(stream, { send, blobs, tools, estimate, close, stepUsage if (calls === 0) { // nothing written and nothing called: an empty reply, // which the client asks again, not a finished turn - yield wrote === 0 ? { error: { status: 502, message: "an empty reply" } } : finish() + yield wrote === 0 ? { error: { status: 502, message: "an empty reply" } } : await settled() return } break @@ -1810,4 +1999,4 @@ export async function CursorAuthPlugin() { } // for tests -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 } +export const _internal = { STEP_WAIT, stepUsage, ledger, owed, flights, misses, unreadable, 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/latency.test.mjs b/packages/cursor/latency.test.mjs new file mode 100644 index 0000000..d20c3a4 --- /dev/null +++ b/packages/cursor/latency.test.mjs @@ -0,0 +1,233 @@ +// Far from Cursor (yetone/magpie#1053, plugins#33: Windows in mainland +// China) a GetFilteredUsageEvents round trip takes about 4.2 s and a Run's +// usage event shows 4–5 s after the Run is closed, so a tool step's event +// never showed inside STEP_WAIT: every tool step was counted as its whole +// prompt guessed, uncached (Claude Code on fable: 13 of 13 steps, 0% +// cached, where Cursor counted 95–99%). These run whole conversations +// through the plugin against a fake Cursor with that latency, every time +// scaled down twentyfold: its API by a stand-in fetch, its agent API by +// an HTTP/2 server here. Nothing reaches Cursor. +import "./nonet.mjs" // first: no request leaves this machine +import { afterAll, afterEach, beforeAll, beforeEach, expect, test } from "bun:test" +import http2 from "node:http2" +import { CursorAuthPlugin, _internal } from "./index.mjs" + +const { fields, pb, frame, STEP_WAIT } = _internal + +// a twentieth of the reporter's times: the round trip, and how long after +// the Run is closed its event shows +const SCALE = 20 +const RTT = 4200 / SCALE +const SHOWS = 4500 / SCALE + +const real = globalThis.fetch +const wait = { ...STEP_WAIT } +beforeEach(() => { + // the times, not the counts; a debt is let go as before + for (const k of ["first", "every", "until", "ask", "owedAt"]) if (k in wait) STEP_WAIT[k] = wait[k] / SCALE + _internal.owed?.clear() + _internal.misses?.clear() + _internal.unreadable?.clear() +}) +afterEach(() => { + globalThis.fetch = real + Object.assign(STEP_WAIT, wait) +}) + +const jwt = (exp) => ["e30", Buffer.from(JSON.stringify({ exp, sub: "latency-" + Math.random() })).toString("base64url"), "sig"].join(".") +let n = 0 +const fresh = () => ({ type: "oauth", access: jwt(Math.floor(Date.now() / 1000) + 7200 + ++n), refresh: "", expires: 0, accountId: "a@b.c" }) + +// The reporter's three dashboard events (fable twice, opus), in the order +// of their Runs. Each step of a conversation here takes the next one: a +// tool step tells it only through the dashboard, a step that ends the +// turn in its TurnEndedUpdate too (whose input counts the cache in). +const CURSOR = [ + { inputTokens: 2, outputTokens: 621, cacheReadTokens: 63457, cacheWriteTokens: 3081 }, + { inputTokens: 2, outputTokens: 942, cacheReadTokens: 66538, cacheWriteTokens: 14756 }, + { inputTokens: 4, outputTokens: 151, cacheReadTokens: 67872, cacheWriteTokens: 2392 }, +] + +// the agent API: a Run answers a tool call (listed first, as Cursor does) +// and waits for the client to close it, or ends the turn with its usage. +// A closed Run's event shows on the dashboard SHOWS later, stamped then. +let server, base +let script = [] // per Run: "tool" or "end", with its CURSOR usage +const shown = [] // the dashboard's events +beforeAll(async () => { + server = http2.createServer() + server.on("stream", (stream) => { + stream.respond({ ":status": 200, "content-type": "application/connect+proto" }) + let buf = Buffer.alloc(0) + let step + stream.on("data", (c) => { + buf = Buffer.concat([buf, c]) + if (step || buf.length < 5 || buf.length < 5 + buf.readUInt32BE(1)) return + const rr = fields(fields(buf.subarray(5, 5 + buf.readUInt32BE(1))).find((f) => f.num === 1).data) + step = { conv: rr.find((f) => f.num === 5)?.data.toString(), ...script.shift() } + const update = (num, body) => frame(pb().bytes(1, pb().bytes(num, body)).done()) + if (step.kind === "tool") { + stream.write(update(1, pb().str(1, "probing").done())) + stream.write(update(27, pb().varint(1, 1).done())) + stream.write( + frame(pb().bytes(2, pb().varint(1, 7).str(15, "x1").bytes(11, pb().str(1, "magpie-Read").str(3, "call_" + n++).str(5, "Read").done()).done()).done()), + ) + return // the client closes it, to run the tool + } + const u = step.usage + stream.write(update(1, pb().str(1, "done").done())) + const whole = u.inputTokens + u.cacheReadTokens + u.cacheWriteTokens + stream.write(update(14, pb().varint(1, whole).varint(2, u.outputTokens).varint(3, u.cacheReadTokens).varint(4, u.cacheWriteTokens).done())) + const end = Buffer.from("{}") + const head = Buffer.alloc(5) + head[0] = 2 + head.writeUInt32BE(end.length, 1) + stream.end(Buffer.concat([head, end])) + }) + stream.on("close", () => { + if (!step?.usage) return + setTimeout(() => shown.push({ timestamp: String(Date.now()), model: "claude-fable-5-thinking-max", conversationId: step.conv, tokenUsage: step.usage }), SHOWS) + }) + stream.on("error", () => {}) + }) + await new Promise((r) => server.listen(0, "127.0.0.1", r)) + base = `http://127.0.0.1:${server.address().port}` +}) +afterAll(() => server.close()) + +// Cursor's API, every answer RTT after it was asked: the dashboard's +// events as they stood when the question reached it (halfway) +let asks = 0 +function fakeAPI() { + globalThis.fetch = async (url, init) => { + const u = String(url) + if (u === "https://api2.cursor.sh/aiserver.v1.ServerConfigService/GetServerConfig") return Response.json({ agentUrlConfig: { agentUrl: base } }) + if (u === "https://api2.cursor.sh/agent.v1.AgentService/GetUsableModels") return Response.json({ models: [{ modelId: "claude-fable-5-thinking", displayName: "Fable" }] }) + if (u === "https://api2.cursor.sh/aiserver.v1.DashboardService/GetFilteredUsageEvents") { + asks++ + const timeout = init?.signal + const sleep = (ms) => + new Promise((r, j) => { + const t = setTimeout(r, ms) + timeout?.addEventListener("abort", () => (clearTimeout(t), j(timeout.reason)), { once: true }) + }) + await sleep(RTT / 2) + const evs = shown.map((e) => ({ ...e })) + await sleep(RTT / 2) + return Response.json({ usageEventsDisplay: evs.reverse() }) + } + throw new Error("the test asked " + u) + } +} + +// one step of the conversation, as Claude Code sends it through magpie +async function ask(auth, chat, session) { + const hooks = await CursorAuthPlugin() + const out = { headers: {} } + await hooks["chat.headers"]({ sessionID: session, model: { providerID: "cursor", id: chat.model }, provider: { info: { id: "cursor" } } }, out) + const l = await hooks.auth.loader(async () => auth) + const t0 = Date.now() + const res = await l.fetch(base + "/v1/chat/completions", { method: "POST", headers: new Headers(out.headers), body: JSON.stringify(chat) }) + const j = await res.json() + expect([res.status, j.error]).toEqual([200, undefined]) + return { stop: j.choices[0].finish_reason, usage: j.usage, ms: Date.now() - t0 } +} + +const chat = (steps) => { + const messages = [{ role: "user", content: "read the repo and fix the bug " + "x".repeat(4000) }] + for (let i = 0; i < steps; i++) + messages.push( + { role: "assistant", content: "", tool_calls: [{ id: "call_" + i, type: "function", function: { name: "Read", arguments: "{}" } }] }, + { role: "tool", tool_call_id: "call_" + i, content: "file " + i + " " + "y".repeat(4000) }, + ) + return { model: "claude-fable-5-thinking", messages, tools: [{ type: "function", function: { name: "Read", parameters: { type: "object" } } }] } +} + +const sum = (us) => + us.reduce( + (a, u) => ({ + prompt: a.prompt + u.prompt_tokens, + cached: a.cached + u.prompt_tokens_details.cached_tokens, + written: a.written + u.prompt_tokens_details.cache_write_tokens, + }), + { prompt: 0, cached: 0, written: 0 }, + ) +const cursorSum = (evs) => + evs.reduce( + (a, u) => ({ + prompt: a.prompt + u.inputTokens + u.cacheReadTokens + u.cacheWriteTokens, + cached: a.cached + u.cacheReadTokens, + written: a.written + u.cacheWriteTokens, + }), + { prompt: 0, cached: 0, written: 0 }, + ) + +test("far from Cursor, a conversation's tool steps add up to what Cursor counted, cache and all", async () => { + fakeAPI() + shown.length = 0 + const auth = fresh() + const session = "claude-code-session-1" + script = [ + { kind: "tool", usage: CURSOR[0] }, + { kind: "tool", usage: CURSOR[1] }, + { kind: "end", usage: CURSOR[2] }, + ] + const steps = [] + for (let i = 0; i < 3; i++) steps.push(await ask(auth, chat(i), session)) + expect(steps.map((s) => s.stop)).toEqual(["tool_calls", "tool_calls", "stop"]) + // Cursor counted 95–99% of it from the cache; so does the conversation + expect(sum(steps.map((s) => s.usage))).toEqual(cursorSum(CURSOR)) + // and no step waited longer than it did before + for (const s of steps) expect(s.ms).toBeLessThan(STEP_WAIT.until * 2.5) +}) + +test("an account whose events never show in time stops waiting for them, and the count still adds up", async () => { + fakeAPI() + shown.length = 0 + const auth = fresh() + const session = "claude-code-session-2" + const evs = Array.from({ length: 6 }, (_, i) => CURSOR[i % 2]) + script = [...evs.map((usage) => ({ kind: "tool", usage })), { kind: "end", usage: CURSOR[2] }] + const steps = [] + for (let i = 0; i < 7; i++) steps.push(await ask(auth, chat(i), session)) + // after skipAfter misses in a row a tool step no longer waits + const tools = steps.slice(0, 6) + expect(Math.max(...tools.slice(STEP_WAIT.skipAfter).map((s) => s.ms))).toBeLessThan(STEP_WAIT.until / 2) + expect(sum(steps.map((s) => s.usage))).toEqual(cursorSum([...evs, CURSOR[2]])) +}) + +test("with nothing naming the session a tool step is guessed, as before: nothing could collect it later", async () => { + fakeAPI() + shown.length = 0 + const auth = fresh() + script = [{ kind: "tool", usage: CURSOR[0] }] + const s = await ask(auth, chat(0), "") + expect(s.stop).toBe("tool_calls") + expect(s.usage.prompt_tokens).toBeGreaterThan(1000) // the estimate + expect(s.usage.prompt_tokens_details).toEqual({ cached_tokens: 0, cache_write_tokens: 0 }) +}) + +test("near Cursor a tool step still counts its own Run", async () => { + fakeAPI() + shown.length = 0 + const auth = fresh() + // the event shows at once, the round trip short + const keep = STEP_WAIT.until + script = [{ kind: "tool", usage: CURSOR[0] }] + const fast = globalThis.fetch + globalThis.fetch = async (url, init) => { + if (String(url).endsWith("GetFilteredUsageEvents")) { + await new Promise((r) => setTimeout(r, SHOWS + 5)) + return Response.json({ usageEventsDisplay: shown }) + } + return fast(url, init) + } + const s = await ask(auth, chat(0), "near-session") + expect(STEP_WAIT.until).toBe(keep) + expect(s.usage).toEqual({ + prompt_tokens: 2 + 63457 + 3081, + completion_tokens: 621, + total_tokens: 2 + 63457 + 3081 + 621, + prompt_tokens_details: { cached_tokens: 63457, cache_write_tokens: 3081 }, + }) +}) diff --git a/packages/cursor/package.json b/packages/cursor/package.json index 7c5fdce..b2a617b 100644 --- a/packages/cursor/package.json +++ b/packages/cursor/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-cursor-auth", - "version": "0.1.9", + "version": "0.1.10", "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 index 044811a..190a7ab 100644 --- a/packages/cursor/stepusage.test.mjs +++ b/packages/cursor/stepusage.test.mjs @@ -97,3 +97,41 @@ test("stepUsage finds the Run's event by its conversation and time, once", async expect(await stepUsage("tok", conv, since)).toBe(null) expect(asks.length).toBe(1) }) + +// yetone/magpie#1053: a step's count can be owed to a later step of its +// conversation (ledger); latency.test.mjs runs whole conversations +test("an account that can't read its events is guessed as before, and owes nothing", async () => { + const { ledger, owed, unreadable, misses } = _internal + Object.assign(STEP_WAIT, { first: 0, every: 10, until: 60 }) + const conv = "6b5568d9-0000-4000-8000-000000000003" + let asks = 0 + globalThis.fetch = async () => (asks++, new Response("{}", { status: 403 })) + const out = await run([listed, call], { stepUsage: ledger("tok-403", conv, Date.now(), undefined, true).own }) + expect(out.at(-1).usage.prompt_tokens).toBe(2395) + expect(owed.has(conv)).toBe(false) + // nor asked again for a while + expect(await ledger("tok-403", conv, Date.now(), undefined, true).own()).toBe(null) + expect(asks).toBe(1) + unreadable.clear() + misses.clear() +}) + +test("what a Run collected and never gave out goes to the conversation's next step", async () => { + const { ledger, owed } = _internal + Object.assign(STEP_WAIT, { first: 0, every: 10, until: 60 }) + const conv = "6b5568d9-0000-4000-8000-000000000004" + const since = Date.now() + globalThis.fetch = async () => + Response.json({ usageEventsDisplay: [{ timestamp: String(since + 4000), conversationId: conv, tokenUsage: { inputTokens: 2, outputTokens: 621, cacheReadTokens: 63457, cacheWriteTokens: 3081 } }] }) + owed.set(conv, { since, n: 1, ready: since, carry: null }) + // the Run collects the debt, then fails before its step is counted + const failed = ledger("tok", conv, Date.now(), undefined, true) + await new Promise((r) => setTimeout(r, 30)) + failed.done() + expect(owed.get(conv).carry).toEqual({ input: 2, output: 621, cacheRead: 63457, cacheWrite: 3081, reasoning: 0 }) + // the next step that ends the turn has it, once + const next = ledger("tok", conv, Date.now(), undefined, true) + expect(await next.owed(true)).toEqual({ input: 2, output: 621, cacheRead: 63457, cacheWrite: 3081, reasoning: 0 }) + expect(owed.has(conv)).toBe(false) + expect(await ledger("tok", conv, Date.now(), undefined, true).owed(true)).toBe(null) +})