diff --git a/packages/cursor/README.md b/packages/cursor/README.md index 72cbfbc..8b8502c 100644 --- a/packages/cursor/README.md +++ b/packages/cursor/README.md @@ -51,8 +51,10 @@ plugin's `fetch` answers them on Cursor's agent API: (refused, no network) or a stream the server refused leaves the next Run to try HTTP/2 again. A region error over HTTP/1.1 sends the Run back to HTTP/2 at the region's agent host. BidiAppends go up numbered in order, - up to 16 at a time as cursor-agent sends them (one at a time for a - native session's Run, whose tool results must be certain). A BidiAppend + up to 16 at a time as cursor-agent sends them. A native session's Run + sends only its KV replies (the history's blobs) that way; a tool result + or anything else waits for the appends before it, goes alone, and is + written once Cursor answered it, so it is never uncertain. A BidiAppend with no answer in 60 s (more for a large one) ends the Run, as cursor-agent does. - A new Run imports the whole conversation as AI SDK messages kept as blobs diff --git a/packages/cursor/index.mjs b/packages/cursor/index.mjs index f143076..1eece36 100644 --- a/packages/cursor/index.mjs +++ b/packages/cursor/index.mjs @@ -2038,10 +2038,11 @@ async function agentURL(tok, fresh) { // H2.retryAfter, or until a region error sends one back (answerOf); a // connection that failed (refused, no network) or a stream the server // refused leaves the next Run to try HTTP/2 again. atOnce is how many -// BidiAppends openH1 may have on their way at once. +// BidiAppends openH1 may have on their way at once, overlaps which messages +// may be among them (openH1). let h1Until = 0 const cancelledOpen = () => ({ error: { status: 410, message: "the request was cancelled" }, h2Failed: false }) -async function open(base, headers, signal, atOnce = H1.atOnce) { +async function open(base, headers, signal, atOnce = H1.atOnce, overlaps) { if (signal?.aborted) return cancelledOpen() if (Date.now() >= h1Until) { const o = await openH2(base, headers, signal) @@ -2055,7 +2056,7 @@ async function open(base, headers, signal, atOnce = H1.atOnce) { if (o.blocked) h1Until = Date.now() + H2.retryAfter } if (signal?.aborted) return cancelledOpen() - return openH1(headers, signal, atOnce) + return openH1(headers, signal, atOnce, overlaps) } const H2 = { @@ -2128,10 +2129,19 @@ const H1 = { // keeps them: one at a time, a new Run's history (a blob a message, // hundreds for a long conversation, all asked for at once) took a round // trip to Cursor each before the model could start. A native session's - // Run keeps them one at a time (runNative). + // Run sends only its KV replies that way (kvReply); each of its other + // messages waits for every append before it, and goes alone (runNative). atOnce: 16, } +// kvReply is whether a client message (an AgentClientMessage, unframed) is +// a KV reply, kv_client_message: a blob Cursor asked for, which nothing +// else waits on. Cursor asks for a new Run's whole history at once. +function kvReply(msg) { + const b = Buffer.isBuffer(msg) ? msg : Buffer.from(msg ?? EMPTY) + return b.length > 0 && b[0] === 0x1a // field 3, length-delimited +} + // connectCode is Connect's code for an HTTP status that came with no // Connect error of its own function connectCode(status) { @@ -2144,8 +2154,11 @@ function connectCode(status) { // the stream it reads, Connect's frames as the HTTP/2 Run's. Its response // is a 200 at once; an error Cursor says later, or a call that fails, // ends the stream with Connect's end frame, which runOnce reads as the -// Run's own. -function openH1(headers, signal, atOnce = H1.atOnce) { +// Run's own. overlaps says of a message whether it may go up while appends +// before it are on their way (up to atOnce of them); one that may not waits +// for all of them, goes alone, and its write's callback is its own append +// answered. +function openH1(headers, signal, atOnce = H1.atOnce, overlaps = () => true) { if (signal?.aborted) return Promise.resolve(cancelledOpen()) const ac = new AbortController() const id = headers["x-request-id"] @@ -2159,11 +2172,20 @@ function openH1(headers, signal, atOnce = H1.atOnce) { write(chunk, _enc, cb) { // runOnce writes one whole frame each time const msg = Buffer.from(chunk).subarray(5) - const n = seq++ - const p = append(msg, n) - going.add(p) - const gone = () => going.delete(p) - p.then(gone, gone) + const go = () => { + const p = append(msg, seq++) + going.add(p) + const gone = () => going.delete(p) + p.then(gone, gone) + return p + } + if (!overlaps(msg)) { + // alone: after every append before it is answered, and answered + // itself before the next write + Promise.allSettled([...going]).then(go).then(() => cb(), (e) => cb(e)) + return + } + go() // Up to atOnce appends go at once; past that the write stays // buffered until one finishes, so callbacks and drain reflect the // pending upload rather than an unbounded promise chain. At one, @@ -2432,9 +2454,15 @@ async function runNative({ tok, base, id, tools, conv, convID, signal, maxMode, "x-cursor-agent-allowed-tools": "mcp_tool_call,get_mcp_tools_tool_call", }, native.ac.signal, - // one at a time: a native session counts a write as done only when - // Cursor answered its own append, so a tool result is never uncertain - 1, + // Over HTTP/1.1 the history's blobs go up H1.atOnce at a time, as + // cursor-agent sends them; one at a time, a Run with a long history + // waited a round trip to api2 a blob before its first token (ysm119 on + // Discord: 135 blobs, 37 s against 3 s over HTTP/2). Everything else + // goes alone, after the appends before it were answered, and counts as + // written only once Cursor answered it, so a tool result is never + // uncertain. + H1.atOnce, + kvReply, ) if (o.error) { native.fail(o.error) @@ -3167,4 +3195,4 @@ export async function CursorAuthPlugin() { } // for tests -export const _internal = { listFor, lists, keychain, keychainToken, nativeTransport, onDemandOf,resetH1: () => (h1Until = 0), onH1: () => Date.now() < h1Until, resetTeam: () => { teamRead.at = 0; teamRead.info = null }, expireTeam: () => (teamRead.at = 0),H2, H1, h2Blocked, open, openH1, openH2, STEP_WAIT, stepUsage, usageKey, ledger, owed, flights, misses, unreadable, catalog, usable, request, modelsOf, tokensOf, maxRequired, conversationID, usageOf, sessionOf, SESSION, errorResponse, kept, poolBase, conversation, buildRun, decode, exec, fields, pb, pbValue, pbAny, frame, frames, failure, toolsOf, expiry } +export const _internal = { kvReply, listFor, lists, keychain, keychainToken, nativeTransport, onDemandOf,resetH1: () => (h1Until = 0), onH1: () => Date.now() < h1Until, resetTeam: () => { teamRead.at = 0; teamRead.info = null }, expireTeam: () => (teamRead.at = 0),H2, H1, h2Blocked, open, openH1, openH2, STEP_WAIT, stepUsage, usageKey, ledger, owed, flights, misses, unreadable, catalog, usable, request, modelsOf, tokensOf, maxRequired, conversationID, usageOf, sessionOf, SESSION, errorResponse, kept, poolBase, conversation, buildRun, decode, exec, fields, pb, pbValue, pbAny, frame, frames, failure, toolsOf, expiry } diff --git a/packages/cursor/native-http1.test.mjs b/packages/cursor/native-http1.test.mjs index fd7f01d..00eeb6c 100644 --- a/packages/cursor/native-http1.test.mjs +++ b/packages/cursor/native-http1.test.mjs @@ -48,8 +48,9 @@ async function fixture({ failResult = false, stallKv = false } = {}) { await new Promise((r) => server.listen(0, "127.0.0.1", r)) servers.push({ server, sessions }) const base = `http://127.0.0.1:${server.address().port}` - const seen = { sse: 0, runs: 0, appends: [], results: [], closes: [], kv: [], histories: [], maxInFlight: 0, conversationId: "", dashboardRequests: 0 } + const seen = { sse: 0, runs: 0, appends: [], results: [], closes: [], kv: [], histories: [], maxInFlight: 0, alone: 0, conversationId: "", dashboardRequests: 0 } let inFlight = 0 + let othersIn = 0 let controller let ended = false let requestID @@ -89,6 +90,11 @@ async function fixture({ failResult = false, stallKv = false } = {}) { expect(string(nest(body, 2), 1)).toBe(requestID) const seqno = number(body, 3) const wire = Buffer.from(string(body, 1), "hex") + // Only KV replies may overlap: anything else goes alone, and nothing + // goes beside it (seen.alone counts the breaches). + const kvMsg = readWire(wire).some((f) => f.no === 3) + if (kvMsg ? othersIn > 0 : inFlight > 0) seen.alone++ + if (!kvMsg) othersIn++ inFlight++ seen.maxInFlight = Math.max(seen.maxInFlight, inFlight) seen.appends.push(seqno) @@ -157,6 +163,7 @@ async function fixture({ failResult = false, stallKv = false } = {}) { return new Response(new Uint8Array(0)) } finally { inFlight-- + if (!kvMsg) othersIn-- } } const account = { @@ -196,11 +203,14 @@ test("native HTTP/1: two external roundtrips keep one RunSSE and serialize resul expect(final.body.choices[0].finish_reason).toBe("stop") expect(final.body.usage.prompt_tokens).toBe(17) expect(final.body.usage.completion_tokens).toBe(5) - expect(seen).toMatchObject({ sse: 1, runs: 1, appends: [0, 1, 2, 3, 4], closes: [7, 8], maxInFlight: 1 }) + expect(seen).toMatchObject({ sse: 1, runs: 1, appends: [0, 1, 2, 3, 4], closes: [7, 8], maxInFlight: 1, alone: 0 }) expect(seen.results.map((r) => r.id)).toEqual([7, 8]) }) -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 () => { +// KV replies (a Run's history, which Cursor asks for at once) go up +// H1.atOnce at a time, so 16 stalled appends are on their way before the +// outbound queue fills behind them. +for (const bound of ["bytes", "messages"]) test(`native loader HTTP/1: KV replies go ${_internal.H1.atOnce} at once; stalled past writeWait at the outbound ${bound} bound they abort all transport work`, async () => { NATIVE_LIMITS.outboundBytes = 4 << 20 NATIVE_LIMITS.writeWait = 100 NATIVE_LIMITS.outboundMessages = bound === "messages" ? 4 : 256 @@ -214,7 +224,7 @@ for (const bound of ["bytes", "messages"]) test(`native loader HTTP/1: parked KV await until(() => a.seen.kv.includes(90) && a.inFlight() === 0) a.push(getBlob(91, blobID)) await until(() => a.seen.kv.includes(91)) - for (let i = 0; i < 8; i++) a.push(getBlob(92 + i, blobID)) + for (let i = 0; i < _internal.H1.atOnce + 8; i++) a.push(getBlob(92 + i, blobID)) await until(() => !!owner.error) expect(owner.error).toMatchObject({ status: 503 }) expect(owner.error.message).toContain("outbound") @@ -222,8 +232,9 @@ for (const bound of ["bytes", "messages"]) test(`native loader HTTP/1: parked KV await until(() => a.inFlight() === 0 && a.ended()) expect(owner.transport.outbound).toEqual({ bytes: 0, messages: 0 }) expect(owner.ac.signal.aborted).toBe(true) - expect(a.seen.kv).toEqual([90, 91]) - expect(a.seen.maxInFlight).toBe(1) + expect(a.seen.kv).toEqual(Array.from({ length: _internal.H1.atOnce + 1 }, (_, i) => 90 + i)) + expect(a.seen.maxInFlight).toBe(_internal.H1.atOnce) + expect(a.seen.alone).toBe(0) expect(a.seen.results).toEqual([]) expect(a.seen.closes).toEqual([]) // Retention overflow ends this owner. A later request is history input to @@ -257,5 +268,5 @@ for (const stream of [false, true]) test(`native HTTP/1: ${stream ? "streamed" : expect(seen.sse).toBe(2) expect(seen.results).toHaveLength(1) expect(seen.closes).toEqual([]) - expect(seen.maxInFlight).toBe(1) + expect(seen.alone).toBe(0) }) diff --git a/packages/cursor/open.test.mjs b/packages/cursor/open.test.mjs index 65daafd..b99bc23 100644 --- a/packages/cursor/open.test.mjs +++ b/packages/cursor/open.test.mjs @@ -262,6 +262,58 @@ test("openH1 one at a time (a native session's Run): write callbacks and drain w expect(callbacks).toEqual([0, 1]) }) +// A native session's Run over HTTP/1.1 (runNative): its history's KV replies +// go up together, as cursor-agent sends them; anything else (a tool result, +// an exec close) waits for every append before it, goes alone, and its +// write's callback is its own append answered. +test("openH1 with kvReply: KV replies overlap; any other message waits for them, goes alone, and is answered before its callback", async () => { + const downstream = body() + const held = new Map() + const seqnos = [] + const callbacks = [] + globalThis.fetch = async (url, init) => { + if (String(url).endsWith("/RunSSE")) return new Response(downstream.stream) + const seq = fields(Buffer.from(init.body)).find((f) => f.num === 3)?.n ?? 0 + seqnos.push(seq) + const b = body() + held.set(seq, b) + return new Response(b.stream) + } + const o = keep(await openH1(headers, undefined, H1.atOnce, _internal.kvReply)) + const kv = (i) => frame(pb().bytes(3, pb().varint(1, i).bytes(2, pb().bytes(1, Buffer.from("blob " + i)))).done()) + const result = frame(pb().bytes(2, pb().varint(1, 7)).done()) + for (let i = 0; i < 3; i++) o.req.write(kv(i), () => callbacks.push("kv" + i)) + o.req.write(result, () => callbacks.push("result")) + o.req.write(kv(3), () => callbacks.push("kv3")) + await until(() => seqnos.length === 3 && callbacks.length === 3) + // three KV replies on their way at once, their callbacks already called + expect(seqnos).toEqual([0, 1, 2]) + expect(callbacks).toEqual(["kv0", "kv1", "kv2"]) + held.get(0).controller.close() + held.get(2).controller.close() + await new Promise((r) => setTimeout(r, 20)) + expect(seqnos).toEqual([0, 1, 2]) // the result waits for append 1 too + held.get(1).controller.close() + await until(() => seqnos.length === 4) + await new Promise((r) => setTimeout(r, 20)) + expect(seqnos).toEqual([0, 1, 2, 3]) // alone: nothing goes beside it + expect(callbacks).toEqual(["kv0", "kv1", "kv2"]) // nor is it written before it is answered + held.get(3).controller.close() + await until(() => callbacks.length === 5) + expect(seqnos).toEqual([0, 1, 2, 3, 4]) + expect(callbacks).toEqual(["kv0", "kv1", "kv2", "result", "kv3"]) + held.get(4).controller.close() +}) + +test("kvReply is a kv_client_message and nothing else", () => { + expect(_internal.kvReply(pb().bytes(3, pb().varint(1, 1)).done())).toBe(true) + expect(_internal.kvReply(pb().bytes(2, pb().varint(1, 1)).done())).toBe(false) // exec result + expect(_internal.kvReply(pb().bytes(5, pb().varint(1, 1)).done())).toBe(false) // exec control + expect(_internal.kvReply(pb().bytes(7, Buffer.alloc(0)).done())).toBe(false) // heartbeat + expect(_internal.kvReply(pb().bytes(1, pb().varint(1, 1)).done())).toBe(false) // run request + expect(_internal.kvReply(Buffer.alloc(0))).toBe(false) +}) + // The same plugin ownership assertions cover retained Runs and capacity fallback. for (const retained of [0, 32]) for (const outcome of ["head abort", "completion", "HTTP error"]) { test(`the plugin (${retained ? "retained" : "stateless fallback"}): ${outcome} releases transport ownership and its Run abort listener`, async () => { diff --git a/packages/cursor/package.json b/packages/cursor/package.json index 7615bb7..99cc0ae 100644 --- a/packages/cursor/package.json +++ b/packages/cursor/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-cursor-auth", - "version": "0.2.28", + "version": "0.2.29", "description": "Cursor subscriptions (Pro, Pro+, Ultra, Teams) in OpenCode and magpie, through the API cursor-agent talks to", "type": "module", "main": "./index.mjs",