cursor: a multi-step turn's last step reports its own share of usage, and a step's calls get batchWait from the latest one (#156 erzay, #155 midmirror)

#156: a native Run of N tool steps ended with TurnEndedUpdate's totals as
the final step's prompt_tokens (1,105,934 on erzay's ~21-step turn, where
the real context was ~61K), and Codex compacted at once. The final step
now keeps its last model call's share, max(that call's chars/4 prompt
estimate, turn total / model calls), split proportionally across input,
cache read and cache write; the rest goes into usage.magpie_deferred
(merged with any settled stateless debt), so magpie still bills the whole
turn. On erzay's numbers that is ~52.7K reported, ~1.05M deferred.

#155: waitForBatch armed once, at a step's first call, so a step whose
calls arrive one by one as the model writes them (13 calls, 9 long-arg)
failed 502 "did not complete its declared native tool batch" ~30s after
the first call even though it never paused that long. The deadline now
restarts on every call, answered call, count and text/reasoning frame.

Run at this commit: packages/cursor `bun test` (isolated HOME) 266 pass,
0 fail, three times; `bun scripts/check.mjs` ok. The three new tests fail
on 4e64f26's source (prompt 1105934; sealed step failed at 300ms; stall
failed 303ms after the first call instead of after the latest).
This commit is contained in:
yetone
2026-10-16 15:09:25 +08:00
parent 423e78e49c
commit c7c6498d85
5 changed files with 119 additions and 5 deletions
+9 -1
View File
@@ -100,6 +100,10 @@ reach their bound (a long history asks for its blobs at once, and a slow link
drains them slowly), the Run waits for the link to drain, and fails only if it
doesn't for 30 seconds.
A step's calls must all arrive within 30 seconds of each other: Cursor sends
each one once the model has written it, so a step of many long calls can take
longer than that in all (#155).
Cursor's count of a step's tool calls includes calls the plugin answers itself:
a tool the request doesn't have is refused to the model, and Cursor's own
`get_mcp_tools` is answered with the request's tools. The step's calls are the
@@ -115,7 +119,11 @@ request can rebuild from its supplied history without submitting the result to
the old native exec again.
A native tool handoff reports zero usage with `magpie_native.accounting=pending`;
the final native answer reports the turn's totals. An identical completed retry
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
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
stateless debt as `usage.magpie_deferred`, separately from its own prompt total.
If a started native Run is abandoned after a pending handoff, its dashboard
+2 -1
View File
@@ -2592,7 +2592,8 @@ async function answerOf(auth, chat, signal, session = "") {
const convID = conversationID(chat, session)
const prepared = nativeSessions.prepare(tok, chat, convID, tools)
let r
if (prepared.owner) r = prepared.owner.resume(prepared, signal)
// the continuation's own prompt, which its final step reports (#156)
if (prepared.owner) r = prepared.owner.resume({ ...prepared, estimate: conversation(chat, tools).estimate }, signal)
const model = String(chat.model ?? "")
if (!r) {
let raw = []
+27 -1
View File
@@ -148,7 +148,7 @@ async function agent(options = {}) {
if (options.stallFinal) return
send(update(4, text(1, "native final thinking")))
send(update(1, text(1, marker)))
const usage = 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))
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
if (!options.noEnd) delay(() => stream.end(end()), 55)
@@ -276,6 +276,32 @@ test("native retention: healthy two external roundtrips use one Run", async () =
expect(a.errors).toEqual([])
})
// #156 (erzay, Codex on cursor/claude-opus-5-5@1m): a turn of about 20 tool
// steps ended with TurnEndedUpdate's totals, 1,105,934 prompt (1,035,734 read
// from the cache, 70,156 written) as the final step's prompt_tokens; Codex
// read that as its context and compacted a 61K one. The last call keeps its
// own share; the rest is still billed, as magpie_deferred.
test("native accounting: a multi-step turn's final step reports its own share, the rest deferred (#156)", async () => {
const turnUsage = message(uint(1, 1105934), uint(2, 2100), uint(3, 1035734), uint(4, 70156), uint(5, 900))
const a = await agent({ 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)
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)
expect(u.prompt_tokens).toBeGreaterThan(0)
expect(u.total_tokens).toBe(u.prompt_tokens + u.completion_tokens)
expect(u.prompt_tokens + d.prompt_tokens).toBe(1105934)
expect(u.prompt_tokens_details.cached_tokens + d.cached_tokens).toBe(1035734)
expect(u.prompt_tokens_details.cache_write_tokens + d.cache_write_tokens).toBe(70156)
expect(u.completion_tokens + d.completion_tokens).toBe(2100)
expect(u.completion_tokens_details.reasoning_tokens).toBeLessThanOrEqual(u.completion_tokens)
})
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)
+43 -2
View File
@@ -454,6 +454,10 @@ class NativeSession {
this.retainedBytes = 0
this.sequence = 0
this.segments = 0
// the model calls of the turn so far, and what was said before the
// latest one began: the last step's own share of the turn (#156)
this.steps = 1
this.stepSaid = 0
this.said = 0
this.wrote = 0
this.terminal = false
@@ -515,6 +519,7 @@ class NativeSession {
}
this.transport = transport
this.estimate = estimate
this.stepEstimate = estimate
this.blobs = blobs
this.knownHashes = new Set(blobs.keys())
this.blobSize = [...blobs.values()].reduce((n, b) => n + b.length, 0)
@@ -571,6 +576,8 @@ class NativeSession {
this.state = "submitting"
clearTimeout(this.resultTimer)
clearTimeout(this.batchTimer)
this.batchTimer = null
this.nextStep(prepared.estimate)
try {
for (let i = 0; i < prepared.results.length; i++) {
const call = batch.calls.find((c) => c.id === prepared.results[i].tool_call_id)
@@ -620,8 +627,20 @@ class NativeSession {
this.waitForBatch()
this.sealBatch()
}
// nextStep is Cursor's next model call in the same turn: after the
// caller's results, or after a step whose calls were all answered here.
nextStep(estimate) {
this.steps++
this.stepSaid = this.said
if (estimate != null) this.stepEstimate = estimate
}
// waitForBatch gives the step batchWait from its latest call, answered
// call or count, not from its first. Cursor sends each call once the model
// has written its arguments, so a step of many long calls arrives over
// longer than batchWait while never pausing that long (#155).
waitForBatch() {
this.batchTimer ??= later(() => {
clearTimeout(this.batchTimer)
this.batchTimer = later(() => {
if (this.segment.expected == null && this.segment.calls.length && !this.resultSubmitted) this.missingCount()
else this.fail({ status: 502, message: "Cursor did not complete its declared native tool batch" })
}, this.limits.batchWait)
@@ -636,6 +655,7 @@ class NativeSession {
answeredCall() {
if (this.terminal || this.state === "awaiting-results") return
this.segment.answered++
if (this.batchTimer) this.waitForBatch()
this.sealBatch()
}
listed(count) {
@@ -659,6 +679,7 @@ class NativeSession {
segment.answered = 0
clearTimeout(this.batchTimer)
this.batchTimer = null
this.nextStep()
return
}
clearTimeout(this.batchTimer)
@@ -762,6 +783,24 @@ class NativeSession {
const u = usageOf(this.usageFields ?? [])
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.
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),
}
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)
}
const prompt = u.input + u.cacheRead + u.cacheWrite
this.finalUsage = {
prompt_tokens: prompt, completion_tokens: u.output, total_tokens: prompt + u.output,
@@ -771,8 +810,9 @@ class NativeSession {
}
this.state = "finalizing"
this.closeTransport()
const finish = (more) => {
const finish = (settled) => {
if (this.error) return
const more = earlier && settled ? Object.fromEntries(Object.keys(earlier).map((k) => [k, earlier[k] + settled[k]])) : earlier ?? settled
const deferred = more && more.input + more.output + more.cacheRead + more.cacheWrite > 0
this.segment.finish({ stop: "stop", usage: {
...this.finalUsage,
@@ -816,6 +856,7 @@ class NativeSession {
this.said += text.length
if (u.num === 1) this.wrote += text.length
this.segment.emit(u.num === 1 ? { text } : { reasoning: text })
if (this.batchTimer) this.waitForBatch()
}
} 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)
+38
View File
@@ -287,3 +287,41 @@ test("native transport: a burst of KV requests past the queue bound waits for wr
expect(most).toBeLessThanOrEqual(16)
expect(written.map((w) => number(nest(w.subarray(5), 3), 1))).toEqual(Array.from({ length: 300 }, (_, i) => 1000 + i))
})
// #155 (midmirror, Auto): a step of 13 calls, nine of them long-argument
// tools, failed after batchWait with no call delivered; the same step
// sealed on a retry that took 33s. Cursor sends each call once the model
// has written it, so the calls arrive spread over longer than batchWait
// with no single pause that long. 0.2.15 counted batchWait from the first.
test("native protocol: a step whose calls keep arriving seals past batchWait from its first call (#155)", async () => {
const { run } = owner({}, { batchWait: 300 })
const gap = () => new Promise((r) => setTimeout(r, 150))
async function* spread() {
for (const id of [7, 8, 9]) {
yield* frames([tool(id, "call-" + id, "long arguments " + id)])
await gap()
}
yield* frames([update(27, uint(1, 3))])
await new Promise(() => {})
}
run.pump(spread())
await until(() => run.error || run.state === "awaiting-results")
expect(run.error).toBeUndefined()
expect(run.segment.events.filter((e) => e.tool)).toHaveLength(3)
expect(run.segment.events.at(-1).stop).toBe("tool_calls")
})
test("native protocol: a step that stops sending fails batchWait after its latest call (#155)", async () => {
const { run } = owner({}, { batchWait: 300 })
const started = Date.now()
async function* stalled() {
yield* frames([tool(7, "call-7", "one")])
await new Promise((r) => setTimeout(r, 150))
yield* frames([tool(8, "call-8", "two"), update(27, uint(1, 3))])
await new Promise(() => {})
}
run.pump(stalled())
await until(() => run.error)
expect(run.error).toMatchObject({ status: 502, message: "Cursor did not complete its declared native tool batch" })
expect(Date.now() - started).toBeGreaterThanOrEqual(440)
})