cursor 0.2.21: a Run Cursor stops answering ends, retained or stateless (yetone/magpie#2672) (#364)
A Run Cursor stops answering mid-turn now ends with a 502 that says so,
on both the stateless path (runOnce/decode) and the retained path
(NativeSession.pump), instead of holding the reply open until the agent
gives up (yetone/magpie#2672: two composer-2.5 turns waited 305 s).
Quiet wraps a Run's frames: 60 s with no message at all, or 240 s with
only Cursor's heartbeats (InteractionUpdate.heartbeat), ends it. Only
time spent waiting on Cursor's next frame counts; a retained Run parked
for the caller's tool results is paused (resultWait bounds it) and
resumes from nothing after the submit. Each frame gets a fresh wake
promise, so frames already passed on are not held for the stream's life
(review of cbd5d3b). cursor 0.2.20 -> 0.2.21.
Run at the reviewed head 6a17d61 (base 79e383c; main 8d687ad since
touched only kimi-work), Bun 1.4.2, sandbox HOME:
- packages/cursor `bun test`: 288 pass, 0 fail (17 files).
- `bun scripts/check.mjs`: every package ok.
- 20,000 frames of 50 KB through Quiet.frames with the stream left
open: 95 MB RSS (1376 MB at cbd5d3b).
Broken by hand, each red:
- the long-lived `gone` promise put back: the WeakRef frames test fails;
- heartbeats counted as frames: both heartbeats-only tests fail;
- stateless path unwrapped: 3 stateless tests fail;
- resume() leaving the Run paused: no test went red. A test for it
(a continued Run going quiet after the caller's results) follows in
its own commit; red with that break, green at this head.
- decode's `e.quiet` branch removed: no test red (the message then
reads "the reply broke off: Cursor went quiet: ..."; tests use
toContain). Cosmetic, left as is.
Not tried by the reviewer: a real Cursor account, Windows, Cursor
actually going quiet (the author's live runs are on the PR).
This commit is contained in:
@@ -109,6 +109,13 @@ 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).
|
||||
|
||||
A Run Cursor stops answering ends with a 502 that says so, retained or
|
||||
stateless: 60 seconds with no message at all, or 4 minutes with only
|
||||
Cursor's heartbeats (yetone/magpie#2672, where a Run sent some thinking and
|
||||
then nothing, and the reply waited until the agent gave up after 5 minutes).
|
||||
Only time spent waiting on Cursor counts: a retained Run waiting for the
|
||||
caller's tool results is bounded by the 120 seconds above instead.
|
||||
|
||||
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
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
//
|
||||
// OpenCode speaks chat completions to it (@ai-sdk/openai-compatible); the
|
||||
// fetch here answers them.
|
||||
import { NATIVE_LIMITS, nativeSessions, NativeSessionError, nativeFields, nativeMcpArgs } from "./native-session.mjs"
|
||||
import { NATIVE_LIMITS, nativeSessions, NativeSessionError, nativeFields, nativeMcpArgs, Quiet } from "./native-session.mjs"
|
||||
import { isDeepStrictEqual } from "node:util"
|
||||
import http2 from "node:http2"
|
||||
import { STATUS_CODES } from "node:http"
|
||||
@@ -2278,7 +2278,8 @@ async function runOnce({ tok, base, id, tools, conv, convID, signal, maxMode, pa
|
||||
book.done()
|
||||
return { error: failure(o.status, Buffer.concat(chunks).toString("utf8").slice(0, 1 << 20)) }
|
||||
}
|
||||
const it = decode(frames(req), {
|
||||
// a Run Cursor stops answering ends, as a retained one does (#2672)
|
||||
const it = decode(new Quiet(NATIVE_LIMITS, close).frames(frames(req)), {
|
||||
send,
|
||||
blobs,
|
||||
tools,
|
||||
@@ -2492,6 +2493,11 @@ async function* decode(stream, { send, blobs, tools, estimate, close, stepUsage,
|
||||
}
|
||||
yield { error: { status: 502, message: "the reply broke off: EOF" } }
|
||||
} catch (e) {
|
||||
// gone quiet is no answer, calls or not: the step's count never came
|
||||
if (e?.quiet) {
|
||||
yield { error: { status: e.status, message: e.message } }
|
||||
return
|
||||
}
|
||||
if (calls > 0 && /EOF/.test(e?.message ?? "")) {
|
||||
yield await settled()
|
||||
return
|
||||
|
||||
@@ -96,6 +96,11 @@ async function agent(options = {}) {
|
||||
const first = () => {
|
||||
if (options.stallInitial) return
|
||||
send(update(4, text(1, options.initialReasoning ?? "native planning one")))
|
||||
// Cursor's own heartbeats, InteractionUpdate.heartbeat, and nothing else
|
||||
if (options.serverHeartbeat) {
|
||||
const beat = () => delay(() => { send(update(13, Buffer.alloc(0))); beat() }, options.serverHeartbeat)
|
||||
beat()
|
||||
}
|
||||
if (options.toolDisplay) {
|
||||
const at = Math.floor(options.toolDisplay.length / 2)
|
||||
send(update(1, text(1, options.toolDisplay.slice(0, at))))
|
||||
@@ -1501,3 +1506,69 @@ test("native accounting: cancellation interrupts final debt collection and prese
|
||||
expect(_internal.owed.has(key)).toBe(false)
|
||||
expect(a.results).toEqual([])
|
||||
})
|
||||
|
||||
// yetone/magpie#2672: a Run that sent some thinking and then nothing (no
|
||||
// text, call, count or TurnEnded) kept the reply open until the agent gave
|
||||
// up after 305 s, retained (native) or not (stateless, the path it was on).
|
||||
const sseOf = async (response) => {
|
||||
const reader = response.body.getReader()
|
||||
let sse = ""
|
||||
for (;;) {
|
||||
const part = await reader.read()
|
||||
if (part.done) return sse
|
||||
sse += new TextDecoder().decode(part.value)
|
||||
}
|
||||
}
|
||||
for (const path of ["native", "stateless"]) {
|
||||
test(`${path}: a Run silent after its thinking ends in an error within idle (#2672)`, async () => {
|
||||
NATIVE_LIMITS.idle = 150
|
||||
if (path === "stateless") NATIVE_LIMITS.perProcess = 0
|
||||
const a = await agent({ thinkingOnly: true })
|
||||
const response = await a.ask(auth(), initial({ stream: true }))
|
||||
expect(response.headers.get("X-Magpie-Cursor-Continuity")).toMatch(path === "native" ? /^same-run/ : /^stateless/)
|
||||
const started = Date.now()
|
||||
const sse = await sseOf(response)
|
||||
expect(Date.now() - started).toBeLessThan(1000)
|
||||
expect(sse).toContain("native planning one")
|
||||
expect(sse).toContain("Cursor went quiet: no message for 0 s, its last message thinking (try again)")
|
||||
expect(sse).not.toContain("[DONE]")
|
||||
await until(() => a.closedStreams === 1)
|
||||
})
|
||||
|
||||
test(`${path}: Cursor's heartbeats alone don't keep a silent Run open past quiet (#2672)`, async () => {
|
||||
Object.assign(NATIVE_LIMITS, { idle: 150, quiet: 400 })
|
||||
if (path === "stateless") NATIVE_LIMITS.perProcess = 0
|
||||
const a = await agent({ thinkingOnly: true, serverHeartbeat: 40 })
|
||||
const response = await a.ask(auth(), initial({ stream: true }))
|
||||
// the heartbeats branch names the wait as past quiet: that it ended so,
|
||||
// and not on idle, is the check, not how long a loaded machine took
|
||||
const sse = await sseOf(response)
|
||||
const [, beats] = sse.match(/Cursor went quiet: (\d+) heartbeats and nothing else for \d+ s, its last message thinking/) ?? []
|
||||
expect(Number(beats)).toBeGreaterThan(0)
|
||||
await until(() => a.closedStreams === 1)
|
||||
})
|
||||
}
|
||||
|
||||
test("stateless: a call with no count, then silence, is an error, not a step of tool calls (#2672)", async () => {
|
||||
Object.assign(NATIVE_LIMITS, { idle: 150, perProcess: 0 })
|
||||
const a = await agent({ noCount: true, stateDelay: 10_000 })
|
||||
const r = await a.ask(auth(), initial())
|
||||
expect(r.status).toBe(502)
|
||||
expect(r.body.error.message).toContain("Cursor went quiet")
|
||||
expect(r.body.choices).toBeUndefined()
|
||||
})
|
||||
|
||||
test("native: a Run parked for the caller's results longer than idle still continues (#2672)", async () => {
|
||||
NATIVE_LIMITS.idle = 120
|
||||
const a = await agent(), account = auth(), chat = initial()
|
||||
const first = await a.ask(account, chat)
|
||||
expect(first.status).toBe(200)
|
||||
await new Promise((r) => setTimeout(r, 400))
|
||||
const owner = [...nativeSessions.entries][0]
|
||||
expect(owner.error).toBeUndefined()
|
||||
const next = continueWith(chat, first.body, ["after a long tool"])
|
||||
const second = await a.ask(account, next)
|
||||
expect(second.status).toBe(200)
|
||||
expect(second.diagnostic).toMatch(/^same-run/)
|
||||
expect(a.runs).toHaveLength(1)
|
||||
})
|
||||
|
||||
@@ -19,6 +19,14 @@ export const NATIVE_LIMITS = {
|
||||
// How long a KV reply waits for room in the outbound queue (Cursor's own
|
||||
// flow control taking the writes before it) before the Run fails.
|
||||
writeWait: 30_000,
|
||||
// How long a Run waits on Cursor before it ends as gone quiet
|
||||
// (yetone/magpie#2672): idle, with no message at all, as @cursor/sdk's
|
||||
// stall detector ends one (30 s there; Cursor's client retries, this one
|
||||
// can't once output went out); quiet, with heartbeats and nothing else,
|
||||
// under the 5 minutes magpie keeps a silent reply alive. Only time spent
|
||||
// waiting on Cursor counts, never a Run parked for the caller's results.
|
||||
idle: 60_000,
|
||||
quiet: 240_000,
|
||||
perAccount: 8,
|
||||
perProcess: 32,
|
||||
}
|
||||
@@ -43,6 +51,113 @@ export class NativeSessionError extends Error {
|
||||
const invalid = (message, status = 409) => { throw new NativeSessionError(status, message) }
|
||||
const failureOf = (e) => ({ status: e?.status ?? 502, message: e?.message ?? String(e) })
|
||||
|
||||
// kindOf is what a frame of AgentServerMessage is, for Quiet: a heartbeat
|
||||
// alone, or what an error names as the last thing Cursor sent
|
||||
const UPDATES = { 1: "text", 4: "thinking", 14: "turn end", 27: "tool count" }
|
||||
const MESSAGES = { 2: "tool call", 3: "checkpoint", 4: "blob request" }
|
||||
function kindOf(f) {
|
||||
if (f.end) return "stream end"
|
||||
try {
|
||||
const fs = nativeFields(f.data)
|
||||
const updates = fs.filter((m) => m.num === 1).flatMap((m) => nativeFields(m.data))
|
||||
if (fs.length && fs.every((m) => m.num === 1) && updates.length && updates.every((u) => u.num === 13)) return null
|
||||
const u = updates.find((u) => u.num !== 13)
|
||||
if (u) return UPDATES[u.num] ?? `update #${u.num}`
|
||||
return MESSAGES[fs[0]?.num] ?? `message #${fs[0]?.num}`
|
||||
} catch {
|
||||
return "malformed message"
|
||||
}
|
||||
}
|
||||
|
||||
// Quiet ends a Run Cursor has stopped answering. Cursor can leave a Run's
|
||||
// stream open after some thinking with nothing more to come, no text, call,
|
||||
// count or TurnEnded, while the plugin's heartbeats keep it alive: the
|
||||
// reply then waited until the agent gave up (305 s, yetone/magpie#2672).
|
||||
// Only time spent waiting on Cursor's next frame counts: not this side
|
||||
// handling one, not a slow reader of the reply, not a paused Run.
|
||||
export class Quiet {
|
||||
constructor(limits, stop) {
|
||||
this.limits = limits
|
||||
this.stop = stop
|
||||
this.heard = 0 // ms waited since Cursor's last frame that wasn't a heartbeat
|
||||
this.heartbeats = 0
|
||||
this.last = ""
|
||||
this.since = null
|
||||
this.paused = false
|
||||
this.waiting = false
|
||||
this.why = ""
|
||||
}
|
||||
arm() {
|
||||
clearTimeout(this.timer)
|
||||
if (this.paused || !this.waiting || this.why || this.done) return
|
||||
this.since = Date.now()
|
||||
this.timer = later(() => this.fire(), Math.max(0, Math.min(this.limits.idle, this.limits.quiet - this.heard)))
|
||||
}
|
||||
// waited stops the clock: Cursor answered, or the Run paused
|
||||
waited() {
|
||||
clearTimeout(this.timer)
|
||||
if (this.since != null) this.heard += Date.now() - this.since
|
||||
this.since = null
|
||||
}
|
||||
fire() {
|
||||
const gap = Date.now() - this.since
|
||||
const what = this.heard + gap >= this.limits.quiet ? `${this.heartbeats} heartbeats and nothing else for ${Math.round((this.heard + gap) / 1000)} s` : `no message for ${Math.round(gap / 1000)} s`
|
||||
this.why = `Cursor went quiet: ${what}${this.last ? ", its last message " + this.last : ""} (try again)`
|
||||
this.gone?.()
|
||||
this.stop({ status: 502, message: this.why })
|
||||
}
|
||||
// pause stops the clock while the Run waits on the caller's tool results;
|
||||
// resume starts it again from nothing, for Cursor's next model call
|
||||
pause() {
|
||||
this.waited()
|
||||
this.paused = true
|
||||
}
|
||||
resume() {
|
||||
this.paused = false
|
||||
this.heard = 0
|
||||
this.heartbeats = 0
|
||||
this.arm()
|
||||
}
|
||||
// frames passes on a Run's frames; once Cursor has gone quiet, the read
|
||||
// that was waiting ends in its error, whether or not the stream does
|
||||
async *frames(stream) {
|
||||
const it = (stream[Symbol.asyncIterator] ?? stream[Symbol.iterator]).call(stream)
|
||||
try {
|
||||
for (;;) {
|
||||
this.waiting = true
|
||||
this.arm()
|
||||
let r
|
||||
try {
|
||||
const next = Promise.resolve(it.next())
|
||||
next.catch(() => {}) // a read left behind by gone fails unheard
|
||||
// a wake of this read's own: one that lived as long as the stream
|
||||
// would hold every race's result, each frame, until it ended
|
||||
r = await Promise.race([next, new Promise((wake) => { this.gone = wake })])
|
||||
} catch (e) {
|
||||
if (!this.why) throw e
|
||||
} finally {
|
||||
this.gone = null
|
||||
this.waiting = false
|
||||
this.waited()
|
||||
}
|
||||
if (this.why) throw Object.assign(new NativeSessionError(502, this.why), { quiet: true })
|
||||
if (r.done) return
|
||||
const kind = kindOf(r.value)
|
||||
if (kind == null) this.heartbeats++
|
||||
else [this.heard, this.heartbeats, this.last] = [0, 0, kind]
|
||||
yield r.value
|
||||
}
|
||||
} finally {
|
||||
this.done = true
|
||||
clearTimeout(this.timer)
|
||||
// not waited for: a read may still be pending on a stream that didn't
|
||||
// end, and the reader's error handling (a failed protocol check failing
|
||||
// the Run before a sealed batch is read) must not wait behind it
|
||||
Promise.resolve(it.return?.()).catch(() => {})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Unlike the compatibility codec, malformed protobuf tails must fail a live
|
||||
// continuation. Dropping one could turn a truncated batch into a valid handoff.
|
||||
export function nativeFields(input, maxFields = Infinity) {
|
||||
@@ -472,6 +587,7 @@ class NativeSession {
|
||||
this.segment = new Segment(this, prepared.chat)
|
||||
this.retain(bytes(prepared.chat))
|
||||
this.expireIn(this.limits.lifetime)
|
||||
this.quiet = new Quiet(this.limits, (e) => this.fail(e))
|
||||
}
|
||||
// expireIn sets the Run's absolute deadline ms from now: from its start,
|
||||
// the whole lifetime; a test brings it in after the first answer
|
||||
@@ -508,6 +624,7 @@ class NativeSession {
|
||||
clearTimeout(this.resultTimer)
|
||||
clearTimeout(this.drainTimer)
|
||||
clearTimeout(this.lifetimeTimer)
|
||||
this.quiet.pause()
|
||||
this.ac.abort()
|
||||
this.transport?.close()
|
||||
}
|
||||
@@ -605,6 +722,7 @@ class NativeSession {
|
||||
this.execClose(call.requestID)
|
||||
}
|
||||
this.state = "running"
|
||||
this.quiet.resume()
|
||||
} catch (e) {
|
||||
const error = failureOf(e)
|
||||
this.fail({ status: error.status, message: `${error.message}; native result submission failed; its outcome is uncertain and cannot be replayed` })
|
||||
@@ -706,6 +824,8 @@ class NativeSession {
|
||||
clearTimeout(this.batchTimer)
|
||||
this.batchTimer = null
|
||||
this.state = "awaiting-results"
|
||||
// Cursor waits on the caller now: resultWait bounds the wait
|
||||
this.quiet.pause()
|
||||
this.batches ??= []
|
||||
this.batches.push(segment)
|
||||
for (const c of segment.calls) this.pool.handles.set(c.id, { owner: this, batch: segment })
|
||||
@@ -855,7 +975,7 @@ class NativeSession {
|
||||
async pump(stream) {
|
||||
const { pb, exec, failure } = this.wire
|
||||
try {
|
||||
for await (const f of stream) {
|
||||
for await (const f of this.quiet.frames(stream)) {
|
||||
if (this.error || this.state === "complete") return
|
||||
if (f.end) {
|
||||
const e = failure(200, f.data)
|
||||
|
||||
@@ -325,3 +325,64 @@ test("native protocol: a step that stops sending fails batchWait after its lates
|
||||
expect(run.error).toMatchObject({ status: 502, message: "Cursor did not complete its declared native tool batch" })
|
||||
expect(Date.now() - started).toBeGreaterThanOrEqual(440)
|
||||
})
|
||||
|
||||
// #2672 bounds each wait on Cursor, not the step: calls that keep coming,
|
||||
// each sooner than idle, seal however long the step takes in all.
|
||||
test("native protocol: a step whose calls each come within idle outlasts idle in all (#2672)", async () => {
|
||||
const { run } = owner({}, { batchWait: 1000, idle: 200 })
|
||||
async function* spread() {
|
||||
for (const id of [7, 8, 9]) {
|
||||
yield* frames([tool(id, "call-" + id, "long arguments " + id)])
|
||||
await new Promise((r) => setTimeout(r, 150))
|
||||
}
|
||||
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()
|
||||
// parked for the caller: idle no longer counts
|
||||
await new Promise((r) => setTimeout(r, 400))
|
||||
expect(run.error).toBeUndefined()
|
||||
expect(run.state).toBe("awaiting-results")
|
||||
})
|
||||
|
||||
test("native protocol: a step silent after its first call fails at idle, before batchWait (#2672)", async () => {
|
||||
const { run } = owner({}, { batchWait: 5000, idle: 150 })
|
||||
const started = Date.now()
|
||||
run.pump((async function* () {
|
||||
yield* frames([update(4, text(1, "thinking")), tool(7, "call-7", "one")])
|
||||
await new Promise(() => {})
|
||||
})())
|
||||
await until(() => run.error)
|
||||
expect(run.error).toMatchObject({ status: 502, message: "Cursor went quiet: no message for 0 s, its last message tool call (try again)" })
|
||||
expect(Date.now() - started).toBeLessThan(1000)
|
||||
})
|
||||
|
||||
// Quiet.frames must not hold the frames it passed on while the stream stays
|
||||
// open: a long turn streams many MB through one Run.
|
||||
test("native protocol: frames already passed on are not kept while the Run streams on (#2672)", async () => {
|
||||
const { Quiet } = await import("./native-session.mjs")
|
||||
const refs = []
|
||||
let release
|
||||
const held = new Promise((r) => { release = r })
|
||||
async function* src() {
|
||||
for (let i = 0; i < 200; i++) {
|
||||
const f = { data: Buffer.alloc(64 * 1024, i & 255) }
|
||||
refs.push(new WeakRef(f))
|
||||
yield f
|
||||
}
|
||||
await held // the stream stays open
|
||||
}
|
||||
const it = new Quiet(NATIVE_LIMITS, () => {}).frames(src())
|
||||
for (let i = 0; i < 200; i++) await it.next()
|
||||
const pending = it.next()
|
||||
for (let i = 0; i < 5 && refs.some((r) => r.deref()); i++) {
|
||||
Bun.gc(true)
|
||||
await new Promise((r) => setTimeout(r, 0))
|
||||
}
|
||||
// the last frame may still be held by the generator's own state
|
||||
expect(refs.filter((r) => r.deref()).length).toBeLessThanOrEqual(2)
|
||||
release()
|
||||
await pending
|
||||
})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-cursor-auth",
|
||||
"version": "0.2.20",
|
||||
"version": "0.2.21",
|
||||
"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