diff --git a/packages/cursor/README.md b/packages/cursor/README.md index fcde856..0f51edf 100644 --- a/packages/cursor/README.md +++ b/packages/cursor/README.md @@ -152,8 +152,9 @@ the old native exec again. A native tool handoff reports zero usage with `magpie_native.accounting=pending`; the final native answer bills the turn's totals. Its own `prompt_tokens` and -`completion_tokens` are its last model call's share (the larger of that -call's prompt estimate and the turn's mean per call), since a client reads +`completion_tokens` are its last model call's count (`ModelCallCompletedUpdate`, +asked for with `emit_model_call_usage`, else the larger of that call's prompt +estimate and the turn's mean per call), since a client reads them as how full its context is; the earlier calls' share is `usage.magpie_deferred` (#156). An identical completed retry replays the saved response with zero usage. A native final also collects earlier diff --git a/packages/cursor/index.mjs b/packages/cursor/index.mjs index 36249ab..ff1a82c 100644 --- a/packages/cursor/index.mjs +++ b/packages/cursor/index.mjs @@ -1932,15 +1932,17 @@ function conversationID(chat, session) { return uuidOf(sum) } -// usageOf is a TurnEndedUpdate as magpie counts usage, as the built-in's -// cursorUsage has it (magpie #498). Its input_tokens is the whole prompt, -// what was read from the cache and written to it included, as Cursor's -// own client has it (it takes both out to get the prompt's uncached -// rest); input is that rest, the cache added back for prompt_tokens. Its -// reasoning_tokens is kept as reasoning. -function usageOf(uf) { - const [inp, cr, cw] = [pbNum(uf, 1), pbNum(uf, 3), pbNum(uf, 4)] - return { input: Math.max(inp - cr - cw, 0), output: pbNum(uf, 2), cacheRead: cr, cacheWrite: cw, reasoning: pbNum(uf, 5) } +// usageOf is a TurnEndedUpdate or ModelCallCompletedUpdate as magpie +// counts usage, as the built-in's cursorUsage has it (magpie #498). Its +// input_tokens is the whole prompt, what was read from the cache and +// written to it included, as Cursor's own client has it (it takes both out +// to get the prompt's uncached rest); input is that rest, the cache added +// back for prompt_tokens. Its reasoning_tokens is kept as reasoning. +// ModelCallCompletedUpdate carries model_call_id at field 1 and the five +// token counts at 2..6 (one after TurnEndedUpdate's 1..5). +function usageOf(uf, shift = 0) { + const [inp, cr, cw] = [pbNum(uf, 1 + shift), pbNum(uf, 3 + shift), pbNum(uf, 4 + shift)] + return { input: Math.max(inp - cr - cw, 0), output: pbNum(uf, 2 + shift), cacheRead: cr, cacheWrite: cw, reasoning: pbNum(uf, 5 + shift) } } // A step that calls the caller's tools has no TurnEndedUpdate: Cursor ends @@ -2354,6 +2356,7 @@ function buildRun(msgs, lastUser, tools, model, conv = "", { maxMode = false, pa .str(5, conv || randomUUID()) .bytes(9, requested) .varint(19, 1) // inline images + .varint(37, 1) // emit_model_call_usage: ModelCallCompletedUpdate (31) per step return { first: pb().bytes(1, rr).done(), blobs } } @@ -3093,7 +3096,7 @@ async function* decode(stream, { send, blobs, tools, estimate, close, stepUsage, // 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) { + if (calls > 0 && !ended && !counted && stepUsage) { close?.() const u = await stepUsage().catch(() => null) if (u) usage = u @@ -3195,6 +3198,12 @@ async function* decode(stream, { send, blobs, tools, estimate, close, stepUsage, return } break + case 31: // model_call_completed: the step's own token usage + if (!ended && uf.some((f) => f.num >= 2 && f.num <= 6)) { + usage = usageOf(uf, 1) + counted = true + } + break case 2: // a call started on the client case 3: // a call completed: by Cursor itself when it never started here case 7: // a call the model is writing diff --git a/packages/cursor/native-e2e.test.mjs b/packages/cursor/native-e2e.test.mjs index c1fd141..6140614 100644 --- a/packages/cursor/native-e2e.test.mjs +++ b/packages/cursor/native-e2e.test.mjs @@ -149,6 +149,7 @@ async function agent(options = {}) { const advance = () => { const expected = phase === 0 && options.parallel ? [firstID, 8] : [phase === 0 ? firstID : 8] if (!expected.every((id) => closed.has(id))) return + if (options.stepUsages?.[phase]) send(update(31, options.stepUsages[phase])) if (phase === 0 && !options.parallel && !options.finalAfterFirst) { marker = received.get(firstID).content[0].text phase = 1 @@ -170,6 +171,7 @@ async function agent(options = {}) { if (options.halfFinal) { send(update(1, text(1, "half said"))); return } send(update(4, text(1, "native final thinking"))) send(update(1, text(1, marker))) + if (options.stepUsages?.[2]) send(update(31, options.stepUsages[2])) const usage = options.turnUsage ?? (options.zeroUsage ? message(uint(1, 0), uint(2, 0), uint(5, 0)) : message(uint(1, 23), uint(2, 7), uint(3, 10), uint(4, 0), uint(5, 4))) send(update(14, usage)) state(false, true) // late state after TurnEnded must still be retained @@ -312,6 +314,7 @@ test("native accounting: a multi-step turn's final step reports its own share, t const final = await a.ask(account, continueWith(next, second.body, ["two"])) expect(final.status).toBe(200) expect(a.runs).toHaveLength(1) + expect(number(a.runs[0], 37)).toBe(1) // emit_model_call_usage const u = final.body.usage, d = u.magpie_deferred // three model calls: none is more than half the turn expect(u.prompt_tokens).toBeLessThan(1105934 / 2) @@ -324,6 +327,37 @@ test("native accounting: a multi-step turn's final step reports its own share, t expect(u.completion_tokens_details.reasoning_tokens).toBeLessThanOrEqual(u.completion_tokens) }) +test("native accounting: ModelCallCompletedUpdate (31) gives the final step its exact context and defers the rest (#156)", async () => { + // Three model calls: 50K -> 55K -> 61K context; TurnEndedUpdate sums all three (166K). + const stepUsages = [ + message(text(1, "mc-1"), uint(2, 50000), uint(3, 600), uint(4, 25000), uint(5, 24990), uint(6, 200)), + message(text(1, "mc-2"), uint(2, 55000), uint(3, 800), uint(4, 50000), uint(5, 4990), uint(6, 300)), + message(text(1, "mc-3"), uint(2, 61000), uint(3, 700), uint(4, 55000), uint(5, 5980), uint(6, 400)), + ] + const turnUsage = message(uint(1, 166000), uint(2, 2100), uint(3, 130000), uint(4, 35960), uint(5, 900)) + const a = await agent({ stepUsages, turnUsage }), account = auth(), chat = initial() + const first = await a.ask(account, chat) + const next = continueWith(chat, first.body, ["one"]) + const second = await a.ask(account, next) + const final = await a.ask(account, continueWith(next, second.body, ["two"])) + expect(final.status).toBe(200) + expect(a.runs).toHaveLength(1) + expect(number(a.runs[0], 37)).toBe(1) + expect(final.body.usage).toEqual({ + prompt_tokens: 61000, + completion_tokens: 700, + total_tokens: 61700, + prompt_tokens_details: { cached_tokens: 55000, cache_write_tokens: 5980 }, + completion_tokens_details: { reasoning_tokens: 400 }, + magpie_deferred: { + prompt_tokens: 105000, + completion_tokens: 1400, + cached_tokens: 75000, + cache_write_tokens: 29980, + }, + }) +}) + test("native retention: Task parent awaiting results permits a child sharing session with different first user", async () => { const a = await agent({ name: "Task" }), account = auth(), parent = initial({ tools: [{ type: "function", function: { name: "Task", parameters: { type: "object" } } }] }) const first = await a.ask(account, parent) diff --git a/packages/cursor/native-session.mjs b/packages/cursor/native-session.mjs index 307b5e9..966ef64 100644 --- a/packages/cursor/native-session.mjs +++ b/packages/cursor/native-session.mjs @@ -73,7 +73,7 @@ const UPDATES = { 1: "text", 2: "tool call started", 3: "tool call completed", 4: "thinking", 5: "thinking done", 6: "user message", 7: "partial tool call", 8: "token count", 9: "summary", 10: "summary started", 11: "summary done", 12: "shell output", 14: "turn end", 15: "tool call delta", 16: "step started", - 17: "step done", 27: "tool count", + 17: "step done", 27: "tool count", 31: "model call completed", } const MESSAGES = { 2: "tool call", 3: "checkpoint", 4: "blob request" } function kindOf(f) { @@ -872,6 +872,8 @@ export class NativeSessionPool { owner.checkpoint = null owner.execs.clear() owner.nativeCalls.clear() + owner.stepUsages.clear() + owner.lastStepUsage = null } async clear() { await Promise.all([...this.entries].map((e) => e.cancel("native owner removed"))) @@ -906,6 +908,8 @@ class NativeSession { // latest one began: the last step's own share of the turn (#156) this.steps = 1 this.stepSaid = 0 + this.stepUsages = new Map() + this.lastStepUsage = null this.said = 0 this.wrote = 0 this.terminal = false @@ -1099,8 +1103,20 @@ class NativeSession { this.stepCalls.nextStep() this.quiet.nextStep(this.steps) this.stepSaid = this.said + this.lastStepUsage = null if (estimate != null) this.stepEstimate = estimate } + modelCallCompleted(fields) { + const id = str(fields, 1) + const entry = { + usage: this.wire.usageOf(fields, 1), + measuredInput: fields.some((f) => [2, 4, 5].includes(f.num)), + measuredOutput: fields.some((f) => f.num === 3), + hasReasoning: fields.some((f) => f.num === 6), + } + this.stepUsages.set(id || `step:${this.steps}:${this.stepUsages.size}`, entry) + this.lastStepUsage = entry + } // waitForBatch gives the step batchWait from its latest call, answered // call, count, text or heartbeat, not from its first. Cursor sends each // call once the model has written its arguments, so a step of many long @@ -1281,28 +1297,57 @@ class NativeSession { if (this.error || this.state === "complete") return if (!this.terminal) invalid("native Run ended before TurnEnded or a complete final answer", 502) const { usageOf } = this.wire - const measuredInput = this.usageFields?.some((f) => [1, 3, 4].includes(f.num)) - const measuredOutput = this.usageFields?.some((f) => f.num === 2) + const turnInput = this.usageFields?.some((f) => [1, 3, 4].includes(f.num)) + const turnOutput = this.usageFields?.some((f) => f.num === 2) + const last = this.lastStepUsage + const measuredInput = turnInput || !!last?.measuredInput + const measuredOutput = turnOutput || !!last?.measuredOutput const u = usageOf(this.usageFields ?? []) + if (!turnInput && last?.measuredInput) Object.assign(u, { input: last.usage.input, cacheRead: last.usage.cacheRead, cacheWrite: last.usage.cacheWrite }) + if (!turnOutput && last?.measuredOutput) Object.assign(u, { output: last.usage.output, reasoning: last.usage.reasoning }) if (!measuredInput) u.input = this.estimate if (!measuredOutput) u.output = Math.floor((this.said + 3) / 4) // A turn of several model calls: TurnEndedUpdate counts them all, but a // client reads the last response's prompt as how full its context is - // (Codex compacted a 61K context at 1.1M, #156). The last call keeps its - // own share, the larger of its prompt estimate and the turn's mean per - // call; the rest is billed as magpie_deferred. + // (Codex compacted a 61K context at 1.1M, #156). When Cursor emitted + // ModelCallCompletedUpdate (31) for the last step, it keeps its exact + // count; otherwise it keeps the larger of its prompt estimate and the + // turn's mean per call. The rest is billed as magpie_deferred. let earlier = null if (this.steps > 1) { - const whole = u.input + u.cacheRead + u.cacheWrite - const share = (total, own) => total > 0 ? Math.min(1, Math.max(own, total / this.steps) / total) : 0 - const fi = share(whole, measuredInput ? this.stepEstimate ?? 0 : whole) - const fo = share(u.output, Math.floor((this.said - this.stepSaid + 3) / 4)) - const own = { - input: Math.round(u.input * fi), cacheRead: Math.round(u.cacheRead * fi), cacheWrite: Math.round(u.cacheWrite * fi), - output: Math.round(u.output * fo), reasoning: Math.round(u.reasoning * fo), + if (last && (last.measuredInput || last.measuredOutput)) { + const prev = [...this.stepUsages.values()].filter((e) => e !== last) + const sum = (k) => prev.reduce((s, e) => s + e.usage[k], 0) + const whole = u.input + u.cacheRead + u.cacheWrite + const share = (total, own) => total > 0 ? Math.min(1, Math.max(own, total / this.steps) / total) : 0 + const fi = share(whole, turnInput ? this.stepEstimate ?? 0 : whole) + const fo = share(u.output, Math.floor((this.said - this.stepSaid + 3) / 4)) + const own = { + input: last.measuredInput ? last.usage.input : Math.round(u.input * fi), + cacheRead: last.measuredInput ? last.usage.cacheRead : Math.round(u.cacheRead * fi), + cacheWrite: last.measuredInput ? last.usage.cacheWrite : Math.round(u.cacheWrite * fi), + output: last.measuredOutput ? last.usage.output : Math.round(u.output * fo), + reasoning: last.hasReasoning ? last.usage.reasoning : last.measuredOutput ? Math.min(u.reasoning, last.usage.output) : Math.round(u.reasoning * fo), + } + earlier = { + input: turnInput ? Math.max(0, u.input - own.input) : sum("input"), + cacheRead: turnInput ? Math.max(0, u.cacheRead - own.cacheRead) : sum("cacheRead"), + cacheWrite: turnInput ? Math.max(0, u.cacheWrite - own.cacheWrite) : sum("cacheWrite"), + output: turnOutput ? Math.max(0, u.output - own.output) : sum("output"), + } + Object.assign(u, own) + } else { + const whole = u.input + u.cacheRead + u.cacheWrite + const share = (total, own) => total > 0 ? Math.min(1, Math.max(own, total / this.steps) / total) : 0 + const fi = share(whole, measuredInput ? this.stepEstimate ?? 0 : whole) + const fo = share(u.output, Math.floor((this.said - this.stepSaid + 3) / 4)) + const own = { + input: Math.round(u.input * fi), cacheRead: Math.round(u.cacheRead * fi), cacheWrite: Math.round(u.cacheWrite * fi), + output: Math.round(u.output * fo), reasoning: Math.round(u.reasoning * fo), + } + earlier = { input: u.input - own.input, cacheRead: u.cacheRead - own.cacheRead, cacheWrite: u.cacheWrite - own.cacheWrite, output: u.output - own.output } + Object.assign(u, own) } - earlier = { input: u.input - own.input, cacheRead: u.cacheRead - own.cacheRead, cacheWrite: u.cacheWrite - own.cacheWrite, output: u.output - own.output } - Object.assign(u, own) } // What a later Run collected of this Run's event while this one waited on // results (handover) is in the turn's totals too: it comes off them, from @@ -1317,7 +1362,7 @@ class NativeSession { this.finalUsage = { prompt_tokens: prompt, completion_tokens: u.output, total_tokens: prompt + u.output, prompt_tokens_details: { cached_tokens: u.cacheRead, cache_write_tokens: u.cacheWrite }, - ...(this.usageFields?.some((f) => f.num === 5) ? { completion_tokens_details: { reasoning_tokens: u.reasoning } } : {}), + ...(this.usageFields?.some((f) => f.num === 5) || last?.hasReasoning ? { completion_tokens_details: { reasoning_tokens: u.reasoning } } : {}), ...(!measuredInput || !measuredOutput ? { magpie_native: { accounting: "estimated" } } : {}), } this.state = "finalizing" @@ -1373,6 +1418,8 @@ class NativeSession { } else if (u.num === 14) { if (!this.segment.content && !this.segment.calls.length) invalid("an empty reply (Cursor ended the turn without text or a tool call)", 502) this.terminalSeen(uf) + } else if (u.num === 31) { + this.modelCallCompleted(uf) } else if (u.num === 27) { this.listed(num(uf, 1)) if (this.error) return diff --git a/packages/cursor/package.json b/packages/cursor/package.json index 927cb9d..6256d5f 100644 --- a/packages/cursor/package.json +++ b/packages/cursor/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-cursor-auth", - "version": "0.2.42", + "version": "0.2.43", "description": "Cursor subscriptions (Pro, Pro+, Ultra, Teams) in OpenCode and magpie, through the API cursor-agent talks to", "type": "module", "main": "./opencode.mjs", diff --git a/packages/cursor/stepusage.test.mjs b/packages/cursor/stepusage.test.mjs index 36339d3..a881de3 100644 --- a/packages/cursor/stepusage.test.mjs +++ b/packages/cursor/stepusage.test.mjs @@ -58,6 +58,16 @@ test("a count Cursor gave, or none to be had, is as before", async () => { 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) + // ModelCallCompletedUpdate (31) before the step seals gives the step its count without polling the dashboard + out = await run([update(31, pb().str(1, "mc-1").varint(2, 950).varint(3, 12).varint(4, 900).varint(5, 40).varint(6, 5).done()), listed, call], { stepUsage }) + expect(asked).toBe(0) + expect(out.at(-1).usage).toEqual({ + prompt_tokens: 950, + completion_tokens: 12, + total_tokens: 962, + prompt_tokens_details: { cached_tokens: 900, cache_write_tokens: 40 }, + completion_tokens_details: { reasoning_tokens: 5 }, + }) // no event in time: the guess out = await run([listed, call], { stepUsage }) expect(asked).toBe(1)