diff --git a/packages/cursor/README.md b/packages/cursor/README.md index 0696c1b..048beca 100644 --- a/packages/cursor/README.md +++ b/packages/cursor/README.md @@ -95,7 +95,15 @@ uses the same session/cache key and first user message as `conversation_id`, so Task subagents sharing their parent's session can run independently. Retention waits at most 120 seconds for a result batch and 15 minutes for a Run's total lifetime. The pool holds at most 8 owners per account and 32 per process, with -bounded history, blobs, arguments, and pending writes. +bounded history, blobs, arguments, and pending writes. When pending writes +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. + +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 +rest. These are retention limits. A missing, expired, restarted, busy, incompatible, or full owner uses the original history reconstruction and stateless decoder diff --git a/packages/cursor/index.mjs b/packages/cursor/index.mjs index 43be16c..64edb64 100644 --- a/packages/cursor/index.mjs +++ b/packages/cursor/index.mjs @@ -1939,6 +1939,15 @@ function nativeTransport(req, close, fail, limits = NATIVE_LIMITS) { const outbound = { bytes: 0, messages: 0 } const queue = [] let closed = false, flushing = false, rejectWrite + // waiters for room (KV replies), woken as writes complete. An eighth of + // each bound stays free for heartbeats and exec answers, which never wait. + const waiters = new Set() + const spare = (n) => Math.floor(n / 8) + const fits = (size) => outbound.messages === 0 || (outbound.messages + 1 + spare(limits.outboundMessages) <= limits.outboundMessages + && outbound.bytes + size + spare(limits.outboundBytes) <= limits.outboundBytes) + const wake = () => { + for (const w of waiters) if (closed || fits(w.size)) w.done() + } const flush = async () => { if (closed || flushing) return flushing = true @@ -1975,7 +1984,7 @@ function nativeTransport(req, close, fail, limits = NATIVE_LIMITS) { check() } catch (e) { finish(e) } }) - if (!closed) { outbound.bytes -= packet.length; outbound.messages-- } + if (!closed) { outbound.bytes -= packet.length; outbound.messages--; wake() } } } catch (e) { if (!closed) fail(e) @@ -1993,12 +2002,35 @@ function nativeTransport(req, close, fail, limits = NATIVE_LIMITS) { queue.push(frame(message)) void flush() }, + // room resolves once a message of size fits the queue with the spare + // kept, and fails the Run when the queue doesn't drain for writeWait. + room(size) { + if (closed || fits(size)) return Promise.resolve() + return new Promise((resolve, reject) => { + const w = { + size, + done() { + waiters.delete(w) + clearTimeout(w.timer) + resolve() + }, + } + w.timer = setTimeout(() => { + waiters.delete(w) + const which = outbound.bytes + size + spare(limits.outboundBytes) > limits.outboundBytes ? "bytes" : "messages" + reject(new NativeSessionError(503, `native outbound ${which} limit reached: the queue did not drain for ${Math.round(limits.writeWait / 1000)}s`)) + }, limits.writeWait) + w.timer.unref?.() + waiters.add(w) + }) + }, close() { if (closed) return closed = true queue.length = 0 outbound.bytes = 0 outbound.messages = 0 + wake() rejectWrite?.(new NativeSessionError(410, "native transport was cancelled")) close() }, @@ -2232,9 +2264,22 @@ async function runOnce({ tok, base, id, tools, conv, convID, signal, maxMode, pa // turn ends, or the model has made its tool calls. async function* decode(stream, { send, blobs, tools, estimate, close, stepUsage, owedUsage }) { let calls = 0 + // answered: the step's calls answered here (a refusal, the MCP tool + // list), which Cursor's count of the step's calls takes in too (#142) + let answered = 0 // ended: Cursor said what the turn used let ended = false let listed = 0 + // stepDone is whether every call the step listed has come. A step whose + // calls were all answered here goes on on Cursor's side, under a count of + // its own. + const stepDone = () => { + if (!listed || calls + answered < listed) return false + if (calls > 0) return true + listed = 0 + answered = 0 + return false + } let said = 0 // wrote: the reply's text alone; a turn of thinking only says nothing let wrote = 0 @@ -2342,9 +2387,9 @@ async function* decode(stream, { send, blobs, tools, estimate, close, stepUsage, return } break - case 27: // how many tool calls the step makes, sent before them + case 27: // how many tool calls the step makes, sent before or after them listed = pbNum(uf, 1) - if (listed > 0 && calls >= listed) { + if (stepDone()) { yield await settled() return } @@ -2360,8 +2405,8 @@ async function* decode(stream, { send, blobs, tools, estimate, close, stepUsage, if (call) { said += call.args.length yield { tool: { index: calls++, ...call } } - } - if (listed > 0 && calls >= listed) { + } else if (!fields(m.data).some((e) => e.num === 10)) answered++ + if (stepDone()) { // every call made: the caller runs them yield await settled() return diff --git a/packages/cursor/native-e2e.test.mjs b/packages/cursor/native-e2e.test.mjs index 2931fb7..91d5ae5 100644 --- a/packages/cursor/native-e2e.test.mjs +++ b/packages/cursor/native-e2e.test.mjs @@ -557,8 +557,9 @@ test("native loader: streamed ordinary text/thinking arrives before the server p }) -for (const bound of ["bytes", "messages"]) test(`native loader HTTP/2: stalled writes bound queued parked KV ${bound}`, async () => { +for (const bound of ["bytes", "messages"]) test(`native loader HTTP/2: KV replies stalled past writeWait at the queued ${bound} bound fail the Run`, async () => { NATIVE_LIMITS.outboundBytes = 4 << 20 + NATIVE_LIMITS.writeWait = 100 NATIVE_LIMITS.outboundMessages = bound === "messages" ? 4 : 256 const a = await agent({ stateDelay: 10_000 }) const connect = http2.connect diff --git a/packages/cursor/native-http1.test.mjs b/packages/cursor/native-http1.test.mjs index be83192..fd7f01d 100644 --- a/packages/cursor/native-http1.test.mjs +++ b/packages/cursor/native-http1.test.mjs @@ -200,8 +200,9 @@ test("native HTTP/1: two external roundtrips keep one RunSSE and serialize resul expect(seen.results.map((r) => r.id)).toEqual([7, 8]) }) -for (const bound of ["bytes", "messages"]) test(`native loader HTTP/1: stalled parked KV replies hit the outbound ${bound} bound and abort all transport work`, async () => { +for (const bound of ["bytes", "messages"]) test(`native loader HTTP/1: parked KV replies stalled past writeWait at the outbound ${bound} bound abort all transport work`, async () => { NATIVE_LIMITS.outboundBytes = 4 << 20 + NATIVE_LIMITS.writeWait = 100 NATIVE_LIMITS.outboundMessages = bound === "messages" ? 4 : 256 const a = await fixture({ stallKv: true }) const chat = initial() diff --git a/packages/cursor/native-session.mjs b/packages/cursor/native-session.mjs index 3317ec4..4bc2ad7 100644 --- a/packages/cursor/native-session.mjs +++ b/packages/cursor/native-session.mjs @@ -16,6 +16,9 @@ export const NATIVE_LIMITS = { argumentDepth: 64, outboundBytes: 16 << 20, outboundMessages: 256, + // 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, perAccount: 8, perProcess: 32, } @@ -270,6 +273,9 @@ class Segment { this.prefixDigest = historyDigest(chat.messages) this.events = [] this.calls = [] + // answered: the step's execs the bridge answered itself (a refusal, or + // the MCP tool list). Cursor's tool_requests_listed counts them too. + this.answered = 0 this.content = "" this.reasoning = "" this.expected = null @@ -530,6 +536,14 @@ class NativeSession { if (this.error || this.transportClosed) invalid("native transport is no longer writable", 410) this.transport.send(message) } + // reply answers one of Cursor's KV requests once the outbound queue has + // room. Cursor asks for every history blob at once, hundreds for a long + // conversation, faster than a slow link takes the replies: the decoder + // waits for the queue rather than failing the Run (#142). + async reply(message) { + await this.transport.room?.(message.length + 5) + this.send(message) + } execClose(id) { this.send(this.wire.pb().bytes(5, this.wire.pb().bytes(1, this.wire.pb().varint(1, id))).done()) } @@ -615,6 +629,15 @@ class NativeSession { missingCount() { this.fail({ status: 502, message: "Cursor did not declare its native tool batch", retentionIneligible: !this.resultSubmitted }) } + // A call of the model's step the bridge answered itself: a refused tool (a + // name it doesn't serve, Cursor's own tools) or get_mcp_tools. Cursor's + // count is of every call the step made, so it counts toward the batch; + // never handed to the caller (#142). + answeredCall() { + if (this.terminal || this.state === "awaiting-results") return + this.segment.answered++ + this.sealBatch() + } listed(count) { if (!Number.isSafeInteger(count) || count < 1) invalid("invalid native tool count", 502) if (this.segment.expected != null && this.segment.expected !== count) invalid("inconsistent native tool count", 502) @@ -626,8 +649,18 @@ class NativeSession { sealBatch() { const segment = this.segment if (segment.expected == null) return - if (segment.calls.length > segment.expected) invalid("native tool batch exceeded its declared count", 502) - if (segment.calls.length !== segment.expected || segment.closed) return + const made = segment.calls.length + segment.answered + if (made > segment.expected) invalid("native tool batch exceeded its declared count", 502) + if (made !== segment.expected || segment.closed) return + if (!segment.calls.length) { + // Every call of the step was answered here: Cursor goes on with the + // turn by itself, and its next step lists a count of its own. + segment.expected = null + segment.answered = 0 + clearTimeout(this.batchTimer) + this.batchTimer = null + return + } clearTimeout(this.batchTimer) this.batchTimer = null this.state = "awaiting-results" @@ -793,6 +826,8 @@ class NativeSession { case 2: { const c = exec(m.data, this.chatTools, (b) => this.send(b), (id) => this.execClose(id), null, true) if (c) this.acceptCall(c) + // request_context is Cursor asking for the environment, not a call + else if (!nativeFields(m.data).some((e) => e.num === 10)) this.answeredCall() break } case 3: @@ -806,7 +841,7 @@ class NativeSession { const want = field(nativeFields(k.data), 1)?.data.toString("hex") ?? "" const b = this.blobs.get(want) const res = b ? pb().bytes(1, b) : pb().bytes(2, pb().str(1, "blob not found")) - this.send(pb().bytes(3, pb().varint(1, id).bytes(2, res)).done()) + await this.reply(pb().bytes(3, pb().varint(1, id).bytes(2, res)).done()) } else if (k.num === 3) { try { const set = nativeFields(k.data) @@ -815,7 +850,7 @@ class NativeSession { this.send(pb().bytes(3, pb().varint(1, id).bytes(3, pb().bytes(1, pb().str(1, "native blob could not be retained")))).done()) throw e } - this.send(pb().bytes(3, pb().varint(1, id).bytes(3, Buffer.alloc(0))).done()) + await this.reply(pb().bytes(3, pb().varint(1, id).bytes(3, Buffer.alloc(0))).done()) } } break diff --git a/packages/cursor/native-session.test.mjs b/packages/cursor/native-session.test.mjs index 11d8e4b..3337068 100644 --- a/packages/cursor/native-session.test.mjs +++ b/packages/cursor/native-session.test.mjs @@ -4,7 +4,7 @@ import { createHash } from "node:crypto" import { EventEmitter } from "node:events" import { _internal } from "./index.mjs" import { NativeSessionPool, NATIVE_LIMITS, nativeFields } from "./native-session.mjs" -import { bin, text, uint, message, tool, update, setBlob, checkpoint, end, readWire, nest, number, readResult } from "./native-test-wire.mjs" +import { bin, text, uint, message, tool, update, setBlob, getBlob, checkpoint, end, readWire, nest, number, readResult } from "./native-test-wire.mjs" const pools = [] afterEach(async () => { await Promise.all(pools.splice(0).map((p) => p.clear())) }) @@ -22,6 +22,13 @@ function owner(extra = {}, overrides = {}) { run.bind({ send: (b) => writes.push(Buffer.from(b)), close: () => closed++ }, new Map(), 11) return { run, writes, pool, request, closed: () => closed } } +const until = async (predicate) => { + const deadline = Date.now() + 5000 + while (!predicate()) { + if (Date.now() >= deadline) throw new Error("fixture did not reach its expected state") + await new Promise((r) => setTimeout(r, 5)) + } +} const frames = (wire) => wire.map((b) => ({ data: b.subarray(5), end: !!(b[0] & 2) })) // H2 e2e covers the full lifecycle. These cases probe protocol fault/retention @@ -201,3 +208,82 @@ test("native lifecycle: absolute deadline terminates a Run even without a parked expect(run.state).toBe("expired") expect(closed()).toBe(1) }) + + +// #142: Cursor's tool_requests_listed (InteractionUpdate 27) counts every call +// of the model's step, and comes after them, including calls the bridge +// answers itself. Captured from real Cursor (model auto, 2026-10-15), frames +// without their envelopes: +// - steps: get_mcp_tools and a WebSearch the caller doesn't have in one step +// (both answered here), Cursor's count 2, then read_file a.txt alone and +// its count 1. 0.2.14 failed it with "inconsistent native tool count". +// - mixed: read_file a.txt, WebSearch (refused), read_file b.txt, count 3. +// 0.2.14 waited for a third call and failed after batchWait. +const captured = { + steps: ["123f9a01360a2031633366376432386261313531653137303639616231343163626637316165651210653532623935616633363331663934321800a20200b80300","12f80108015a91010a106d61677069652d576562536561726368120b0a047061746812031a01781a5563616c6c2d35653434356466642d636438612d343238642d623561352d6562656137313838376435392d310a66635f61633833643337622d666536362d393964622d623036652d3736613663633562616564325f3122066d61677069652a095765625365617263684a066d61677069657a2462616465343834312d366230342d346464632d626330392d3936313763306635343666389a01360a2031633366376432386261313531653137303639616231343163626637316165651210333632323535313938666465653532321800b80301","0a05da01020802","12fc0108025a95010a106d61677069652d726561645f66696c65120f0a047061746812071a05612e7478741a5563616c6c2d63346339313634342d646332392d343835312d383365372d6261313430626363666361612d320a66635f64623930633334622d643361342d396532312d626336342d3032396231383363346462305f3022066d61677069652a09726561645f66696c654a066d61677069657a2434333165303535662d343234642d343336612d623365322d3464363964373162333066649a01360a2031633366376432386261313531653137303639616231343163626637316165651210333764623631343839646433646665661800b80301","0a05da01020801"], + mixed: ["12fa015a95010a106d61677069652d726561645f66696c65120f0a047061746812071a05612e7478741a5563616c6c2d64376533623732652d343432312d343166332d623638652d3461386439393737343836352d300a66635f36333866613563312d623731652d393137352d623035372d6133373436613831663463305f3022066d61677069652a09726561645f66696c654a066d61677069657a2431663861373061622d643138302d346434392d386232652d3964343733386133343963669a01360a2062333264396133313831363939656338366462373134626663363735346135351210383739306264393462653165356366341800b80301","12f80108015a91010a106d61677069652d576562536561726368120b0a047061746812031a01781a5563616c6c2d64376533623732652d343432312d343166332d623638652d3461386439393737343836352d310a66635f36333866613563312d623731652d393137352d623035372d6133373436613831663463305f3122066d61677069652a095765625365617263684a066d61677069657a2435356536613234362d306564342d343836332d393733642d3332613234306634303761369a01360a2062333264396133313831363939656338366462373134626663363735346135351210316532363165363634346633643932371800b80301","12fc0108025a95010a106d61677069652d726561645f66696c65120f0a047061746812071a05622e7478741a5563616c6c2d64376533623732652d343432312d343166332d623638652d3461386439393737343836352d320a66635f36333866613563312d623731652d393137352d623035372d6133373436613831663463305f3222066d61677069652a09726561645f66696c654a066d61677069657a2435376434646662632d623532392d343537332d383537342d6238666530326335623766659a01360a2062333264396133313831363939656338366462373134626663363735346135351210376538343239303361646533313434341800b80301","0a05da01020803"], +} +const readFile = [{ name: "read_file", description: "Read a file from disk", schema: { type: "object" }, schemaText: '{"type":"object"}' }] +const capturedFrames = (name) => captured[name].map((h) => ({ data: Buffer.from(h, "hex") })) +// a stream that stays open after its frames, as Cursor's does while it waits +// for the results +async function* open(list) { + yield* list + await new Promise(() => {}) +} +for (const [name, paths] of [["steps", ["a.txt"]], ["mixed", ["a.txt", "b.txt"]]]) test(`native protocol: calls the bridge answered count toward Cursor's tool count (#142, real ${name} capture)`, async () => { + const { run, writes } = owner() + run.chatTools = readFile + run.pump(open(capturedFrames(name))) + await until(() => run.error || run.state === "awaiting-results") + expect(run.error).toBeUndefined() + const calls = run.segment.events.filter((e) => e.tool).map((e) => e.tool) + expect(calls.map((c) => [c.name, JSON.parse(c.args).path])).toEqual(paths.map((p) => ["read_file", p])) + expect(run.segment.events.at(-1).stop).toBe("tool_calls") + // the refusal (and the MCP tool list) went back to Cursor; no result was sent + expect(writes.filter((w) => readWire(w).some((f) => f.no === 2))).toHaveLength(name === "steps" ? 1 : 0) + expect(writes.filter((w) => readWire(w).some((f) => f.no === 5 && readWire(f.data).some((g) => g.no === 2)))).toHaveLength(1) +}) + +for (const [name, calls] of [["steps", ["WebSearch"]], ["mixed", ["read_file", "WebSearch", "read_file"]]]) test(`stateless decode: calls answered here count toward Cursor's tool count (#142, real ${name} capture)`, async () => { + // the stream stays open after the count: the decoder must end the step on + // the count alone + const events = [] + const done = (async () => { + for await (const e of _internal.decode(open(capturedFrames(name)), { send() {}, blobs: new Map(), tools: readFile, estimate: 1 })) { + events.push(e) + if (e.stop || e.error) return + } + })() + const timer = new Promise((r) => setTimeout(() => r("open"), 1000)) + expect(await Promise.race([done.then(() => "ended"), timer])).toBe("ended") + // the stateless path hands every MCP name to the caller; get_mcp_tools is + // answered here + expect(events.filter((e) => e.tool).map((e) => e.tool.name)).toEqual(calls) + expect(events.at(-1).stop).toBe("tool_calls") +}) + +test("native transport: a burst of KV requests past the queue bound waits for writes instead of failing the Run (#142)", async () => { + // Cursor asks for every history blob of a long conversation at once; on a + // slow link the replies are written far slower than they are asked for + const req = Object.assign(new EventEmitter(), { writable: true, destroyed: false }) + const written = [] + let inFlight = 0, most = 0 + req.write = (packet, callback) => { + inFlight++ + most = Math.max(most, transport.outbound.messages) + setTimeout(() => { written.push(packet); inFlight--; callback?.(); req.emit("drain") }, 1) + return false + } + const limits = { ...NATIVE_LIMITS, outboundMessages: 16 } + const transport = _internal.nativeTransport(req, () => {}, (e) => { throw e }, limits) + const { run } = owner({}, { outboundMessages: 16 }) + run.transport = transport + const blob = Buffer.from("synthetic history message") + run.blobs.set(blob.toString("hex"), blob) + run.pump(open(frames(Array.from({ length: 300 }, (_, i) => getBlob(1000 + i, blob))))) + await until(() => run.error || written.length === 300) + expect(run.error).toBeUndefined() + expect(most).toBeLessThanOrEqual(16) + expect(written.map((w) => number(nest(w.subarray(5), 3), 1))).toEqual(Array.from({ length: 300 }, (_, i) => 1000 + i)) +})