From 5b67ff41aa0704efea27c45bb31ea3e8fb0aeffb Mon Sep 17 00:00:00 2001 From: kazecreator <129589624+kazecreator@users.noreply.github.com> Date: Sat, 10 Oct 2026 09:33:23 +0800 Subject: [PATCH] cursor 0.2.3: a Run HTTP/2 can't open goes over HTTP/1.1, as RunSSE + BidiAppend on api2 (#59, kazecreator) Where a proxy or network blocks HTTP/2, a Cursor Run goes over HTTP/1.1 on api2: RunSSE down, a BidiAppend for each client message up. A failure that says HTTP/2 itself can't be had keeps later Runs on HTTP/1.1 for 10 minutes; a refused connection or a reset stream falls back for that Run only. Reviewed at f5c11b7, merged onto 0437abb: cursor 66 pass, whole repo 1026 pass, check.mjs all 15; each guarded piece broken by hand turns http1.test.mjs red. --- packages/cursor/README.md | 12 + packages/cursor/http1.test.mjs | 416 +++++++++++++++++++++++++++++++++ packages/cursor/index.mjs | 174 +++++++++++++- packages/cursor/package.json | 2 +- 4 files changed, 594 insertions(+), 10 deletions(-) create mode 100644 packages/cursor/http1.test.mjs diff --git a/packages/cursor/README.md b/packages/cursor/README.md index 9fae278..ad20d0f 100644 --- a/packages/cursor/README.md +++ b/packages/cursor/README.md @@ -38,6 +38,18 @@ plugin's `fetch` answers them on Cursor's agent API: - Each request is one `agent.v1.AgentService/Run`, a Connect stream both ways over HTTP/2, with the CLI's headers (`x-cursor-client-type: cli`, its version, privacy mode on). +- Where HTTP/2 can't open a Run (an error before its response, or none in + 15 s: a proxy or network that blocks HTTP/2), it goes as Cursor's clients + run it without HTTP/2: `agent.v1.AgentService/RunSSE` down and a + `aiserver.v1.BidiService/BidiAppend` for each client message up, over + HTTP/1.1 on `api2.cursor.sh`, through the proxy magpie gives the request. + When the failure says HTTP/2 itself can't be had (no head in 15 s, + "h2 is not supported", no HTTP/2 in ALPN, a protocol error), the Runs + after it go straight to HTTP/1.1 for 10 minutes; a failed connection + (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. A BidiAppend with no answer in 60 s + (more for a large one) ends the Run, as cursor-agent does. - The whole conversation goes each time, as AI SDK messages kept as blobs the server asks for. The caller's tools are MCP tools, listed in the system prompt; the model calls them through Cursor's `CallDynamicTool`, diff --git a/packages/cursor/http1.test.mjs b/packages/cursor/http1.test.mjs new file mode 100644 index 0000000..ad56af9 --- /dev/null +++ b/packages/cursor/http1.test.mjs @@ -0,0 +1,416 @@ +// Where HTTP/2 can't open a Run (a proxy or network that blocks it), the +// Run goes over HTTP/1.1 as Cursor's clients run it: RunSSE down, a +// BidiAppend for each client message up. Only a failure that says HTTP/2 +// itself can't be had keeps the Runs after it on HTTP/1.1; a refused +// connection doesn't. Against a fake Cursor: its API, RunSSE and BidiAppend +// included, answered by a stand-in fetch, its agent API by an HTTP/2 server +// here, or a port nothing listens on. Nothing reaches Cursor. +import "./nonet.mjs" // first: no request leaves this machine +import { afterAll, afterEach, beforeEach, expect, test } from "bun:test" +import http from "node:http" +import http2 from "node:http2" +import { CursorAuthPlugin, _internal } from "./index.mjs" + +const { fields, pb, frame, h2Blocked, open, openH1 } = _internal +const H2 = _internal.H2 ?? {} +const H1 = _internal.H1 ?? {} + +const real = globalThis.fetch +const saved = { ...H2 } +const savedH1 = { ...H1 } +afterEach(() => { + globalThis.fetch = real + Object.assign(H2, saved) + Object.assign(H1, savedH1) +}) +beforeEach(() => _internal.resetH1()) + +// how many HTTP/2 sessions the plugin opened +let h2Tries = 0 +const connect = http2.connect +http2.connect = (origin, ...rest) => { + if (!String(origin).startsWith("http://127.0.0.1:")) throw new Error("the test connected to " + origin) + h2Tries++ + return connect(origin, ...rest) +} +afterAll(() => { + http2.connect = connect + _internal.resetH1() +}) + +const jwt = (exp) => ["e30", Buffer.from(JSON.stringify({ exp, sub: "http1-" + Math.random() })).toString("base64url"), "sig"].join(".") +let n = 0 +const fresh = () => ({ type: "oauth", access: jwt(Math.floor(Date.now() / 1000) + 7200 + ++n), refresh: "", expires: 0, accountId: "a@b.c" }) + +// a port nothing listens on, for now +async function freePort() { + const server = http.createServer() + await new Promise((r) => server.listen(0, "127.0.0.1", r)) + const { port } = server.address() + await new Promise((r) => server.close(r)) + return port +} + +const end = (body) => { + const f = frame(Buffer.from(body)) + f[0] = 2 + return f +} +const update = (num, body) => frame(pb().bytes(1, pb().bytes(num, body)).done()) + +// the agent API over HTTP/2 on port: "answer" answers a Run "hi" and the +// turn's end; "stall" takes the stream and never sends its head; "refuse" +// closes the stream with code (REFUSED_STREAM unless told) before its head. +// resets refuses that many streams first, whatever the mode. +async function agent(port, mode, { resets = 0, code = http2.constants.NGHTTP2_REFUSED_STREAM } = {}) { + const a = { mode, runs: 0, resets, code } + a.server = http2.createServer() + a.server.on("stream", (stream) => { + stream.on("error", () => {}) + if (a.resets > 0 || a.mode === "refuse") { + a.resets-- + return stream.close(a.code) + } + if (a.mode === "stall") return + a.runs++ + stream.respond({ ":status": 200, "content-type": "application/connect+proto" }) + let buf = Buffer.alloc(0) + let answered = false + stream.on("data", (c) => { + buf = Buffer.concat([buf, c]) + if (answered || buf.length < 5 || buf.length < 5 + buf.readUInt32BE(1)) return + answered = true + stream.write(update(1, pb().str(1, "hi").done())) + stream.write(update(14, pb().varint(1, 0).done())) + stream.end(end("{}")) + }) + }) + await new Promise((r) => a.server.listen(port, "127.0.0.1", r)) + return a +} + +// Cursor's API over HTTP/1.1. RunSSE's stream answers once BidiAppend has +// brought the Run's first message: "hi" and the turn's end, or the error +// given in its end frame (refuse) or as an HTTP error (sseHttp). A +// BidiAppend answers, answers an HTTP error (appendHttp), or never answers +// (hangAppend). What each call carried is noted. +// an HTTP error: Connect's JSON, or a plain body as a proxy or load balancer sends +const httpError = (e) => + typeof e.body === "string" + ? new Response(e.body, { status: e.status, headers: { "content-type": "text/plain" } }) + : new Response(JSON.stringify(e.body), { status: e.status, headers: { "content-type": "application/json" } }) +function fakeAPI(base, { refuse, sseHttp, appendHttp, hangAppend } = {}) { + const seen = { sse: [], appends: [] } + const streams = new Map() // request id → RunSSE's controller + globalThis.fetch = async (url, init = {}) => { + const u = String(url) + const h = new Headers(init.headers) + if (u.endsWith("/aiserver.v1.ServerConfigService/GetServerConfig")) return Response.json({ agentUrlConfig: { agentUrl: base } }) + if (u.endsWith("/agent.v1.AgentService/GetUsableModels")) return Response.json({ models: [{ modelId: "grok-4.7-fast", displayName: "Grok 4.7 Fast" }] }) + if (u === "https://api2.cursor.sh/agent.v1.AgentService/RunSSE") { + const id = fields(Buffer.from(init.body).subarray(5))[0].data.toString() + seen.sse.push({ id, type: h.get("content-type"), auth: h.get("authorization"), encoding: h.get("accept-encoding") }) + if (sseHttp) return httpError(sseHttp) + if (refuse) return new Response(end(JSON.stringify({ error: refuse })), { headers: { "content-type": "application/connect+proto" } }) + return new Response(new ReadableStream({ start: (c) => streams.set(id, c) }), { headers: { "content-type": "application/connect+proto" } }) + } + if (u === "https://api2.cursor.sh/aiserver.v1.BidiService/BidiAppend") { + const f = fields(Buffer.from(init.body)) + const id = fields(f.find((x) => x.num === 2).data)[0].data.toString() + const seqno = f.find((x) => x.num === 3)?.n ?? 0 + const msg = Buffer.from(f.find((x) => x.num === 1).data.toString(), "hex") + seen.appends.push({ id, seqno, type: h.get("content-type") }) + if (appendHttp) return httpError(appendHttp) + if (hangAppend) return new Promise((_, no) => init.signal?.addEventListener("abort", () => no(init.signal.reason), { once: true })) + const c = streams.get(id) + if (c && seqno === 0 && fields(msg).some((x) => x.num === 1)) { + c.enqueue(update(1, pb().str(1, "hi").done())) + c.enqueue(update(14, pb().varint(1, 0).done())) + c.enqueue(end("{}")) + c.close() + } + return new Response(new Uint8Array(0), { headers: { "content-type": "application/proto" } }) + } + throw new Error("the test asked " + u) + } + return seen +} + +async function ask(auth, base) { + const hooks = await CursorAuthPlugin() + const l = await hooks.auth.loader(async () => auth) + const res = await l.fetch(base + "/v1/chat/completions", { + method: "POST", + body: JSON.stringify({ model: "grok-4.7-fast", messages: [{ role: "user", content: "hello" }] }), + }) + return { status: res.status, body: await res.json() } +} + +test("a Run whose HTTP/2 connection is refused goes as RunSSE + BidiAppend over HTTP/1.1, and the next tries HTTP/2 again", async () => { + const base = `http://127.0.0.1:${await freePort()}` + const seen = fakeAPI(base) + const auth = fresh() + h2Tries = 0 + const a = await ask(auth, base) + expect(a.status).toBe(200) + expect(a.body.choices[0].message.content).toBe("hi") + expect(h2Tries).toBe(1) + expect(seen.sse).toHaveLength(1) + expect(seen.sse[0]).toMatchObject({ type: "application/connect+proto", encoding: "identity" }) + expect(seen.sse[0].auth).toBe(`Bearer ${auth.access}`) + // the Run's first message, numbered 0, under RunSSE's request id + expect(seen.appends[0]).toMatchObject({ id: seen.sse[0].id, seqno: 0, type: "application/proto" }) + const b = await ask(auth, base) + expect(b.body.choices[0].message.content).toBe("hi") + expect(h2Tries).toBe(2) // a refused connection says nothing of HTTP/2 + expect(seen.sse).toHaveLength(2) +}) + +test("refused once, then a working HTTP/2 agent: the next Run goes over HTTP/2", async () => { + const port = await freePort() + const base = `http://127.0.0.1:${port}` + const seen = fakeAPI(base) + const auth = fresh() + h2Tries = 0 + const a = await ask(auth, base) + expect(a.body.choices[0].message.content).toBe("hi") + expect(seen.sse).toHaveLength(1) + const ag = await agent(port, "answer") + try { + const b = await ask(auth, base) + expect(b.body.choices[0].message.content).toBe("hi") + expect(h2Tries).toBe(2) + expect(ag.runs).toBe(1) + expect(seen.sse).toHaveLength(1) + } finally { + ag.server.close() + } +}) + +test("no head over HTTP/2 in time keeps the Runs after it on HTTP/1.1", async () => { + H2.wait = 200 + const port = await freePort() + const base = `http://127.0.0.1:${port}` + const ag = await agent(port, "stall") + try { + const seen = fakeAPI(base) + const auth = fresh() + h2Tries = 0 + const a = await ask(auth, base) + expect(a.body.choices[0].message.content).toBe("hi") + expect(seen.sse).toHaveLength(1) + const b = await ask(auth, base) + expect(b.body.choices[0].message.content).toBe("hi") + expect(h2Tries).toBe(1) // no second try over HTTP/2 + expect(seen.sse).toHaveLength(2) + } finally { + ag.server.close() + } +}) + +test("a region error over HTTP/1.1 sends the Run back to HTTP/2 at the region's agent host", async () => { + H2.wait = 200 + const port = await freePort() + const base = `http://127.0.0.1:${port}` + const ag = await agent(port, "stall") + try { + const auth = fresh() + fakeAPI(base) + await ask(auth, base) // HTTP/2 found blocked: on HTTP/1.1 from now on + ag.mode = "answer" + const seen = fakeAPI(base, { refuse: { code: "permission_denied", message: "This team is served in its region only" } }) + h2Tries = 0 + const r = await ask(auth, base) + expect(r.status).toBe(200) + expect(r.body.choices[0].message.content).toBe("hi") + expect(seen.sse).toHaveLength(1) + expect(h2Tries).toBe(1) + expect(ag.runs).toBe(1) + } finally { + ag.server.close() + } +}) + +test("only a failure that says HTTP/2 itself can't be had counts as blocked", () => { + expect(h2Blocked(Object.assign(new Error("no answer over HTTP/2 in 15s"), { h2Timeout: true }))).toBe(true) + expect(h2Blocked(new Error("h2 is not supported"))).toBe(true) + expect(h2Blocked(Object.assign(new Error("Protocol error"), { code: "ERR_HTTP2_ERROR" }))).toBe(true) + expect(h2Blocked(Object.assign(new Error("connect ECONNREFUSED 127.0.0.1:1"), { code: "ECONNREFUSED" }))).toBe(false) + expect(h2Blocked(Object.assign(new Error("getaddrinfo ENOTFOUND agentn.global.api5.cursor.sh"), { code: "ENOTFOUND" }))).toBe(false) + expect(h2Blocked(Object.assign(new Error("read ECONNRESET"), { code: "ECONNRESET" }))).toBe(false) + expect(h2Blocked(Object.assign(new Error("connect ENETUNREACH"), { code: "ENETUNREACH" }))).toBe(false) + expect(h2Blocked(new Error("something else"))).toBe(false) + // a connection reset that also says "protocol error" is still a connection's failure + expect(h2Blocked(Object.assign(new Error("Protocol error: read ECONNRESET"), { code: "ECONNRESET" }))).toBe(false) + // a stream the server refused: HTTP/2 itself got through + expect(h2Blocked(Object.assign(new Error("Stream closed with error code NGHTTP2_REFUSED_STREAM"), { code: "ERR_HTTP2_STREAM_ERROR" }))).toBe(false) +}) + +test("an error Cursor ends RunSSE with keeps its status", async () => { + const base = `http://127.0.0.1:${await freePort()}` + fakeAPI(base, { + refuse: { code: "unauthenticated", message: "Error", details: [{ debug: { error: "ERROR_NOT_LOGGED_IN", details: { title: "Authentication error", detail: "If you are logged in, try logging out and back in." } } }] }, + }) + const r = await ask(fresh(), base) + expect(r.status).toBe(401) + expect(r.body.error.message).toContain("Authentication error") +}) + +const SIGNED_OUT = { code: "unauthenticated", message: "Error", details: [{ debug: { error: "ERROR_NOT_LOGGED_IN", details: { title: "Authentication error", detail: "If you are logged in, try logging out and back in." } } }] } + +// REFUSED_STREAM comes as an error on the stream; CANCEL (and NO_ERROR) +// closes it with none, which only its close says +for (const [name, code] of [ + ["REFUSED_STREAM", http2.constants.NGHTTP2_REFUSED_STREAM], + ["CANCEL", http2.constants.NGHTTP2_CANCEL], +]) { + test(`a stream closed before its head (${name}) falls back at once, and the next Run tries HTTP/2 again`, async () => { + H2.wait = 2000 + const port = await freePort() + const base = `http://127.0.0.1:${port}` + const ag = await agent(port, "refuse", { code }) + try { + const seen = fakeAPI(base) + const auth = fresh() + h2Tries = 0 + const t = Date.now() + const a = await ask(auth, base) + expect(a.body.choices[0].message.content).toBe("hi") + expect(Date.now() - t).toBeLessThan(1000) // not the head timer's 2 s + expect(seen.sse).toHaveLength(1) + expect(_internal.onH1()).toBe(false) + ag.mode = "answer" + const b = await ask(auth, base) + expect(b.body.choices[0].message.content).toBe("hi") + expect(h2Tries).toBe(2) + expect(ag.runs).toBe(1) + expect(seen.sse).toHaveLength(1) + } finally { + ag.server.close() + } + }) +} + +test("a BidiAppend that never answers ends the Run with deadline_exceeded", async () => { + H1.appendWait = 200 + const base = `http://127.0.0.1:${await freePort()}` + fakeAPI(base, { hangAppend: true }) + const t = Date.now() + const r = await ask(fresh(), base) + expect(r.status).toBe(502) + expect(r.body.error.message).toContain("BidiAppend got no answer") + expect(Date.now() - t).toBeLessThan(5000) +}) + +test("an HTTP error from RunSSE keeps its status", async () => { + const base = `http://127.0.0.1:${await freePort()}` + fakeAPI(base, { sseHttp: { status: 401, body: SIGNED_OUT } }) + const r = await ask(fresh(), base) + expect(r.status).toBe(401) + expect(r.body.error.message).toContain("Authentication error") +}) + +test("an HTTP error from BidiAppend keeps its status", async () => { + const base = `http://127.0.0.1:${await freePort()}` + fakeAPI(base, { appendHttp: { status: 401, body: SIGNED_OUT } }) + const r = await ask(fresh(), base) + expect(r.status).toBe(401) + expect(r.body.error.message).toContain("Authentication error") +}) + +test("an HTTP error with no Connect error of its own keeps its status: 401 from RunSSE, 429 from BidiAppend", async () => { + const base = `http://127.0.0.1:${await freePort()}` + fakeAPI(base, { sseHttp: { status: 401, body: "Unauthorized" } }) + expect((await ask(fresh(), base)).status).toBe(401) + fakeAPI(base, { appendHttp: { status: 429, body: "Too Many Requests" } }) + expect((await ask(fresh(), base)).status).toBe(429) +}) + +test("appends go up one at a time, numbered in order, a slow one holding the rest", async () => { + const got = [] + let inFlight = 0 + let most = 0 + globalThis.fetch = async (url, init = {}) => { + const u = String(url) + if (u.endsWith("/agent.v1.AgentService/RunSSE")) return new Response(new ReadableStream({}), { headers: { "content-type": "application/connect+proto" } }) + if (u.endsWith("/aiserver.v1.BidiService/BidiAppend")) { + const f = fields(Buffer.from(init.body)) + const seqno = f.find((x) => x.num === 3)?.n ?? 0 + inFlight++ + most = Math.max(most, inFlight) + if (seqno === 0) await new Promise((r) => setTimeout(r, 150)) // the first one slow + got.push({ seqno, data: Buffer.from(f.find((x) => x.num === 1).data.toString(), "hex").toString() }) + inFlight-- + return new Response(new Uint8Array(0), { headers: { "content-type": "application/proto" } }) + } + throw new Error("the test asked " + u) + } + const o = await openH1({ "x-request-id": "r-1", authorization: "Bearer t" }) + for (const m of ["first", "blob 1", "blob 2", "blob 3"]) o.req.write(frame(Buffer.from(m))) + for (let i = 0; i < 100 && got.length < 4; i++) await new Promise((r) => setTimeout(r, 10)) + o.session.close() + expect(got).toEqual([ + { seqno: 0, data: "first" }, + { seqno: 1, data: "blob 1" }, + { seqno: 2, data: "blob 2" }, + { seqno: 3, data: "blob 3" }, + ]) + expect(most).toBe(1) +}) + +test("a Run cancelled while HTTP/2 opens is not counted as HTTP/2 failing", async () => { + H2.wait = 10_000 + const port = await freePort() + const ag = await agent(port, "stall") + try { + const ac = new AbortController() + setTimeout(() => ac.abort(), 50) + const t = Date.now() + const o = await open(`http://127.0.0.1:${port}`, { "x-request-id": "r-2" }, ac.signal) + expect(o.error?.message).toContain("cancelled") + expect(Date.now() - t).toBeLessThan(2000) + expect(_internal.onH1()).toBe(false) + } finally { + ag.server.close() + } +}) + +test("Runs kept on HTTP/1.1 try HTTP/2 again once H2.retryAfter has passed", async () => { + H2.wait = 200 + H2.retryAfter = 300 + const port = await freePort() + const base = `http://127.0.0.1:${port}` + const ag = await agent(port, "stall") + try { + fakeAPI(base) + const auth = fresh() + h2Tries = 0 + await ask(auth, base) + expect(_internal.onH1()).toBe(true) + await new Promise((r) => setTimeout(r, 400)) + expect(_internal.onH1()).toBe(false) + ag.mode = "answer" + const b = await ask(auth, base) + expect(b.body.choices[0].message.content).toBe("hi") + expect(h2Tries).toBe(2) + expect(ag.runs).toBe(1) + } finally { + ag.server.close() + } +}) + +test("a region error on a Run that fell back for itself alone tries HTTP/2 again too", async () => { + const port = await freePort() + const base = `http://127.0.0.1:${port}` + const ag = await agent(port, "answer", { resets: 1 }) // the first stream refused: that Run alone falls back + try { + const seen = fakeAPI(base, { refuse: { code: "permission_denied", message: "This team is served in its region only" } }) + const r = await ask(fresh(), base) + expect(r.status).toBe(200) + expect(r.body.choices[0].message.content).toBe("hi") + expect(seen.sse).toHaveLength(1) + expect(ag.runs).toBe(1) + } finally { + ag.server.close() + } +}) diff --git a/packages/cursor/index.mjs b/packages/cursor/index.mjs index 2cb03d2..0ed214e 100644 --- a/packages/cursor/index.mjs +++ b/packages/cursor/index.mjs @@ -11,6 +11,10 @@ // CURSOR_API_KEY. // // Requests go to AgentService/Run, a Connect stream both ways over HTTP/2. +// Where HTTP/2 can't open one (a proxy or network that blocks it), the Run +// goes as Cursor's clients run it without HTTP/2: its replies down one +// server stream, AgentService/RunSSE, and each client message up as a call +// of its own, BidiService/BidiAppend, both over HTTP/1.1 on api2. // Cursor keeps a conversation on its client: each message of the prompt is // an AI SDK message in JSON, a blob named by its sha256, which the server // asks the client for as it reads them. So each request goes whole, as such @@ -27,6 +31,7 @@ import http2 from "node:http2" import { STATUS_CODES } from "node:http" import { gunzipSync } from "node:zlib" +import { Duplex } from "node:stream" import { createHash, randomBytes, randomUUID } from "node:crypto" import { execFile } from "node:child_process" import { readFile, stat, readdir, realpath } from "node:fs/promises" @@ -1509,18 +1514,61 @@ async function agentURL(tok, fresh) { } // open starts a Run at base: the session, the stream, and the response's -// status, or an error the request never got past. -function open(base, headers, signal) { +// status, or an error the request never got past. A Run HTTP/2 can't open +// goes over HTTP/1.1 (openH1). When the failure says HTTP/2 itself can't be +// had here (h2Blocked), the Runs after it go straight to HTTP/1.1 for +// 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. +let h1Until = 0 +async function open(base, headers, signal) { + if (Date.now() >= h1Until) { + const o = await openH2(base, headers, signal) + if (!o.h2Failed) return o + if (o.blocked) h1Until = Date.now() + H2.retryAfter + } + return openH1(headers, signal) +} + +const H2 = { + wait: 15_000, // ms an HTTP/2 Run waits for its response's head + retryAfter: 10 * 60_000, // ms the Runs after one found HTTP/2 blocked stay on HTTP/1.1 +} + +// NET are the failures of a connection itself, which say nothing of HTTP/2 +const NET = ["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "ENETUNREACH", "EHOSTUNREACH", "ECONNRESET", "ETIMEDOUT", "ECONNABORTED", "EPIPE"] + +// h2Blocked is whether a failure to open an HTTP/2 Run says HTTP/2 itself +// can't be had: no head in H2.wait, the "h2 is not supported" magpie's +// host gives a tunnel that can't carry it, a server or proxy that won't +// negotiate it (ALPN), an HTTP/2 protocol error. Anything else, a failed +// connection above all, is not. +function h2Blocked(e) { + if (e?.h2Timeout) return true + const code = String(e?.code ?? "") + const text = `${code} ${e?.message ?? ""}` + if (NET.some((c) => text.includes(c))) return false + // a stream the server refused or reset: HTTP/2 itself got through + if (code === "ERR_HTTP2_STREAM_ERROR") return false + return code.startsWith("ERR_HTTP2") || /h2 is not supported|alpn|nghttp2|protocol error/i.test(text) +} + +// openH2 is open over HTTP/2. A Run that fails before its response, other +// than by being cancelled, says h2Failed, and blocked when h2Blocked says +// so of the failure. +function openH2(base, headers, signal) { return new Promise((resolve) => { const u = new URL(base) const session = http2.connect(u.origin) let done = false - const fail = (e) => { + const fail = (e, h2Failed = true) => { if (done) return done = true + clearTimeout(timer) session.destroy() - resolve({ error: { status: 502, message: e?.message ?? String(e) } }) + resolve({ error: { status: 502, message: e?.message ?? String(e) }, h2Failed, blocked: h2Failed && h2Blocked(e) }) } + const timer = setTimeout(() => fail(Object.assign(new Error(`no answer over HTTP/2 in ${H2.wait / 1000}s`), { h2Timeout: true })), H2.wait) session.on("error", fail) const req = session.request({ ":method": "POST", @@ -1528,15 +1576,120 @@ function open(base, headers, signal) { ...headers, }) req.on("error", fail) + // a stream reset before its head (RST_STREAM, REFUSED_STREAM) may close + // it with no error said + req.once("close", () => fail(Object.assign(new Error(`the HTTP/2 stream closed before its response (code ${req.rstCode ?? "?"})`), { code: "ERR_HTTP2_STREAM_ERROR" }))) req.once("response", (h) => { if (done) return done = true + clearTimeout(timer) resolve({ session, req, status: Number(h[":status"]) }) }) - signal?.addEventListener("abort", () => fail(new Error("the request was cancelled")), { once: true }) + signal?.addEventListener("abort", () => fail(new Error("the request was cancelled"), false), { once: true }) }) } +const H1 = { appendWait: 60_000 } // ms a BidiAppend may take before the Run fails, as cursor-agent's appendTimeoutMs + +// connectCode is Connect's code for an HTTP status that came with no +// Connect error of its own +function connectCode(status) { + return { 400: "invalid_argument", 401: "unauthenticated", 403: "permission_denied", 429: "resource_exhausted" }[status] ?? "unavailable" +} + +// openH1 is open over HTTP/1.1, as Cursor's clients run a Run without +// HTTP/2: what runOnce writes (a Connect frame each time) goes up as +// BidiAppend calls in turn, numbered from 0, and what RunSSE sends down is +// 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) { + const ac = new AbortController() + signal?.addEventListener("abort", () => ac.abort(), { once: true }) + const id = headers["x-request-id"] + const h = { ...headers, "accept-encoding": "identity", "x-cursor-streaming": "true" } + let ended = false + let seq = 0 + let chain = Promise.resolve() + const req = new Duplex({ + read() {}, + write(chunk, _enc, cb) { + // runOnce writes one whole frame each time + const msg = Buffer.from(chunk).subarray(5) + const n = seq++ + chain = chain.then(() => (ended ? undefined : append(msg, n))) + cb() + }, + }) + const end = (body) => { + if (ended || req.destroyed) return + ended = true + const f = frame(Buffer.from(body)) + f[0] = 2 + req.push(f) + req.push(null) + ac.abort() + } + const failed = async (res) => { + const text = await res.text().catch(() => "") + let e + try { + e = JSON.parse(text) + } catch {} + end(JSON.stringify({ error: typeof e?.code === "string" ? e : { code: connectCode(res.status), message: text.trim() || `HTTP ${res.status}` } })) + } + // append sends one message up. One that gets no answer by its deadline + // (more time for a large one) ends the Run, as cursor-agent's + // bidi_append_deadline_exceeded does: the messages after it wait on it. + const append = async (msg, n) => { + const body = pb().str(1, msg.toString("hex")).bytes(2, pb().str(1, id).done()).varint(3, n).done() + const ms = H1.appendWait + Math.ceil(body.length / 65536) * 1000 + const deadline = AbortSignal.timeout(ms) + try { + const res = await fetch(API + "/aiserver.v1.BidiService/BidiAppend", { + method: "POST", + headers: { ...h, "content-type": "application/proto", "connect-protocol-version": "1" }, + body, + signal: AbortSignal.any([ac.signal, deadline]), + }) + if (!res.ok) return failed(res) + await res.arrayBuffer() + } catch (e) { + if (ac.signal.aborted) return + if (deadline.aborted) return end(JSON.stringify({ error: { code: "deadline_exceeded", message: `BidiAppend got no answer in ${Math.round(ms / 1000)}s` } })) + end(JSON.stringify({ error: { code: "unavailable", message: `BidiAppend: ${e?.message ?? e}` } })) + } + } + ;(async () => { + try { + const res = await fetch(API + "/agent.v1.AgentService/RunSSE", { + method: "POST", + headers: { ...h, "content-type": "application/connect+proto", "connect-protocol-version": "1" }, + body: frame(pb().str(1, id).done()), + signal: ac.signal, + }) + if (!res.ok) return failed(res) + for await (const c of res.body) { + if (ended || req.destroyed) return + req.push(Buffer.from(c)) + } + if (!ended && !req.destroyed) { + ended = true + req.push(null) + } + } catch (e) { + if (!ac.signal.aborted) end(JSON.stringify({ error: { code: "unavailable", message: `RunSSE: ${e?.message ?? e}` } })) + } + })() + const close = () => { + ended = true + ac.abort() + req.destroy() + } + return Promise.resolve({ session: { close, destroy: close }, req: Object.assign(req, { close }), status: 200, h1: true }) +} + // runOnce is one Run of the chat on the agent API at base: an async // iterator of the answer's pieces, or the error it failed with before any. async function runOnce({ tok, base, id, tools, conv, convID, signal, maxMode, params }) { @@ -1615,7 +1768,7 @@ async function runOnce({ tok, base, id, tools, conv, convID, signal, maxMode, pa if (head.done) return book.done(), { error: { status: 502, message: "an empty reply" } } if (head.value.error) { await wrapped.return() - return { error: head.value.error } + return { error: head.value.error, h1: !!o.h1 } } return { events: (async function* () { @@ -1883,9 +2036,12 @@ async function answerOf(auth, chat, signal, session = "") { let r = await once() if (r.error && regional(r.error.message)) { // the team moved, or the config was kept from before: once more with - // what the config says now + // what the config says now. A Run that went over HTTP/1.1 went to api2, + // not the region's agent host: once more over HTTP/2 there. + const viaH1 = !!r.h1 + h1Until = 0 const fresh = await agentURL(tok, true) - if (fresh !== base) { + if (fresh !== base || viaH1) { base = fresh r = await once() } @@ -2041,4 +2197,4 @@ export async function CursorAuthPlugin() { } // for tests -export const _internal = { STEP_WAIT, stepUsage, 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 = { resetH1: () => (h1Until = 0), onH1: () => Date.now() < h1Until, H2, H1, h2Blocked, open, openH1, STEP_WAIT, stepUsage, 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/package.json b/packages/cursor/package.json index 654f61d..f971c7d 100644 --- a/packages/cursor/package.json +++ b/packages/cursor/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-cursor-auth", - "version": "0.2.2", + "version": "0.2.3", "description": "Cursor subscriptions (Pro, Pro+, Ultra, Teams) in OpenCode and magpie, through the API cursor-agent talks to", "type": "module", "main": "./index.mjs",