cursor 0.2.41: new input past a parent awaiting results gets a retained Run that takes no reservation (#706)
cursor 0.2.41 (ooboqoo): new input past a parent that is awaiting results gets a retained Run that takes no reservation, so those turns stop falling back to "owner busy" and then "historical native calls" rebuilds. When a later Run of the conversation starts, a parent waiting on results owes its step at once, bounded before that start, and the later Run collects it. The collection waits until owedAt, because Cursor adds a step to a Run's one event as the step ends. If the parent's own results resume it, an uncollected count is withdrawn, and a collected one comes off its final, so the event is billed once.
Reviewed at 74a1d8b23 merged onto main 20b89389, on Linux (WSL2 Ubuntu 24.04, Bun 1.4.2):
- `bun scripts/check.mjs` OK.
- `bun test packages/cursor` three times: 400/1 once, under load, from native-http1's 100 ms writeWait test. That test isn't touched here and is filed as #754. The other two runs were 401/0. Main ran 394/0 twice.
- `native-e2e` + `native-session` + `native-http1` three times: 182/0 each. native-http1 alone five times: green.
- Broken by hand:
- The selector filter in `create` dropped: the admission test red.
- No handover: 5 red.
- No hold: 1 red.
- No withdraw: 1 red.
- No final subtraction: 1 red.
- Restored: 177/0.
- Real account: the author's runs are in the PR. 398 requests at a0f9363, with no owner busy. 144 requests at 74a1d8b, where all 15 handed-over parents were collected once.
This commit is contained in:
@@ -102,7 +102,11 @@ uses the same session/cache key and first user message as `conversation_id`, so
|
||||
Task subagents sharing their parent's session can run independently. A new
|
||||
user turn whose earlier native calls all have their results gets a retained Run
|
||||
of its own, with those calls as imported history; while any of them is still
|
||||
pending, the turn goes stateless. Retention
|
||||
pending, the turn goes stateless. New input after results already given (a
|
||||
reminder Claude Code sends beside a tool result reaches the plugin as a user
|
||||
message after it) also gets a retained Run of its own while a parent Run of
|
||||
the conversation still awaits results. That Run takes no reservation and
|
||||
leaves the parent alone; only its own calls' results resume it. Retention
|
||||
waits at most 120 seconds for a result batch and 15 minutes for a Run's total
|
||||
lifetime. A continuation arriving with less than 10 minutes of that lifetime
|
||||
left rebuilds from supplied history on a fresh Run before submitting results
|
||||
@@ -137,8 +141,8 @@ given also ends the step (#550). The step's calls are the rest.
|
||||
|
||||
These are retention limits. A missing, expired, restarted, busy, incompatible,
|
||||
or full owner uses the original history reconstruction and stateless decoder
|
||||
on a new Run. Pending parent calls and new input can take that path without
|
||||
cancelling the parent's owner. Already supplied client tool results become
|
||||
on a new Run. Pending parent calls can take that path without cancelling the
|
||||
parent's owner. Already supplied client tool results become
|
||||
history; the plugin never executes those external tools. A failed native result
|
||||
write is reported to that request because its outcome may be uncertain. A later
|
||||
request can rebuild from its supplied history without submitting the result to
|
||||
@@ -155,12 +159,22 @@ 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
|
||||
count is owed once to the same account and conversation. Successful final
|
||||
snapshots, including explicit zero, and cached replays do not enroll that debt.
|
||||
A Run still awaiting results when a later native Run of its conversation
|
||||
starts owes that count at once, for the later Run to collect, rather than at
|
||||
abandonment; what it had collected and not given out goes along. Cursor adds
|
||||
each step to a Run's one event as the step ends, so that event is looked for
|
||||
only `owedAt` (5 seconds) after the handover; a final waits for it. If its own
|
||||
results resume it after all, a count not collected yet is withdrawn, and one
|
||||
already collected comes off its final (from the earlier calls' share first),
|
||||
so the event is billed once.
|
||||
|
||||
Dashboard attribution uses event timestamps, rather than when events arrive.
|
||||
Older debt is bounded strictly before the native Run's start, and keeps that
|
||||
bound across later stateless Runs so an authoritative native event is not
|
||||
billed again. An earlier event stamped on or after that boundary cannot be
|
||||
identified reliably and stays unknown. Missing or ambiguous debt expires after
|
||||
billed again. A Run abandoned after a later native Run of its conversation
|
||||
started owes with the same bound, before that later start. An earlier event
|
||||
stamped on or after that boundary cannot be identified reliably and stays
|
||||
unknown. Missing or ambiguous debt expires after
|
||||
10 minutes; at most 64 distinct bounded debt groups are kept per account and
|
||||
conversation, dropping the oldest on overflow. These counts are never guessed
|
||||
as prior usage. Stateless Runs otherwise keep the dashboard accounting above.
|
||||
|
||||
+96
-11
@@ -2014,11 +2014,13 @@ function addUsage(a, b) {
|
||||
// event timestamps before its start: its authoritative final must never be
|
||||
// collected as an earlier Run. Keep that bound when a later stateless Run
|
||||
// adds unbounded debt. Ordinary stateless debt retains its original shape.
|
||||
// A debt owed with a tag is one Run's event, kept in a group of its own: the
|
||||
// tag says whether a step collected it (and what) or the Run withdrew it.
|
||||
const DEBT_GROUP_LIMIT = 64
|
||||
function owe(key, { since = Date.now(), n = 0, ready = Date.now(), carry = null, before }) {
|
||||
function owe(key, { since = Date.now(), n = 0, ready = Date.now(), carry = null, before, tag }) {
|
||||
for (const [k, d] of owed) {
|
||||
if (d.groups) {
|
||||
d.groups = d.groups.filter((g) => Date.now() - g.since <= STEP_WAIT.owedFor)
|
||||
d.groups = d.groups.filter((g) => Date.now() - g.since <= STEP_WAIT.owedFor && g.tag?.state !== "withdrawn")
|
||||
d.n = d.groups.reduce((sum, g) => sum + g.n, 0)
|
||||
if (Date.now() - d.since > STEP_WAIT.owedFor) d.carry = null
|
||||
if (!d.n && !d.carry) owed.delete(k)
|
||||
@@ -2027,15 +2029,16 @@ function owe(key, { since = Date.now(), n = 0, ready = Date.now(), carry = null,
|
||||
}
|
||||
if (n <= 0 && !carry) return
|
||||
const d = owed.get(key)
|
||||
if (!d && tag) return void owed.set(key, { since, n, ready, carry: carry && { ...carry }, groups: [{ since, n, ready, before, tag }] })
|
||||
if (!d) return void owed.set(key, { since, n, ready, carry: carry && { ...carry }, ...(before !== undefined ? { before } : {}) })
|
||||
if (n > 0 && (d.groups || d.before !== undefined || before !== undefined)) {
|
||||
if (n > 0 && (d.groups || d.before !== undefined || before !== undefined || tag)) {
|
||||
const groups = d.groups ?? (d.n > 0 ? [{ since: d.since, n: d.n, ready: d.ready, before: d.before }] : [])
|
||||
const same = groups.find((g) => g.before === before)
|
||||
const same = !tag && groups.find((g) => !g.tag && g.before === before)
|
||||
if (same) {
|
||||
same.since = Math.min(same.since, since)
|
||||
same.n += n
|
||||
same.ready = Math.min(same.ready, ready)
|
||||
} else groups.push({ since, n, ready, before })
|
||||
} else groups.push({ since, n, ready, before, ...(tag ? { tag } : {}) })
|
||||
// As with expired dashboard debt, overflow stays unknown, never estimated
|
||||
// or merged across bounds into an authoritative native Run's event.
|
||||
groups.sort((a, b) => a.since - b.since)
|
||||
@@ -2051,6 +2054,19 @@ function owe(key, { since = Date.now(), n = 0, ready = Date.now(), carry = null,
|
||||
d.carry = addUsage(d.carry, carry)
|
||||
}
|
||||
|
||||
// withdraw takes back the debt owed with tag while no step has collected it:
|
||||
// its Run was resumed after all, and its own final counts its event.
|
||||
function withdraw(key, tag) {
|
||||
if (tag.state !== "owed") return
|
||||
tag.state = "withdrawn"
|
||||
const d = owed.get(key)
|
||||
if (!d?.groups) return
|
||||
d.groups = d.groups.filter((g) => g.tag !== tag)
|
||||
d.n = d.groups.reduce((sum, g) => sum + g.n, 0)
|
||||
if (!d.n && !d.carry) owed.delete(key)
|
||||
else if (d.groups.length) d.since = Math.min(...d.groups.map((g) => g.since))
|
||||
}
|
||||
|
||||
// usageEvents are the dashboard's events of conversation conv from since
|
||||
// on, the `want` oldest not counted yet, summed: usage (null when none),
|
||||
// each with its time (events), how many were found (got), and refused
|
||||
@@ -2094,12 +2110,17 @@ async function usageEvents(tok, conv, since, want, { poll = false, first = STEP_
|
||||
// found already excludes timestamps claimed by earlier fetches. Two
|
||||
// distinct events in this response may share a millisecond; count both.
|
||||
if (at >= before()) continue
|
||||
const group = groups?.findIndex((g, i) => counts[i] < g.n && at >= g.since - 1000 && at < (g.before ?? Infinity))
|
||||
const group = groups?.findIndex((g, i) => counts[i] < g.n && g.tag?.state !== "withdrawn" && at >= g.since - 1000 && at < (g.before ?? Infinity))
|
||||
if (groups && group === -1) continue
|
||||
if (groups) counts[group]++
|
||||
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 }
|
||||
const tag = groups?.[group].tag
|
||||
if (tag) {
|
||||
tag.state = "collected"
|
||||
tag.usage = addUsage(tag.usage, u)
|
||||
}
|
||||
usage = addUsage(usage ?? ZERO(), u)
|
||||
events.push({ at: num(ev.timestamp), usage: u })
|
||||
got++
|
||||
@@ -2128,8 +2149,15 @@ function collect(tok, conv, { poll = false, first, signal, over = () => false, a
|
||||
const d = owed.get(key)
|
||||
if (!d) return Promise.resolve({ usage: null, carry: null, events: [], short: false })
|
||||
owed.delete(key)
|
||||
// A handed-over Run's event still grows by the step that Run just ended
|
||||
// (Cursor adds each step to a Run's one event as the step ends). It is
|
||||
// looked for only from its own ready on, whatever else is owed with it
|
||||
// sooner: until then it stays owed.
|
||||
const now = Date.now()
|
||||
const held = d.groups?.filter((g) => g.tag?.state === "owed" && g.ready > now) ?? []
|
||||
for (const g of held) owe(key, { since: g.since, n: g.n, ready: g.ready, before: g.before, tag: g.tag })
|
||||
const p = (async () => {
|
||||
const groups = (d.groups ?? [d]).filter((g) => (g.before === undefined && !d.groups) || Date.now() - g.since <= STEP_WAIT.owedFor)
|
||||
const groups = (d.groups ?? [d]).filter((g) => !held.includes(g) && g.tag?.state !== "withdrawn" && ((g.before === undefined && !d.groups) || Date.now() - g.since <= STEP_WAIT.owedFor))
|
||||
const want = groups.reduce((sum, g) => sum + g.n, 0)
|
||||
let r = { usage: null, events: [], got: 0 }
|
||||
if (want > 0 && canRead(tok)) r = await usageEvents(tok, conv, Math.min(...groups.map((g) => g.since)), want, {
|
||||
@@ -2138,9 +2166,10 @@ function collect(tok, conv, { poll = false, first, signal, over = () => false, a
|
||||
let short = false
|
||||
for (const [i, g] of groups.entries()) {
|
||||
const remaining = g.n - (d.groups ? r.counts?.[i] ?? 0 : r.got)
|
||||
if (remaining > 0 && canRead(tok)) {
|
||||
// a tag withdrawn while this was asked is its Run's own again
|
||||
if (remaining > 0 && canRead(tok) && g.tag?.state !== "withdrawn") {
|
||||
short = true
|
||||
owe(key, { since: g.since, n: remaining, ready: g.ready, before: g.before })
|
||||
owe(key, { since: g.since, n: remaining, ready: g.ready, before: g.before, tag: g.tag })
|
||||
}
|
||||
}
|
||||
const carry = d.carry && { ...d.carry }
|
||||
@@ -2200,10 +2229,21 @@ function ledger(tok, conv, since, signal, kept, { before } = {}) {
|
||||
}
|
||||
return r
|
||||
})
|
||||
// heldUntil is when the latest handed-over event still held back
|
||||
// (collect) becomes ready; 0 when none is
|
||||
const heldUntil = () => {
|
||||
const now = Date.now()
|
||||
return Math.max(0, ...(owed.get(debtKey)?.groups ?? []).filter((g) => g.tag?.state === "owed" && g.ready > now).map((g) => g.ready))
|
||||
}
|
||||
let collecting = null
|
||||
const debt = kept ? owed.get(debtKey) : undefined
|
||||
const timer = debt ? setTimeout(() => (collecting = gather()), Math.max(0, debt.ready - Date.now())) : null
|
||||
timer?.unref?.()
|
||||
const sleep = (ms) => new Promise((r) => {
|
||||
if (signal?.aborted) return r()
|
||||
const t = setTimeout(r, ms)
|
||||
signal?.addEventListener("abort", () => (clearTimeout(t), r()), { once: true })
|
||||
})
|
||||
const takeMine = () => {
|
||||
const u = mine
|
||||
mine = null
|
||||
@@ -2239,10 +2279,27 @@ function ledger(tok, conv, since, signal, kept, { before } = {}) {
|
||||
if (final) {
|
||||
await collecting
|
||||
await Promise.all([...(flights.get(debtKey) ?? [])])
|
||||
// a handed-over event held back is waited for, up to its ready
|
||||
const until = heldUntil()
|
||||
if (until) await sleep(until - Date.now())
|
||||
await Promise.all([...(flights.get(debtKey) ?? [])])
|
||||
if (owed.has(debtKey)) await gather({ poll: owed.get(debtKey).n > 0, first: 0, signal })
|
||||
}
|
||||
return take()
|
||||
},
|
||||
// handover: a later Run of the conversation began while this one waits
|
||||
// on the caller's results. That Run collects from here on: what this one
|
||||
// collected and has not given out goes to it, as does what an ask still
|
||||
// going brings. A step that ends this Run after all still collects.
|
||||
handover() {
|
||||
clearTimeout(timer)
|
||||
const give = () => {
|
||||
const u = take()
|
||||
if (u) owe(debtKey, { carry: u })
|
||||
}
|
||||
give()
|
||||
collecting?.then(give, () => {})
|
||||
},
|
||||
done() {
|
||||
over = true
|
||||
clearTimeout(timer)
|
||||
@@ -2700,8 +2757,32 @@ async function runNative({ tok, base, id, tools, conv, convID, signal, maxMode,
|
||||
const book = ledger(tok, cid, since, accounting.signal, !!convID, { before: since })
|
||||
const debtKey = usageKey(tok, cid)
|
||||
let started = false, settled = false, deferred = null
|
||||
// handed is this Run's step owed at a later Run's start while this one
|
||||
// waited on results (handover): owed, collected (and what), or withdrawn
|
||||
let handed = null
|
||||
const owes = () => started && native.segments > 0 && !native.finalUsage && convID && canRead(tok)
|
||||
native.accounting = {
|
||||
started() { started = true },
|
||||
// A later Run of the conversation began (NativeSessionPool.create) while
|
||||
// this one waits on the caller's results. Its step's event is owed now,
|
||||
// bounded before that start, for the later Run to collect, rather than
|
||||
// when this one is abandoned at resultWait. Cursor stamps a Run's one
|
||||
// event at its start and adds each step to it as the step ends.
|
||||
handover() {
|
||||
if (settled || handed && handed.state !== "withdrawn" || !owes()) return
|
||||
handed = { state: "owed" }
|
||||
owe(debtKey, { since, n: 1, ready: Date.now() + STEP_WAIT.owedAt, before: native.laterRunAt, tag: handed })
|
||||
book.handover()
|
||||
},
|
||||
// resumed by its own results after all: a step not collected yet is this
|
||||
// Run's to count again, in its final; one collected is counted (below)
|
||||
resumed() {
|
||||
if (handed?.state === "owed") withdraw(debtKey, handed)
|
||||
},
|
||||
// what a later Run collected of this Run's event: its final leaves it out
|
||||
counted() {
|
||||
return handed?.state === "collected" ? handed.usage : null
|
||||
},
|
||||
async settle() {
|
||||
const more = await book.owed(true)
|
||||
if (settled) {
|
||||
@@ -2725,10 +2806,14 @@ async function runNative({ tok, base, id, tools, conv, convID, signal, maxMode,
|
||||
accounting.abort()
|
||||
if (deferred) owe(debtKey, { carry: deferred })
|
||||
deferred = null
|
||||
// a step handed over is owed already, or was collected
|
||||
if (handed && handed.state !== "withdrawn") return
|
||||
// Every handoff of this owner belongs to one Run. Only an abandoned
|
||||
// started/pending Run is owed; a final snapshot (including zero) is not.
|
||||
if (started && native.segments > 0 && !native.finalUsage && convID && canRead(tok)) {
|
||||
owe(debtKey, { since, n: 1, ready: Date.now() + STEP_WAIT.owedAt })
|
||||
if (owes()) {
|
||||
// laterRunAt: a later Run of this conversation began while this one
|
||||
// was live (NativeSessionPool.create); its events are not this debt
|
||||
owe(debtKey, { since, n: 1, ready: Date.now() + STEP_WAIT.owedAt, before: native.laterRunAt })
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
@@ -476,7 +476,7 @@ test("native retention: cross-account continuation rebuilds history without writ
|
||||
expect(owner.state).toBe("awaiting-results")
|
||||
})
|
||||
|
||||
for (const kind of ["same first user", "different tools", "pending ancestor", "new input"]) test(`native retention: busy owner with ${kind} falls back without cancelling its live parent`, async () => {
|
||||
for (const kind of ["same first user", "different tools", "pending ancestor"]) test(`native retention: busy owner with ${kind} falls back without cancelling its live parent`, async () => {
|
||||
const a = await agent(), account = auth(), chat = initial()
|
||||
const first = await a.ask(account, chat)
|
||||
const owner = [...nativeSessions.entries][0]
|
||||
@@ -487,7 +487,6 @@ for (const kind of ["same first user", "different tools", "pending ancestor", "n
|
||||
branch.messages.push(choice(first).message, { role: "user", content: "child request includes a pending parent Task" })
|
||||
marker = "Tool use was interrupted and did not produce a result."
|
||||
}
|
||||
if (kind === "new input") { branch = continueWith(chat, first.body, ["already-provided"]); branch.messages.push({ role: "user", content: "branch on new input" }); marker = "already-provided" }
|
||||
rebuilt(await a.ask(account, branch), marker)
|
||||
expect(owner.state).toBe("awaiting-results")
|
||||
expect(owner.error).toBeUndefined()
|
||||
@@ -500,6 +499,58 @@ for (const kind of ["same first user", "different tools", "pending ancestor", "n
|
||||
expect(a.runs).toHaveLength(2)
|
||||
})
|
||||
|
||||
// Claude Code's reminders: a tool result with text beside it reaches the
|
||||
// plugin as the tool message, then a user message (magpie's chat.go).
|
||||
const withNewInput = (chat, reply, values, text) => {
|
||||
const next = continueWith(chat, reply, values)
|
||||
next.messages.push({ role: "user", content: text })
|
||||
return next
|
||||
}
|
||||
|
||||
test("native retention: new input past a busy owner gets an owner of its own and leaves the parent's reservation", async () => {
|
||||
const a = await agent({ finalAfterFirst: true }), account = auth(), chat = initial()
|
||||
const first = await a.ask(account, chat)
|
||||
const parent = [...nativeSessions.entries][0]
|
||||
const key = parent.account + ":" + parent.selector
|
||||
const branch = withNewInput(chat, first.body, ["already-provided"], "branch on new input")
|
||||
const res = await a.ask(account, branch)
|
||||
expect(res.status).toBe(200)
|
||||
expect(choice(res).message.content).toContain("rebuilt:already-provided")
|
||||
expect(res.diagnostic).toMatch(/^same-run;/)
|
||||
expect(nativeSessions.entries.size).toBe(2)
|
||||
expect(nativeSessions.selectors.get(key)).toBe(parent)
|
||||
expect(parent.state).toBe("awaiting-results")
|
||||
expect(parent.error).toBeUndefined()
|
||||
expect(parent.transportClosed).not.toBe(true)
|
||||
expect(a.results).toEqual([])
|
||||
expect(a.runs).toHaveLength(2)
|
||||
const second = await a.ask(account, continueWith(chat, first.body, ["parent result"]))
|
||||
expect(second.status).toBe(200)
|
||||
expect(second.diagnostic).toMatch(/^same-run;/)
|
||||
expect(choice(second).message.content).toBe("parent result")
|
||||
expect(a.results).toHaveLength(1)
|
||||
expect(a.runs).toHaveLength(2)
|
||||
})
|
||||
|
||||
test("native retention: an owner past a busy reservation is resumed by its own calls' results", async () => {
|
||||
const a = await agent({ finalAfterFirst: true, toolRuns: [1, 2] }), account = auth(), chat = initial()
|
||||
const first = await a.ask(account, chat)
|
||||
const parent = [...nativeSessions.entries][0]
|
||||
const branch = withNewInput(chat, first.body, ["already-provided"], "the user hasn't heard from you")
|
||||
const step = await a.ask(account, branch)
|
||||
expect(step.status).toBe(200)
|
||||
expect(choice(step).finish_reason).toBe("tool_calls")
|
||||
const own = [...nativeSessions.entries].find((e) => e !== parent)
|
||||
expect(choice(step).message.tool_calls[0].id).toContain(own.identity)
|
||||
const next = await a.ask(account, continueWith(branch, step.body, ["its own result"]))
|
||||
expect(next.status).toBe(200)
|
||||
expect(next.diagnostic).toMatch(/^same-run;/)
|
||||
expect(choice(next).message.content).toBe("its own result")
|
||||
expect(a.results.map((r) => r.content[0].text)).toEqual(["its own result"])
|
||||
expect(a.runs).toHaveLength(2)
|
||||
expect(parent.state).toBe("awaiting-results")
|
||||
})
|
||||
|
||||
for (const bound of ["perAccount", "perProcess"]) test(`native retention: ${bound} capacity selects production stateless fallback`, async () => {
|
||||
NATIVE_LIMITS[bound] = 1
|
||||
const a = await agent(), account = auth(), chat = initial()
|
||||
@@ -1493,6 +1544,159 @@ test("native accounting: missing E1 stays bounded past authoritative E2 and a la
|
||||
expect(a.errors).toEqual([])
|
||||
})
|
||||
|
||||
test("native accounting: a parent lost after an owner past its reservation started never collects that owner's event", async () => {
|
||||
const a = await agent({ rebuildUsage: NATIVE_FINAL_USAGE })
|
||||
const account = auth(), chat = initial()
|
||||
const first = await a.ask(account, chat)
|
||||
expect(first.body.usage).toMatchObject({ total_tokens: 0, magpie_native: { accounting: "pending" } })
|
||||
const parent = [...nativeSessions.entries][0]
|
||||
const earlier = eventFor(a, 0, EARLIER_USAGE)
|
||||
const key = _internal.usageKey(account.access, earlier.conversationId)
|
||||
await afterEvent(earlier)
|
||||
const branch = withNewInput(chat, first.body, ["already-provided"], "new input past the busy parent")
|
||||
const second = await a.ask(account, branch)
|
||||
expect(second.diagnostic).toMatch(/^same-run;/)
|
||||
expect(second.body.usage).toMatchObject({ prompt_tokens: 215, completion_tokens: 5, total_tokens: 220 })
|
||||
expect(second.body.usage.magpie_deferred).toBeUndefined()
|
||||
// the branch's own event shows; the parent's never does
|
||||
const later = eventFor(a, 1, LATER_USAGE)
|
||||
await afterEvent(later)
|
||||
a.events.push(later)
|
||||
await parent.cancel("the parent is lost after its branch began")
|
||||
// owed once, at the branch's start, and bounded before it
|
||||
expect(_internal.owed.get(key)?.n).toBe(1)
|
||||
expect(Math.max(..._internal.owed.get(key).groups.map((g) => g.before))).toBeLessThanOrEqual(a.started[1])
|
||||
NATIVE_LIMITS.perProcess = 0
|
||||
const thirdChat = { ...branch, messages: [...branch.messages, choice(second).message, { role: "user", content: "E3 while the parent's event is missing" }] }
|
||||
const third = await a.ask(account, thirdChat)
|
||||
expect(third.status).toBe(200)
|
||||
expect(third.diagnostic).toMatch(/^stateless;/)
|
||||
expect(third.body.usage.magpie_deferred).toBeUndefined()
|
||||
expect(_internal.owed.get(key)?.n).toBe(1)
|
||||
a.events.push(earlier)
|
||||
const fourth = await a.ask(account, thirdChat)
|
||||
expect(fourth.body.usage.magpie_deferred).toEqual(EARLIER_DEFERRED)
|
||||
expect(_internal.owed.has(key)).toBe(false)
|
||||
expect(a.results).toEqual([])
|
||||
expect(a.errors).toEqual([])
|
||||
})
|
||||
|
||||
// A session that ends while a parent still waits out resultWait: nothing
|
||||
// after the unreserved Run would collect what the parent owes at abandon.
|
||||
test("native accounting: a parent waiting behind an owner past its reservation is collected by that owner, once", async () => {
|
||||
const a = await agent({ rebuildUsage: NATIVE_FINAL_USAGE })
|
||||
const account = auth(), chat = initial()
|
||||
const first = await a.ask(account, chat)
|
||||
const parent = [...nativeSessions.entries][0]
|
||||
const earlier = eventFor(a, 0, EARLIER_USAGE)
|
||||
const key = _internal.usageKey(account.access, earlier.conversationId)
|
||||
await afterEvent(earlier)
|
||||
a.events.push(earlier) // stamped before the branch begins, as all 61 were
|
||||
const branch = withNewInput(chat, first.body, ["already-provided"], "the user hasn't heard from you")
|
||||
const second = await a.ask(account, branch)
|
||||
expect(second.diagnostic).toMatch(/^same-run;/)
|
||||
expect(parent.state).toBe("awaiting-results")
|
||||
expect(second.body.usage).toMatchObject({ prompt_tokens: 215, completion_tokens: 5, magpie_deferred: EARLIER_DEFERRED })
|
||||
expect(_internal.owed.has(key)).toBe(false)
|
||||
// the session ends here: the parent runs out its result wait, owing nothing more
|
||||
parent.fail({ status: 410, message: "native tool-result deadline expired" }, "expired")
|
||||
expect(_internal.owed.has(key)).toBe(false)
|
||||
NATIVE_LIMITS.perProcess = 0
|
||||
const later = await a.ask(account, { ...branch, messages: [...branch.messages, choice(second).message, { role: "user", content: "after the parent expired" }] })
|
||||
expect(later.diagnostic).toMatch(/^stateless;/)
|
||||
expect(later.body.usage.magpie_deferred).toBeUndefined()
|
||||
expect(a.results).toEqual([])
|
||||
expect(a.errors).toEqual([])
|
||||
})
|
||||
|
||||
// Cursor adds each step to a Run's one event as the step ends, seconds
|
||||
// later at times. A parent holding an earlier debt it collected hands it
|
||||
// over with its step: the later Run asks at once for that debt, and must
|
||||
// not take the parent's event before its last step is in it.
|
||||
test("native accounting: a handed-over parent's event is collected only once its last step is in it", async () => {
|
||||
const partial = { inputTokens: 5, outputTokens: 2, cacheReadTokens: 40, cacheWriteTokens: 0 }
|
||||
const whole = { inputTokens: 6, outputTokens: 4, cacheReadTokens: 90, cacheWriteTokens: 1 }
|
||||
let parentEvent = null
|
||||
const a = await agent({ toolRuns: [1, 2], rebuildUsage: NATIVE_FINAL_USAGE, dashboard: async (fake) => {
|
||||
const events = [...fake.events]
|
||||
// the parent's last step shows 600 ms after the branch began
|
||||
if (parentEvent) events.push({ ...parentEvent, tokenUsage: fake.runs.length >= 3 && Date.now() - fake.started[2] >= 600 ? whole : partial })
|
||||
return Response.json({ usageEventsDisplay: events })
|
||||
} })
|
||||
const account = auth(), chat = initial()
|
||||
// R0 hands off and is lost: it owes E0
|
||||
const first = await a.ask(account, chat)
|
||||
await [...nativeSessions.entries][0].cancel("R0 is lost")
|
||||
const earlier = eventFor(a, 0, EARLIER_USAGE)
|
||||
const key = _internal.usageKey(account.access, earlier.conversationId)
|
||||
expect(_internal.owed.get(key)?.n).toBe(1)
|
||||
await afterEvent(earlier)
|
||||
a.events.push(earlier)
|
||||
// the next turn's owner collects E0 in the background, then waits on its own call
|
||||
const turn = { ...chat, messages: [...continueWith(chat, first.body, ["R0 result"]).messages, { role: "user", content: "next turn" }] }
|
||||
const step = await a.ask(account, turn)
|
||||
expect(step.diagnostic).toMatch(/^same-run;/)
|
||||
expect(choice(step).finish_reason).toBe("tool_calls")
|
||||
const parent = [...nativeSessions.entries].find((e) => e.state === "awaiting-results")
|
||||
for (const deadline = Date.now() + 3000; _internal.owed.has(key) && Date.now() < deadline;) await new Promise((r) => setTimeout(r, 10))
|
||||
expect(_internal.owed.has(key)).toBe(false)
|
||||
parentEvent = eventFor(a, 1, partial)
|
||||
await afterEvent(parentEvent)
|
||||
const branch = withNewInput(turn, step.body, ["already-provided"], "the user hasn't heard from you")
|
||||
const second = await a.ask(account, branch)
|
||||
expect(second.diagnostic).toMatch(/^same-run;/)
|
||||
expect(parent.state).toBe("awaiting-results")
|
||||
// E0 and the parent's whole event: 118 + 97 in, 3 + 4 out
|
||||
expect(second.body.usage).toMatchObject({ prompt_tokens: 215, completion_tokens: 5, magpie_deferred: { prompt_tokens: 215, completion_tokens: 7, cached_tokens: 190, cache_write_tokens: 8 } })
|
||||
expect(_internal.owed.has(key)).toBe(false)
|
||||
parent.fail({ status: 410, message: "native tool-result deadline expired" }, "expired")
|
||||
expect(_internal.owed.has(key)).toBe(false)
|
||||
expect(a.results).toEqual([])
|
||||
expect(a.errors).toEqual([])
|
||||
})
|
||||
|
||||
// Owed at the branch's start, the parent can still be resumed by its own
|
||||
// result: its final, the whole turn's, must not count that step again.
|
||||
const PARENT_STEP_USAGE = { inputTokens: 5, outputTokens: 2, cacheReadTokens: 4, cacheWriteTokens: 0 }
|
||||
const sumOf = (u) => {
|
||||
const d = u.magpie_deferred ?? { prompt_tokens: 0, completion_tokens: 0, cached_tokens: 0, cache_write_tokens: 0 }
|
||||
return { prompt: u.prompt_tokens + d.prompt_tokens, output: u.completion_tokens + d.completion_tokens, cached: u.prompt_tokens_details.cached_tokens + d.cached_tokens }
|
||||
}
|
||||
for (const when of ["after the branch collected it", "before anything collected it"]) test(`native accounting: a parent resumed ${when} counts its step once`, async () => {
|
||||
const a = await agent({ finalAfterFirst: true, rebuildUsage: NATIVE_FINAL_USAGE })
|
||||
const account = auth(), chat = initial()
|
||||
const first = await a.ask(account, chat)
|
||||
const parent = [...nativeSessions.entries][0]
|
||||
const step = eventFor(a, 0, PARENT_STEP_USAGE)
|
||||
const key = _internal.usageKey(account.access, step.conversationId)
|
||||
await afterEvent(step)
|
||||
const collected = when === "after the branch collected it"
|
||||
if (collected) a.events.push(step)
|
||||
const second = await a.ask(account, withNewInput(chat, first.body, ["already-provided"], "the user hasn't heard from you"))
|
||||
expect(second.diagnostic).toMatch(/^same-run;/)
|
||||
if (collected) {
|
||||
expect(second.body.usage.magpie_deferred).toEqual({ prompt_tokens: 9, completion_tokens: 2, cached_tokens: 4, cache_write_tokens: 0 })
|
||||
expect(_internal.owed.has(key)).toBe(false)
|
||||
} else {
|
||||
expect(second.body.usage.magpie_deferred).toBeUndefined()
|
||||
expect(_internal.owed.get(key)?.n).toBe(1)
|
||||
}
|
||||
const resumed = await a.ask(account, continueWith(chat, first.body, ["parent result"]))
|
||||
expect(resumed.diagnostic).toMatch(/^same-run;/)
|
||||
expect(choice(resumed).message.content).toBe("parent result")
|
||||
expect(parent.state).toBe("complete")
|
||||
// the turn's TurnEnded: 13 uncached + 10 read in, 7 out
|
||||
expect(sumOf(resumed.body.usage)).toEqual(collected ? { prompt: 14, output: 5, cached: 6 } : { prompt: 23, output: 7, cached: 10 })
|
||||
expect(_internal.owed.has(key)).toBe(false)
|
||||
if (!collected) a.events.push(step) // its event shows only now
|
||||
NATIVE_LIMITS.perProcess = 0
|
||||
const later = await a.ask(account, { ...chat, messages: [...continueWith(chat, first.body, ["parent result"]).messages, choice(resumed).message, { role: "user", content: "next turn" }] })
|
||||
expect(later.diagnostic).toMatch(/^stateless;/)
|
||||
expect(later.body.usage.magpie_deferred).toBeUndefined()
|
||||
expect(a.results).toHaveLength(1)
|
||||
expect(a.errors).toEqual([])
|
||||
})
|
||||
|
||||
test("native accounting: an event exactly at native start remains unknown and bounded debt expires", async () => {
|
||||
NATIVE_LIMITS.perProcess = 0
|
||||
const clock = Date.now
|
||||
|
||||
@@ -805,7 +805,15 @@ export class NativeSessionPool {
|
||||
const freshTurn = last?.role === "user" && !toolAttachment(last)
|
||||
if (!freshTurn || historical.some((c) => !answered.has(c.id))) return fallback("historical native calls")
|
||||
}
|
||||
if (selector && this.selectors.has(account + ":" + selector)) return fallback("owner busy")
|
||||
if (selector && this.selectors.has(account + ":" + selector)) {
|
||||
if (!historical.length) return fallback("owner busy")
|
||||
// New input after results the caller already gave its native calls
|
||||
// (Claude Code sends a reminder beside a tool result, which a chat
|
||||
// request carries as a user message after the tool message). The
|
||||
// reservation's holder, a parent awaiting results, is left as it is:
|
||||
// this Run takes no reservation, and only its own calls resume it.
|
||||
return { account, selector, controls, selected: false, chat }
|
||||
}
|
||||
return { account, selector, controls, selected: !!selector, chat }
|
||||
}
|
||||
create(prepared, resolution, wire) {
|
||||
@@ -823,6 +831,17 @@ export class NativeSessionPool {
|
||||
if (!(e instanceof NativeSessionError)) throw e
|
||||
return null
|
||||
}
|
||||
// A Run of this conversation still live may be abandoned after this one
|
||||
// starts: what it then owes is bounded before this start, so this Run's
|
||||
// own dashboard events are never collected as its debt.
|
||||
// One that waits on the caller's results owes its step now, for this
|
||||
// Run to collect, rather than when it is abandoned at resultWait.
|
||||
const at = Date.now()
|
||||
for (const e of this.entries) {
|
||||
if (e.account !== owner.account || !e.selector || e.selector !== owner.selector) continue
|
||||
e.laterRunAt ??= at
|
||||
if (e.state === "awaiting-results") e.accounting?.handover()
|
||||
}
|
||||
this.entries.add(owner)
|
||||
if (prepared.selected) this.selectors.set(owner.account + ":" + owner.selector, owner)
|
||||
return owner
|
||||
@@ -1004,6 +1023,9 @@ class NativeSession {
|
||||
batch.next = next
|
||||
this.segment = next
|
||||
this.state = "submitting"
|
||||
// a step owed at a later Run's start and not collected yet is this Run's
|
||||
// to count again, in its own final
|
||||
this.accounting?.resumed()
|
||||
clearTimeout(this.resultTimer)
|
||||
clearTimeout(this.batchTimer)
|
||||
this.batchTimer = null
|
||||
@@ -1265,6 +1287,15 @@ class NativeSession {
|
||||
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
|
||||
// the earlier steps' share first, so the event counts once.
|
||||
const counted = this.accounting?.counted?.()
|
||||
if (counted) for (const k of ["input", "cacheRead", "cacheWrite", "output"]) {
|
||||
const off = Math.min(earlier?.[k] ?? 0, counted[k] ?? 0)
|
||||
if (earlier) earlier[k] -= off
|
||||
u[k] = Math.max(0, u[k] - ((counted[k] ?? 0) - off))
|
||||
}
|
||||
const prompt = u.input + u.cacheRead + u.cacheWrite
|
||||
this.finalUsage = {
|
||||
prompt_tokens: prompt, completion_tokens: u.output, total_tokens: prompt + u.output,
|
||||
|
||||
@@ -156,6 +156,34 @@ test("native admission: a fresh user turn whose old native calls all have result
|
||||
expect(pool.prepare("synthetic-token", { messages: answered.slice(0, 3) }, "synthetic-session", registered).fallback).toBe("owner unavailable")
|
||||
})
|
||||
|
||||
test("native admission: answered native calls and new input past a held reservation get an owner that takes no reservation", () => {
|
||||
const { pool, run } = owner()
|
||||
const key = run.account + ":" + run.selector
|
||||
const id = "call_cursor_abcdef_0_0"
|
||||
const call = { role: "assistant", content: "", tool_calls: [{ id, type: "function", function: { name: "audit_echo", arguments: "{}" } }] }
|
||||
const messages = [{ role: "user", content: "synthetic" }, call, { role: "tool", tool_call_id: id, content: "done" }, { role: "user", content: "a reminder beside the result" }]
|
||||
const prepared = pool.prepare("synthetic-token", chat({ messages }), "synthetic-session", registered)
|
||||
expect(prepared.fallback).toBeUndefined()
|
||||
expect(prepared.selected).toBe(false)
|
||||
// with no native call in its history, a request past the reservation is a branch, as before
|
||||
expect(pool.prepare("synthetic-token", chat(), "synthetic-session", registered).fallback).toBe("owner busy")
|
||||
// another conversation of the same account, live in the same pool
|
||||
const another = pool.prepare("synthetic-token", chat({ messages: [{ role: "user", content: "another conversation" }] }), "another-session", registered)
|
||||
expect(another.selected).toBe(true)
|
||||
const other = pool.create(another, run.resolution, _internal)
|
||||
expect(other.account).toBe(run.account)
|
||||
expect(other.selector).not.toBe(run.selector)
|
||||
const next = pool.create(prepared, run.resolution, _internal)
|
||||
expect(next).not.toBeNull()
|
||||
expect(pool.selectors.get(key)).toBe(run)
|
||||
// the holder, still live, owes only what came before this Run; another conversation is untouched
|
||||
expect(run.laterRunAt).toBeNumber()
|
||||
expect(next.laterRunAt).toBeUndefined()
|
||||
expect(other.laterRunAt).toBeUndefined()
|
||||
pool.release(next)
|
||||
expect(pool.selectors.get(key)).toBe(run)
|
||||
})
|
||||
|
||||
test("native admission: completed replay entries are bounded; active entries are preserved", () => {
|
||||
const { pool, run } = owner({}, { perAccount: 2, perProcess: 2 })
|
||||
run.terminalSeen(nativeFields(message(uint(1, 0), uint(2, 0))))
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-cursor-auth",
|
||||
"version": "0.2.40",
|
||||
"version": "0.2.41",
|
||||
"description": "Cursor subscriptions (Pro, Pro+, Ultra, Teams) in OpenCode and magpie, through the API cursor-agent talks to",
|
||||
"type": "module",
|
||||
"main": "./opencode.mjs",
|
||||
|
||||
Reference in New Issue
Block a user