diff --git a/packages/cursor/index.mjs b/packages/cursor/index.mjs index 07487c6..11f0ee6 100644 --- a/packages/cursor/index.mjs +++ b/packages/cursor/index.mjs @@ -1358,17 +1358,18 @@ function usageOf(uf) { // 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. +// claimed are the usage events already counted, by account, conversation +// and time, so that two steps of one conversation never count the same one. const claimed = new Map() -// 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. +// owed are what each account's conversation still owes, by credential +// fingerprint and 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. +// flights are each account's conversation 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 @@ -1378,6 +1379,7 @@ const flights = new Map() const unreadable = new Map() const misses = new Map() const tokKey = (tok) => createHash("sha256").update(tok).digest("hex") +const usageKey = (tok, conv) => tokKey(tok) + "\0" + conv function canRead(tok) { const at = unreadable.get(tokKey(tok)) if (at === undefined) return true @@ -1394,12 +1396,12 @@ function addUsage(a, b) { return a } -// owe adds to conversation conv's debt. -function owe(conv, { since = Date.now(), n = 0, ready = Date.now(), carry = null }) { +// owe adds to the account/conversation's debt. +function owe(key, { 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 } }) + const d = owed.get(key) + if (!d) return void owed.set(key, { since, n, ready, carry: carry && { ...carry } }) d.since = Math.min(d.since, since) d.n += n d.ready = Math.min(d.ready, ready) @@ -1413,6 +1415,7 @@ function owe(conv, { since = Date.now(), n = 0, ready = Date.now(), carry = null // 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 key = usageKey(tok, conv) const end = Date.now() + STEP_WAIT.until const wait = (ms) => new Promise((r) => { const t = setTimeout(r, ms) @@ -1439,11 +1442,11 @@ async function usageEvents(tok, conv, since, want, { poll = false, first = STEP_ } const evs = res.ok ? ((await res.json())?.usageEventsDisplay ?? []) : [] const found = evs - .filter((e) => e?.conversationId === conv && e.tokenUsage && num(e.timestamp) >= since - 1000 && !claimed.has(conv + "\0" + e.timestamp)) + .filter((e) => e?.conversationId === conv && e.tokenUsage && num(e.timestamp) >= since - 1000 && !claimed.has(key + "\0" + e.timestamp)) .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()) + claimed.set(key + "\0" + ev.timestamp, Date.now()) const t = ev.tokenUsage 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) @@ -1464,31 +1467,32 @@ 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), what was -// carried alone (carry) and the events found (events), and whether any is +// collect takes the account's debt for conversation conv and asks for its +// events (polling 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) + const key = usageKey(tok, conv) + const d = owed.get(key) if (!d) return Promise.resolve({ usage: null, carry: null, events: [], short: false }) - owed.delete(conv) + owed.delete(key) const p = (async () => { 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 }) + if (short) owe(key, { 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, carry, events: r.events ?? [], short } - owe(conv, { carry: usage }) + owe(key, { carry: usage }) return { usage: null, carry: null, events: [], short } })() - const set = flights.get(conv) ?? new Set() - flights.set(conv, set.add(p)) + const set = flights.get(key) ?? new Set() + flights.set(key, set.add(p)) p.finally(() => { set.delete(p) - if (!set.size && flights.get(conv) === set) flights.delete(conv) + if (!set.size && flights.get(key) === set) flights.delete(key) }) return p } @@ -1515,6 +1519,7 @@ function collect(tok, conv, { poll = false, first, signal, over = () => false } // count would be told in the wrong field, never twice nor lost. function ledger(tok, conv, since, signal, kept) { const key = tokKey(tok) + const debtKey = usageKey(tok, conv) 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 @@ -1528,7 +1533,7 @@ function ledger(tok, conv, since, signal, kept) { return r }) let collecting = null - const debt = kept ? owed.get(conv) : undefined + const debt = kept ? owed.get(debtKey) : undefined const timer = debt ? setTimeout(() => (collecting = gather()), Math.max(0, debt.ready - Date.now())) : null timer?.unref?.() const takeMine = () => { @@ -1552,7 +1557,7 @@ function ledger(tok, conv, since, signal, kept) { else if (!r.refused) misses.set(key, m + 1) return r.usage ?? null } - owe(conv, { since, n: 1, ready: Date.now() + STEP_WAIT.owedAt }) + owe(debtKey, { since, n: 1, ready: Date.now() + STEP_WAIT.owedAt }) if (waits) { const r = await gather({ poll: true, signal }) if (!canRead(tok)) return null @@ -1565,8 +1570,8 @@ function ledger(tok, conv, since, signal, kept) { 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 }) + await Promise.all([...(flights.get(debtKey) ?? [])]) + if (owed.has(debtKey)) await gather({ poll: owed.get(debtKey).n > 0, first: 0, signal }) } return take() }, @@ -1574,7 +1579,7 @@ function ledger(tok, conv, since, signal, kept) { over = true clearTimeout(timer) const u = take() - if (u) owe(conv, { carry: u }) + if (u) owe(debtKey, { carry: u }) }, } } @@ -2441,4 +2446,4 @@ export async function CursorAuthPlugin() { } // for tests -export const _internal = { onDemandOf,resetH1: () => (h1Until = 0), onH1: () => Date.now() < h1Until, H2, H1, h2Blocked, open, openH1, openH2, STEP_WAIT, stepUsage, 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 = { onDemandOf,resetH1: () => (h1Until = 0), onH1: () => Date.now() < h1Until, 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/stepusage.test.mjs b/packages/cursor/stepusage.test.mjs index 190a7ab..36339d3 100644 --- a/packages/cursor/stepusage.test.mjs +++ b/packages/cursor/stepusage.test.mjs @@ -5,13 +5,14 @@ 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 { pb, decode, stepUsage, usageKey, STEP_WAIT } = _internal const real = globalThis.fetch const wait = { ...STEP_WAIT } afterEach(() => { globalThis.fetch = real Object.assign(STEP_WAIT, wait) + for (const map of [_internal.owed, _internal.flights, _internal.misses, _internal.unreadable]) map.clear() }) const update = (num, body) => ({ data: pb().bytes(1, pb().bytes(num, body)).done() }) @@ -108,7 +109,7 @@ test("an account that can't read its events is guessed as before, and owes nothi 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) + expect(owed.has(usageKey("tok-403", 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) @@ -123,15 +124,143 @@ test("what a Run collected and never gave out goes to the conversation's next st 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 }) + owed.set(usageKey("tok", 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 }) + expect(owed.get(usageKey("tok", 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(owed.has(usageKey("tok", conv))).toBe(false) expect(await ledger("tok", conv, Date.now(), undefined, true).owed(true)).toBe(null) }) + +test("usage events with the same conversation and time are counted once per account, including zero", async () => { + Object.assign(STEP_WAIT, { first: 0, every: 5, until: 20 }) + const since = Date.now() + const conv = "synthetic-account-claims" + globalThis.fetch = async (_url, init) => Response.json({ + usageEventsDisplay: [{ timestamp: String(since + 2000), conversationId: conv, + tokenUsage: init.headers.Authorization === "Bearer synthetic-claims-a" + ? { inputTokens: 11, outputTokens: 3, cacheReadTokens: 100, cacheWriteTokens: 7 } + : { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 } }], + }) + expect(await stepUsage("synthetic-claims-a", conv, since)).toEqual({ input: 11, output: 3, cacheRead: 100, cacheWrite: 7, reasoning: 0 }) + const zero = await stepUsage("synthetic-claims-b", conv, since) + expect(zero).toEqual({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0, reasoning: 0 }) + // A dashboard zero is authoritative, rather than missing usage to estimate. + const out = await run([listed, call], { stepUsage: async () => zero }) + expect(out.at(-1).usage).toEqual({ + prompt_tokens: 0, completion_tokens: 0, total_tokens: 0, + prompt_tokens_details: { cached_tokens: 0, cache_write_tokens: 0 }, + }) + expect(await stepUsage("synthetic-claims-a", conv, since)).toBe(null) + expect(await stepUsage("synthetic-claims-b", conv, since)).toBe(null) +}) + +test("ledger debt for the same conversation is collected only by its account", async () => { + const { ledger, owed } = _internal + Object.assign(STEP_WAIT, { first: 0, every: 5, until: 20, owedAt: 60_000 }) + const since = Date.now() - 30_000 + const conv = "synthetic-account-debt" + const keyA = usageKey("synthetic-debt-a", conv) + const keyB = usageKey("synthetic-debt-b", conv) + const usageA = { input: 11, output: 3, cacheRead: 100, cacheWrite: 7, reasoning: 0 } + const usageB = { input: 22, output: 5, cacheRead: 200, cacheWrite: 9, reasoning: 0 } + let shown = false + globalThis.fetch = async (_url, init) => { + const u = init.headers.Authorization === "Bearer synthetic-debt-a" ? usageA : usageB + return Response.json({ usageEventsDisplay: shown ? [{ timestamp: String(since + 2000), conversationId: conv, + tokenUsage: { inputTokens: u.input, outputTokens: u.output, cacheReadTokens: u.cacheRead, cacheWriteTokens: u.cacheWrite } }] : [] }) + } + const a = ledger("synthetic-debt-a", conv, since, undefined, true) + const b = ledger("synthetic-debt-b", conv, since, undefined, true) + let nextA, nextB + try { + for (const book of [a, b]) { + const out = await run([listed, call], { stepUsage: book.own, owedUsage: book.owed }) + // An unpaid Run reports zero now, then its own account collects it later. + expect(out.at(-1).usage.total_tokens).toBe(0) + book.done() + } + expect(owed.get(keyA)).toMatchObject({ since, n: 1, carry: null }) + expect(owed.get(keyB)).toMatchObject({ since, n: 1, carry: null }) + shown = true + nextB = ledger("synthetic-debt-b", conv, Date.now(), undefined, true) + expect(await nextB.owed(true)).toEqual(usageB) + expect(owed.has(keyB)).toBe(false) + expect(owed.get(keyA)).toMatchObject({ since, n: 1, carry: null }) + nextA = ledger("synthetic-debt-a", conv, Date.now(), undefined, true) + expect(await nextA.owed(true)).toEqual(usageA) + expect(owed.has(keyA)).toBe(false) + expect(await nextA.owed(true)).toBe(null) + expect(await nextB.owed(true)).toBe(null) + } finally { + for (const book of [a, b, nextA, nextB]) book?.done() + } +}) + +test("ledger flights and late carry keep account and collection identity during cleanup", async () => { + const { ledger, owed, flights } = _internal + Object.assign(STEP_WAIT, { first: 0, every: 5, until: 20 }) + const since = Date.now() - 30_000 + const conv = "synthetic-account-flights" + const keyA = usageKey("synthetic-flights-a", conv) + const keyB = usageKey("synthetic-flights-b", conv) + const usageA = { input: 11, output: 3, cacheRead: 100, cacheWrite: 7, reasoning: 0 } + const usageB = { input: 22, output: 5, cacheRead: 200, cacheWrite: 9, reasoning: 0 } + const response = (u) => Response.json({ usageEventsDisplay: [{ timestamp: String(since + 2000), conversationId: conv, + tokenUsage: { inputTokens: u.input, outputTokens: u.output, cacheReadTokens: u.cacheRead, cacheWriteTokens: u.cacheWrite } }] }) + let startedA, startedB, releaseA, releaseB + const askedA = new Promise((resolve) => { startedA = resolve }) + const askedB = new Promise((resolve) => { startedB = resolve }) + globalThis.fetch = async (_url, init) => new Promise((resolve) => { + if (init.headers.Authorization === "Bearer synthetic-flights-a") { releaseA = resolve; startedA() } + else { releaseB = resolve; startedB() } + }) + const a = ledger("synthetic-flights-a", conv, since, undefined, true) + const b = ledger("synthetic-flights-b", conv, since, undefined, true) + const ownA = a.own(), ownB = b.own() + let nextA, timeout + try { + await Promise.all([askedA, askedB]) + const inFlightA = flights.get(keyA), inFlightB = flights.get(keyB) + expect(inFlightA?.size).toBe(1) + expect(inFlightB?.size).toBe(1) + expect(inFlightA).not.toBe(inFlightB) + expect(owed.has(keyA)).toBe(false) + expect(owed.has(keyB)).toBe(false) + // A finishing collector must retain a replacement set under the same key. + const replacement = new Set() + flights.set(keyA, replacement) + a.done() + releaseA(response(usageA)) + expect(await ownA).toBe(false) + expect(flights.get(keyA)).toBe(replacement) + expect(flights.get(keyB)).toBe(inFlightB) + expect(owed.get(keyA).carry).toEqual(usageA) + flights.delete(keyA) + nextA = ledger("synthetic-flights-a", conv, Date.now(), undefined, true) + expect(await Promise.race([ + nextA.owed(true), + new Promise((_, reject) => { timeout = setTimeout(() => reject(new Error("waited for another account's collection")), 1000) }), + ])).toEqual(usageA) + clearTimeout(timeout) + expect(owed.has(keyA)).toBe(false) + expect(flights.has(keyA)).toBe(false) + expect(flights.get(keyB)).toBe(inFlightB) + releaseB(response(usageB)) + expect(await ownB).toEqual(usageB) + expect(owed.has(keyB)).toBe(false) + expect(flights.has(keyB)).toBe(false) + } finally { + clearTimeout(timeout) + for (const book of [a, b, nextA]) book?.done() + globalThis.fetch = async () => Response.json({ usageEventsDisplay: [] }) + releaseA?.(response(usageA)) + releaseB?.(response(usageB)) + await Promise.all([ownA, ownB]) + } +})