cursor 0.2.11: a step's usage is its own; what it collected of earlier steps is magpie_deferred (#101)
A tool step whose usage event shows after its wait reports 0, and the
conversation's next step collects it. That step used to add it to its own
prompt_tokens, which clients read as context occupancy: pi saw 366940 tokens
(181270 + 185670) on a 300k window and compacted, though 185670 were in use.
Now a step's standard usage fields are its own Run's only. What it collected
of earlier steps goes in usage.magpie_deferred (prompt_tokens,
completion_tokens, cached_tokens, cache_write_tokens), which magpie bills with
the step (yetone/magpie PR) and clients ignore. ledger() also splits collected
events by timestamp: an event stamped from the Run's start on (less 1 s) is
the Run's own; earlier ones and carried counts are deferred. Before, a late
event of an earlier Run could land in a step's own count through gather().
Verified: bun test on packages/cursor, 88 pass (86 before, plus
deferred-usage.test.mjs); bun scripts/check.mjs. With the old index.mjs the
new test fails with Expected 185670, Received 366940. Against real Cursor
(composer-2.5, STEP_WAIT shortened to force late events, 2 rounds) the
deferred totals matched the dashboard's usage events token for token.
The repo-wide bun test has 2 failures in packages/trae that fail the same on
9074723 without this change.
This commit is contained in:
@@ -76,9 +76,13 @@ plugin's `fetch` answers them on Cursor's agent API:
|
||||
usage events, by the Run's conversation id: it shows in about 2.5 s,
|
||||
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
|
||||
it: its next steps collect the event in the background, and a step
|
||||
that ends the turn waits for what is still owed, so the conversation
|
||||
adds up to what Cursor counted. What a step collected of earlier steps
|
||||
is not added to its own count, which a client reads as how full its
|
||||
context is: it is `usage.magpie_deferred` (`prompt_tokens`,
|
||||
`completion_tokens`, `cached_tokens`, `cache_write_tokens`), which
|
||||
magpie bills with the step and clients ignore. 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
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
// A tool step whose usage event shows only after its wait says 0 used,
|
||||
// and the conversation's next step collects it. That step's own count is
|
||||
// its usage; what it collected of the earlier step goes apart, as
|
||||
// magpie_deferred: a client that reads prompt_tokens as how full the
|
||||
// context is (pi, OpenCode) once saw an earlier step's prompt added to
|
||||
// its own, the context twice its size (366940 = 181270 + 185670 on a
|
||||
// 300k window, where 185670 was used).
|
||||
import "./nonet.mjs"
|
||||
import { afterEach, expect, test } from "bun:test"
|
||||
import { _internal } from "./index.mjs"
|
||||
|
||||
const { pb, decode, ledger, owed, misses, STEP_WAIT } = _internal
|
||||
const real = globalThis.fetch
|
||||
const wait = { ...STEP_WAIT }
|
||||
afterEach(() => {
|
||||
globalThis.fetch = real
|
||||
Object.assign(STEP_WAIT, wait)
|
||||
owed.clear()
|
||||
misses.clear()
|
||||
})
|
||||
|
||||
const update = (num, body) => ({ data: pb().bytes(1, pb().bytes(num, body)).done() })
|
||||
const listed = update(27, pb().varint(1, 1).done())
|
||||
const call = {
|
||||
data: pb()
|
||||
.bytes(2, pb().varint(1, 7).str(15, "x1").bytes(11, pb().str(1, "magpie-bash").str(3, "call_1").str(5, "bash").done()).done())
|
||||
.done(),
|
||||
}
|
||||
async function step(book) {
|
||||
const out = []
|
||||
for await (const p of decode([listed, call], { send() {}, blobs: new Map(), tools: [], estimate: 1, stepUsage: book.own, owedUsage: book.owed })) out.push(p)
|
||||
book.done()
|
||||
return out.at(-1).usage
|
||||
}
|
||||
|
||||
// the report's two tool steps of one pi session
|
||||
const E1 = { inputTokens: 2, outputTokens: 1913, cacheReadTokens: 177533, cacheWriteTokens: 3735 } // 181270
|
||||
const E2 = { inputTokens: 4, outputTokens: 2240, cacheReadTokens: 181266, cacheWriteTokens: 4400 } // 185670
|
||||
const prompt = (e) => e.inputTokens + e.cacheReadTokens + e.cacheWriteTokens
|
||||
|
||||
test("a step's prompt_tokens is its own Run's; what it collected of an earlier step is magpie_deferred", async () => {
|
||||
Object.assign(STEP_WAIT, { first: 0, every: 10, until: 40, owedAt: 0 })
|
||||
const conv = "8a462df8-0000-4000-8000-000000000001"
|
||||
// step 1's Run began a while ago, as a tool step's did before its tool ran
|
||||
const since = Date.now() - 30_000
|
||||
const shown = []
|
||||
globalThis.fetch = async () => Response.json({ usageEventsDisplay: shown.map((e) => ({ ...e })) })
|
||||
|
||||
// step 1: its event shows only after its wait, so it is owed and says 0
|
||||
const u1 = await step(ledger("tok", conv, since, undefined, true))
|
||||
expect(u1.prompt_tokens).toBe(0)
|
||||
expect(u1.magpie_deferred).toBeUndefined()
|
||||
|
||||
// step 1's late event, then step 2's own
|
||||
// Cursor stamps a Run's event as the Run begins, a second or two in
|
||||
shown.push({ timestamp: String(since + 2000), conversationId: conv, tokenUsage: E1 })
|
||||
const since2 = Date.now()
|
||||
shown.push({ timestamp: String(since2 + 2000), conversationId: conv, tokenUsage: E2 })
|
||||
const u2 = await step(ledger("tok", conv, since2, undefined, true))
|
||||
|
||||
// the context as it is: step 2's prompt alone (was 366940)
|
||||
expect(u2.prompt_tokens).toBe(prompt(E2))
|
||||
expect(u2.total_tokens).toBe(prompt(E2) + E2.outputTokens)
|
||||
expect(u2.prompt_tokens_details).toEqual({ cached_tokens: E2.cacheReadTokens, cache_write_tokens: E2.cacheWriteTokens })
|
||||
// and step 1's, which magpie still bills, apart
|
||||
expect(u2.magpie_deferred).toEqual({
|
||||
prompt_tokens: prompt(E1),
|
||||
completion_tokens: E1.outputTokens,
|
||||
cached_tokens: E1.cacheReadTokens,
|
||||
cache_write_tokens: E1.cacheWriteTokens,
|
||||
})
|
||||
// together, what Cursor counted
|
||||
expect(u1.prompt_tokens + u2.prompt_tokens + u2.magpie_deferred.prompt_tokens).toBe(prompt(E1) + prompt(E2))
|
||||
})
|
||||
|
||||
test("a step that owed nothing has no magpie_deferred", async () => {
|
||||
Object.assign(STEP_WAIT, { first: 0, every: 10, until: 200, owedAt: 0 })
|
||||
const conv = "8a462df8-0000-4000-8000-000000000002"
|
||||
const since = Date.now()
|
||||
globalThis.fetch = async () => Response.json({ usageEventsDisplay: [{ timestamp: String(since + 2000), conversationId: conv, tokenUsage: E1 }] })
|
||||
const u = await step(ledger("tok", conv, since, undefined, true))
|
||||
expect(u.prompt_tokens).toBe(prompt(E1))
|
||||
expect(u.magpie_deferred).toBeUndefined()
|
||||
})
|
||||
+59
-20
@@ -1408,7 +1408,8 @@ function owe(conv, { since = Date.now(), n = 0, ready = Date.now(), carry = null
|
||||
|
||||
// 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.
|
||||
// each with its time (events), 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 } = {}) {
|
||||
@@ -1421,6 +1422,7 @@ async function usageEvents(tok, conv, since, want, { poll = false, first = STEP_
|
||||
const num = (v) => (Number.isFinite(Number(v)) ? Number(v) : 0)
|
||||
let usage = null
|
||||
let got = 0
|
||||
const events = []
|
||||
if (poll) await wait(first)
|
||||
while (!signal?.aborted) {
|
||||
try {
|
||||
@@ -1433,7 +1435,7 @@ async function usageEvents(tok, conv, since, want, { poll = false, first = STEP_
|
||||
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 }
|
||||
return { usage, events, got, refused: true }
|
||||
}
|
||||
const evs = res.ok ? ((await res.json())?.usageEventsDisplay ?? []) : []
|
||||
const found = evs
|
||||
@@ -1443,7 +1445,9 @@ async function usageEvents(tok, conv, since, want, { poll = false, first = STEP_
|
||||
for (const ev of found) {
|
||||
claimed.set(conv + "\0" + ev.timestamp, Date.now())
|
||||
const t = ev.tokenUsage
|
||||
usage = addUsage(usage ?? ZERO(), { input: num(t.inputTokens), output: num(t.outputTokens), cacheRead: num(t.cacheReadTokens), cacheWrite: num(t.cacheWriteTokens) })
|
||||
const u = { input: num(t.inputTokens), output: num(t.outputTokens), cacheRead: num(t.cacheReadTokens), cacheWrite: num(t.cacheWriteTokens), reasoning: 0 }
|
||||
usage = addUsage(usage ?? ZERO(), u)
|
||||
events.push({ at: num(ev.timestamp), usage: u })
|
||||
got++
|
||||
}
|
||||
if (got >= want) break
|
||||
@@ -1451,7 +1455,7 @@ async function usageEvents(tok, conv, since, want, { poll = false, first = STEP_
|
||||
if (!poll || Date.now() + STEP_WAIT.every > end) break
|
||||
await wait(STEP_WAIT.every)
|
||||
}
|
||||
return { usage, got, refused: false }
|
||||
return { usage, events, got, refused: false }
|
||||
}
|
||||
|
||||
// stepUsage is the usage of the Run of conversation conv started at since,
|
||||
@@ -1461,22 +1465,24 @@ async function stepUsage(tok, conv, since, signal) {
|
||||
}
|
||||
|
||||
// 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.
|
||||
// when poll): what was carried and what was found (usage), what was
|
||||
// carried alone (carry) and the events found (events), 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 })
|
||||
if (!d) return Promise.resolve({ usage: null, carry: null, events: [], short: false })
|
||||
owed.delete(conv)
|
||||
const p = (async () => {
|
||||
let r = { usage: null, got: 0 }
|
||||
let r = { usage: null, events: [], 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 carry = d.carry && { ...d.carry }
|
||||
const usage = addUsage(d.carry, r.usage)
|
||||
if (!over()) return { usage, short }
|
||||
if (!over()) return { usage, carry, events: r.events ?? [], short }
|
||||
owe(conv, { carry: usage })
|
||||
return { usage: null, short }
|
||||
return { usage: null, carry: null, events: [], short }
|
||||
})()
|
||||
const set = flights.get(conv) ?? new Set()
|
||||
flights.set(conv, set.add(p))
|
||||
@@ -1498,22 +1504,41 @@ function collect(tok, conv, { poll = false, first, signal, over = () => false }
|
||||
// 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.
|
||||
//
|
||||
// What a Run collects is told apart by its event's time: Cursor stamps a
|
||||
// Run's event as the Run begins (1.4–3.4 s after since), so one from since
|
||||
// on (less the second usageEvents allows) is this Run's own (mine), and one
|
||||
// before it, or a count carried, an earlier Run's (theirs). own() gives out only mine, as the step's usage,
|
||||
// which a client reads as how full its context is; theirs goes out by
|
||||
// owed(), apart. A Run of its conversation begins only once the one
|
||||
// before has ended, so the two never meet; were the time off, the step's
|
||||
// count would be told in the wrong field, never twice nor lost.
|
||||
function ledger(tok, conv, since, signal, kept) {
|
||||
const key = tokKey(tok)
|
||||
let pending = null // collected, not given out yet
|
||||
let mine = null // this Run's own, collected, not given out yet
|
||||
let theirs = null // earlier Runs', collected, not given out yet
|
||||
let over = false
|
||||
const gather = (opts) =>
|
||||
collect(tok, conv, { ...opts, over: () => over }).then((r) => {
|
||||
pending = addUsage(pending, r.usage)
|
||||
theirs = addUsage(theirs, r.carry)
|
||||
for (const e of r.events ?? []) {
|
||||
if (e.at >= since - 1000) mine = addUsage(mine, e.usage)
|
||||
else theirs = addUsage(theirs, e.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 takeMine = () => {
|
||||
const u = mine
|
||||
mine = null
|
||||
return u
|
||||
}
|
||||
const take = () => {
|
||||
const u = pending
|
||||
pending = null
|
||||
const u = addUsage(theirs, mine)
|
||||
mine = theirs = null
|
||||
return u
|
||||
}
|
||||
return {
|
||||
@@ -1534,7 +1559,7 @@ function ledger(tok, conv, since, signal, kept) {
|
||||
if (r.short) misses.set(key, m + 1)
|
||||
else misses.delete(key)
|
||||
} else misses.set(key, m + 1)
|
||||
return take() ?? false
|
||||
return takeMine() ?? false
|
||||
},
|
||||
async owed(final) {
|
||||
if (!kept) return null
|
||||
@@ -1548,7 +1573,8 @@ function ledger(tok, conv, since, signal, kept) {
|
||||
done() {
|
||||
over = true
|
||||
clearTimeout(timer)
|
||||
if (pending) owe(conv, { carry: take() })
|
||||
const u = take()
|
||||
if (u) owe(conv, { carry: u })
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1918,16 +1944,19 @@ async function* decode(stream, { send, blobs, tools, estimate, close, stepUsage,
|
||||
// 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
|
||||
// is no reason not to guess the step's own. The step's usage is its own
|
||||
// Run's alone: a client reads its prompt_tokens as how full the context
|
||||
// is (pi, OpenCode), and an earlier step's prompt added to it read twice
|
||||
// the context. What earlier steps owed goes apart, as magpie_deferred,
|
||||
// which magpie counts with the step and no client reads.
|
||||
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; 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
|
||||
const deferred = more && more.input + more.output + more.cacheRead + more.cacheWrite > 0
|
||||
return {
|
||||
stop: calls > 0 ? "tool_calls" : "stop",
|
||||
usage: {
|
||||
@@ -1936,6 +1965,16 @@ async function* decode(stream, { send, blobs, tools, estimate, close, stepUsage,
|
||||
total_tokens: prompt + usage.output,
|
||||
prompt_tokens_details: { cached_tokens: usage.cacheRead, cache_write_tokens: usage.cacheWrite },
|
||||
...(usage.reasoning ? { completion_tokens_details: { reasoning_tokens: usage.reasoning } } : {}),
|
||||
...(deferred
|
||||
? {
|
||||
magpie_deferred: {
|
||||
prompt_tokens: more.input + more.cacheRead + more.cacheWrite,
|
||||
completion_tokens: more.output,
|
||||
cached_tokens: more.cacheRead,
|
||||
cache_write_tokens: more.cacheWrite,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,12 +143,14 @@ const chat = (steps) => {
|
||||
return { model: "claude-fable-5-thinking", messages, tools: [{ type: "function", function: { name: "Read", parameters: { type: "object" } } }] }
|
||||
}
|
||||
|
||||
// what magpie bills for the steps: each step's own, and what it collected
|
||||
// of earlier steps' (magpie_deferred), which its prompt_tokens leaves out
|
||||
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: a.prompt + u.prompt_tokens + (u.magpie_deferred?.prompt_tokens ?? 0),
|
||||
cached: a.cached + u.prompt_tokens_details.cached_tokens + (u.magpie_deferred?.cached_tokens ?? 0),
|
||||
written: a.written + u.prompt_tokens_details.cache_write_tokens + (u.magpie_deferred?.cache_write_tokens ?? 0),
|
||||
}),
|
||||
{ prompt: 0, cached: 0, written: 0 },
|
||||
)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-cursor-auth",
|
||||
"version": "0.2.10",
|
||||
"version": "0.2.11",
|
||||
"description": "Cursor subscriptions (Pro, Pro+, Ultra, Teams) in OpenCode and magpie, through the API cursor-agent talks to",
|
||||
"type": "module",
|
||||
"main": "./index.mjs",
|
||||
|
||||
Reference in New Issue
Block a user