diff --git a/packages/cursor/README.md b/packages/cursor/README.md index 24c9b3f..3f8100f 100644 --- a/packages/cursor/README.md +++ b/packages/cursor/README.md @@ -43,8 +43,18 @@ plugin's `fetch` answers them on Cursor's agent API: system prompt; the model calls them through Cursor's `CallDynamicTool`, and the calls come back as chat completion tool calls. Cursor's own tools (shell, file reads, edits) are never run. +- A conversation's Runs share one `conversation_id`, so Cursor sends them + to the machine that has the prompt cached (Grok on Cursor caches by + machine). It is made from what names the session — the request's + `prompt_cache_key` (Codex's thread id), else the session the + `chat.headers` hook is told — and the conversation's first user message, + so subagents under one session are conversations of their own. With + nothing naming the session, each Run has a new one. - Text, thinking (`reasoning_content`) and token usage come back streamed - or not. Failures keep their statuses: 401 to sign in again, 429 at the + or not. Cursor's `input_tokens` counts the cached prompt too: the cache + read and written is taken out of it, and given as `cached_tokens` and + `cache_write_tokens`, so it is counted once; its reasoning tokens are + `reasoning_tokens`. Failures keep their statuses: 401 to sign in again, 429 at the usage limit, 400 for a prompt too long, 403 for a region refusal. ## Models diff --git a/packages/cursor/conversation.test.mjs b/packages/cursor/conversation.test.mjs new file mode 100644 index 0000000..b00342c --- /dev/null +++ b/packages/cursor/conversation.test.mjs @@ -0,0 +1,174 @@ +// A conversation's Runs keep one conversation_id and Cursor's usage counts +// the cache once, as the built-in's cursorConversation and cursorUsage do +// (magpie #498, internal/gateway/cursor_conversation_test.go), against a +// fake Cursor: its API answered by a stand-in fetch, its agent API by an +// HTTP/2 server here. Nothing reaches Cursor. +import { afterAll, afterEach, beforeAll, expect, test } from "bun:test" +import http2 from "node:http2" +import { CursorAuthPlugin, _internal } from "./index.mjs" + +const { fields, pb, frame, SESSION } = _internal + +const real = globalThis.fetch +afterEach(() => (globalThis.fetch = real)) +// no Run leaves this machine: the agent API is the fake one here or none +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) + return connect(origin, ...rest) +} +afterAll(() => (http2.connect = connect)) + +const jwt = (exp) => ["e30", Buffer.from(JSON.stringify({ exp })).toString("base64url"), "sig"].join(".") +let n = 0 +// a sign-in of its own, so no list or endpoint kept for another is used +const fresh = () => ({ type: "oauth", access: jwt(Math.floor(Date.now() / 1000) + 7200 + ++n), refresh: "", expires: 0, accountId: "a@b.c" }) + +// the agent API: each Run's conversation_id noted, answered "hi" and the +// turn's usage +let server, base +const runs = [] +let turnEnded = pb().varint(1, 0).done() +beforeAll(async () => { + server = http2.createServer() + server.on("stream", (stream, headers) => { + // the headers first, as Cursor's do: the client sends the Run after them + 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 + const msg = buf.subarray(5, 5 + buf.readUInt32BE(1)) + const rr = fields(fields(msg).find((f) => f.num === 1).data) + runs.push({ path: headers[":path"], conv: rr.find((f) => f.num === 5)?.data.toString() }) + const update = (num, body) => frame(pb().bytes(1, pb().bytes(num, body)).done()) + stream.write(update(1, pb().str(1, "hi").done())) + stream.write(update(14, turnEnded)) + const end = Buffer.from("{}") + const head = Buffer.alloc(5) + head[0] = 2 + head.writeUInt32BE(end.length, 1) + stream.end(Buffer.concat([head, end])) + }) + stream.on("error", () => {}) + }) + await new Promise((r) => server.listen(0, "127.0.0.1", r)) + base = `http://127.0.0.1:${server.address().port}` +}) +afterAll(() => server.close()) + +// Cursor's API: the server config naming the fake agent API, and a list +function fakeAPI() { + globalThis.fetch = async (url) => { + const u = String(url) + if (u === "https://api2.cursor.sh/aiserver.v1.ServerConfigService/GetServerConfig") return Response.json({ agentUrlConfig: { agentUrl: base } }) + if (u === "https://api2.cursor.sh/agent.v1.AgentService/GetUsableModels") return Response.json({ models: [{ modelId: "grok-4.7-fast", displayName: "Grok 4.7 Fast" }] }) + throw new Error("the test asked " + u) + } +} + +// ask sends a chat completion as magpie's host does: the chat.headers hook +// told the session, then the loader's fetch with what it added +async function ask(auth, chat, { session = "", provider = "cursor" } = {}) { + const hooks = await CursorAuthPlugin() + const out = { headers: {} } + await hooks["chat.headers"]({ sessionID: session, model: { providerID: provider, id: chat.model }, provider: { info: { id: provider } } }, out) + const l = await hooks.auth.loader(async () => auth) + const res = await l.fetch(base + "/v1/chat/completions", { method: "POST", headers: new Headers(out.headers), body: JSON.stringify(chat) }) + const j = await res.json() + expect([res.status, j.error]).toEqual([200, undefined]) + expect(j.choices[0].message.content).toBe("hi") + return { conv: runs.at(-1).conv, usage: j.usage, headers: out.headers } +} + +const turn = (first, ...more) => ({ + model: "grok-4.7-fast", + messages: [{ role: "system", content: "be brief" }, { role: "user", content: first }, ...more], +}) +const later = (first) => turn(first, { role: "assistant", content: "hi" }, { role: "user", content: "and then?" }) +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/ + +test("a session's turns keep one conversation_id; another session, or another first message, has its own", async () => { + fakeAPI() + const auth = fresh() + const a1 = await ask(auth, turn("fix the bug"), { session: "ses_claude_1" }) + expect(a1.headers).toEqual({ [SESSION]: "ses_claude_1" }) + expect(runs.at(-1).path).toBe("/agent.v1.AgentService/Run") + expect(a1.conv).toMatch(UUID) + const a2 = await ask(auth, later("fix the bug"), { session: "ses_claude_1" }) + expect(a2.conv).toBe(a1.conv) + // a subagent under the same session: a conversation of its own + const sub = await ask(auth, turn("search the repo"), { session: "ses_claude_1" }) + expect(sub.conv).not.toBe(a1.conv) + // the same words in another session + const other = await ask(auth, turn("fix the bug"), { session: "ses_claude_2" }) + expect(other.conv).not.toBe(a1.conv) +}) + +test("Codex's prompt_cache_key names the session before the host's", async () => { + fakeAPI() + const auth = fresh() + const c1 = await ask(auth, { ...turn("hello"), prompt_cache_key: "thread-1" }, { session: "ses_x" }) + const c2 = await ask(auth, { ...later("hello"), prompt_cache_key: "thread-1" }, { session: "ses_y" }) + expect(c2.conv).toBe(c1.conv) + const c3 = await ask(auth, { ...later("hello"), prompt_cache_key: "thread-2" }, { session: "ses_x" }) + expect(c3.conv).not.toBe(c1.conv) + // with no session from the host at all + const c4 = await ask(auth, { ...later("hello"), prompt_cache_key: "thread-1" }) + expect(c4.conv).toBe(c1.conv) +}) + +test("nothing naming the session: each Run a new id, as before", async () => { + fakeAPI() + const auth = fresh() + // magpie's own, made of the first message when the agent names no session + const m1 = await ask(auth, turn("hi"), { session: "magpie-0123456789abcdef01234567" }) + expect(m1.headers).toEqual({}) + const m2 = await ask(auth, turn("hi"), { session: "magpie-0123456789abcdef01234567" }) + const m3 = await ask(auth, turn("hi")) + expect(new Set([m1.conv, m2.conv, m3.conv]).size).toBe(3) + for (const c of [m1.conv, m2.conv, m3.conv]) expect(c).toMatch(UUID) +}) + +test("the hook leaves other providers' requests alone", async () => { + const hooks = await CursorAuthPlugin() + const out = { headers: {} } + await hooks["chat.headers"]({ sessionID: "ses_1", model: { providerID: "grok" }, provider: { info: { id: "grok" } } }, out) + expect(out.headers).toEqual({}) +}) + +test("usage takes the cache out of input_tokens, and keeps reasoning", async () => { + fakeAPI() + const auth = fresh() + // the issue's Opus turn: 15050 in, 15046 of it written to the cache + turnEnded = pb().varint(1, 15050).varint(2, 12).varint(3, 0).varint(4, 15046).varint(5, 7).done() + let { usage } = await ask(auth, turn("x"), { session: "s" }) + expect(usage).toEqual({ + prompt_tokens: 15050, + completion_tokens: 12, + total_tokens: 15062, + prompt_tokens_details: { cached_tokens: 0, cache_write_tokens: 15046 }, + completion_tokens_details: { reasoning_tokens: 7 }, + }) + // read from the cache and some written + turnEnded = pb().varint(1, 15119).varint(2, 3).varint(3, 15096).varint(4, 23).done() + ;({ usage } = await ask(auth, turn("x"), { session: "s" })) + expect(usage).toEqual({ + prompt_tokens: 15119, + completion_tokens: 3, + total_tokens: 15122, + prompt_tokens_details: { cached_tokens: 15096, cache_write_tokens: 23 }, + }) + // all of it from the cache: no guess added + turnEnded = pb().varint(1, 900).varint(2, 3).varint(3, 900).done() + ;({ usage } = await ask(auth, turn("x"), { session: "s" })) + expect(usage.prompt_tokens).toBe(900) + expect(usage.prompt_tokens_details).toEqual({ cached_tokens: 900, cache_write_tokens: 0 }) + // Cursor counted nothing: the prompt is guessed, as before + turnEnded = pb().varint(2, 3).done() + ;({ usage } = await ask(auth, turn("x".repeat(400)), { session: "s" })) + expect(usage.prompt_tokens).toBeGreaterThan(90) + expect(usage.prompt_tokens_details).toEqual({ cached_tokens: 0, cache_write_tokens: 0 }) +}) diff --git a/packages/cursor/index.mjs b/packages/cursor/index.mjs index d480836..7b19f9e 100644 --- a/packages/cursor/index.mjs +++ b/packages/cursor/index.mjs @@ -1020,10 +1020,72 @@ function toolDef(t) { const env = () => pb().str(1, GOOS).str(2, tmpdir()).str(10, "UTC") +// SESSION carries the session magpie (or OpenCode) names a request's +// conversation by, from the chat.headers hook to the loader's fetch. It +// goes no further: nothing of the request's headers is sent to Cursor. +const SESSION = "x-magpie-cursor-session" + +// sessionOf is the session a chat.headers hook is told, "" when it names +// none. magpie, with no session header from the agent, makes one of the +// conversation's first user message ("magpie-" and 24 hex digits): that +// names no session, and is taken as none, as the built-in's +// nativeSessionOf takes no such header as none. +function sessionOf(input) { + const s = String(input?.sessionID ?? "").trim() + if (!s || /^magpie-[0-9a-f]{24}$/.test(s)) return "" + return s.slice(0, 128) +} + +// uuidOf is a version 4 UUID made of a hash's first 16 bytes. +function uuidOf(b) { + b = Buffer.from(b.subarray(0, 16)) + b[6] = (b[6] & 0x0f) | 0x40 + b[8] = (b[8] & 0x3f) | 0x80 + const h = b.toString("hex") + return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}` +} + +// conversationID is the AgentRunRequest's conversation_id for a +// conversation, as the built-in's cursorConversation makes it (magpie +// #498): the same on every request of it, so that Cursor's backend keeps +// sending it to the machine that has its prompt cached — Grok on Cursor +// caches by machine. Cursor's own client keeps one conversationId per +// agent session, so it is made from what names the session — the +// client's prompt_cache_key (Codex's thread id), else the session magpie +// or OpenCode names — together with the conversation's first user +// message, which every later request repeats: subagents running at once +// under one session (Claude Code's Task agents share its session id) are +// separate conversations to Cursor, as they are to its own client. With +// nothing naming the session it is "", and each Run gets a new id as +// before: a first message alone ("hi") would put strangers' conversations +// under one id. +function conversationID(chat, session) { + const key = (typeof chat?.prompt_cache_key === "string" ? chat.prompt_cache_key.trim() : "") || session || "" + if (!key) return "" + const msgs = Array.isArray(chat?.messages) ? chat.messages : [] + const first = msgs.find((m) => m?.role === "user") ?? msgs[0] + const sum = createHash("sha256") + .update("cursor conversation\0" + key + "\0" + (first === undefined ? "" : JSON.stringify(first))) + .digest() + return uuidOf(sum) +} + +// usageOf is a TurnEndedUpdate as magpie counts usage, as the built-in's +// cursorUsage has it (magpie #498). Its input_tokens is the whole prompt, +// what was read from the cache and written to it included, as Cursor's +// own client has it (it takes both out to get the prompt's uncached +// rest); input is that rest, the cache added back for prompt_tokens. Its +// reasoning_tokens is kept as reasoning. +function usageOf(uf) { + const [inp, cr, cw] = [pbNum(uf, 1), pbNum(uf, 3), pbNum(uf, 4)] + return { input: Math.max(inp - cr - cw, 0), output: pbNum(uf, 2), cacheRead: cr, cacheWrite: cw, reasoning: pbNum(uf, 5) } +} + // buildRun is the Run's first message, an AgentClientMessage with its // run_request, and the blobs it names. The conversation state is the // messages and one turn, which the server wants there to sample at all. -function buildRun(msgs, lastUser, tools, model) { +// conv is the conversation_id (conversationID), a new one when "". +function buildRun(msgs, lastUser, tools, model, conv = "") { const blobs = new Map() const put = (b) => { const id = createHash("sha256").update(b).digest() @@ -1049,7 +1111,7 @@ function buildRun(msgs, lastUser, tools, model) { .bytes(2, action) .bytes(3, pb().str(1, model).str(3, model).str(4, model)) .bytes(4, mcp) - .str(5, randomUUID()) + .str(5, conv || randomUUID()) .bytes(9, pb().str(1, model)) .varint(19, 1) // inline images return { first: pb().bytes(1, rr).done(), blobs } @@ -1117,8 +1179,8 @@ function open(base, headers, signal) { // 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, signal }) { - const { first, blobs } = buildRun(conv.msgs, conv.last, tools, id) +async function runOnce({ tok, base, id, tools, conv, convID, signal }) { + const { first, blobs } = buildRun(conv.msgs, conv.last, tools, id, convID) const o = await open( base, { @@ -1191,10 +1253,12 @@ async function* decode(stream, { send, blobs, tools, estimate }) { let calls = 0 let listed = 0 let said = 0 - let usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } + let usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, reasoning: 0 } const finish = () => { if (!usage.output) usage.output = Math.floor((said + 3) / 4) - if (!usage.input) usage.input = estimate + // a guess only when Cursor counted nothing: a prompt read whole from + // the cache leaves no uncached rest, and is no reason to guess + if (!usage.input && !usage.cacheRead && !usage.cacheWrite) usage.input = estimate const prompt = usage.input + usage.cacheRead + usage.cacheWrite return { stop: calls > 0 ? "tool_calls" : "stop", @@ -1203,6 +1267,7 @@ async function* decode(stream, { send, blobs, tools, estimate }) { completion_tokens: usage.output, total_tokens: prompt + usage.output, prompt_tokens_details: { cached_tokens: usage.cacheRead, cache_write_tokens: usage.cacheWrite }, + ...(usage.reasoning ? { completion_tokens_details: { reasoning_tokens: usage.reasoning } } : {}), }, } } @@ -1241,7 +1306,7 @@ async function* decode(stream, { send, blobs, tools, estimate }) { break } case 14: // turn ended, with what it used - usage = { input: pbNum(uf, 1), output: pbNum(uf, 2), cacheRead: pbNum(uf, 3), cacheWrite: pbNum(uf, 4) } + usage = usageOf(uf) if (calls === 0) { yield finish() return @@ -1371,11 +1436,11 @@ function kept(res) { } // answer runs a chat completion on Cursor, the account kept (errorResponse). -const answer = async (auth, chat, signal) => kept(await answerOf(auth, chat, signal)) +const answer = async (auth, chat, signal, session) => kept(await answerOf(auth, chat, signal, session)) // answerOf runs a chat completion on Cursor and answers it as one, streamed // or not. -async function answerOf(auth, chat, signal) { +async function answerOf(auth, chat, signal, session = "") { let tok try { tok = await tokenOf(auth) @@ -1393,13 +1458,14 @@ async function answerOf(auth, chat, signal) { if (id === "auto") id = "default" // Cursor's pick, which its API calls default const tools = toolsOf(chat) const conv = conversation(chat, tools) + const convID = conversationID(chat, session) const base = await agentURL(tok, false) - let r = await runOnce({ tok, base, id, tools, conv, signal }) + let r = await runOnce({ tok, base, id, tools, conv, convID, signal }) 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 const fresh = await agentURL(tok, true) - if (fresh !== base) r = await runOnce({ tok, base: fresh, id, tools, conv, signal }) + if (fresh !== base) r = await runOnce({ tok, base: fresh, id, tools, conv, convID, signal }) } if (r.error) return errorResponse(r.error) const it = r.events @@ -1480,7 +1546,8 @@ export async function CursorAuthPlugin() { } catch { return errorResponse({ status: 400, message: "a request that isn't JSON" }) } - return answer((await getAuth()) ?? auth, chat, init.signal ?? (input instanceof Request ? input.signal : undefined)) + const session = new Headers(init.headers ?? (input instanceof Request ? input.headers : undefined)).get(SESSION) ?? "" + return answer((await getAuth()) ?? auth, chat, init.signal ?? (input instanceof Request ? input.signal : undefined), session) }, } }, @@ -1503,6 +1570,15 @@ export async function CursorAuthPlugin() { return { ...u, ...(plan ? { plan } : {}), signIn: "kept" } }, }, + // the session the request is part of, for the conversation_id + // (conversationID): magpie and OpenCode name it here, and the loader's + // fetch reads it back. Every plugin's hook sees every provider's + // requests, so it is put on Cursor's alone. + async "chat.headers"(input, output) { + if (input?.model?.providerID !== ID && input?.provider?.info?.id !== ID) return + const s = sessionOf(input) + if (s) output.headers[SESSION] = s + }, async config(config) { config.provider ??= {} const was = config.provider[ID] ?? {} @@ -1533,4 +1609,4 @@ export async function CursorAuthPlugin() { } // for tests -export const _internal = { errorResponse, kept, poolBase, splitID, families, byEffort, offered, modelID, conversation, buildRun, decode, exec, fields, pb, pbValue, pbAny, frame, frames, failure, toolsOf, expiry } +export const _internal = { conversationID, usageOf, sessionOf, SESSION, errorResponse, kept, poolBase, splitID, families, byEffort, offered, modelID, 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 aeb7f0f..eb19547 100644 --- a/packages/cursor/package.json +++ b/packages/cursor/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-cursor-auth", - "version": "0.1.5", + "version": "0.1.6", "description": "Cursor subscriptions (Pro, Pro+, Ultra, Teams) in OpenCode and magpie, through the API cursor-agent talks to", "type": "module", "main": "./index.mjs",