cursor 0.2.27: a chat request no longer waits for a model list Cursor can't give
ysm119 on Discord: claude-opus-5-5 through the plugin takes 33-36 s to its first token on every request. A chat request picks its variant from the account's model list (AvailableModels, up to 30 s) before it opens its Run. A list Cursor couldn't give was never kept, so every request asked for it again and waited for the ask to fail before its Run; a list past its 10 minutes was waited for again too, and requests at once each asked. listFor now gives the chat path the list without waiting when it needn't: a list past its keep is used while a new one is asked for in the background, requests at once share one ask (listing), and after a failed ask requests go without the list for 5 minutes (LIST_RETRY), as the first one did. Only a token with no list and no recent failure waits. provider.models still fails when Cursor can't list, so magpie keeps its list. Measured against a fake Cursor (bun 1.4.2, on mote): with AvailableModels failing after 3 s, every request's setup was 3003 ms before, re-asked each time; the plugin's own setup is ~20 ms cold, ~4 ms warm, and stream chunks reach the client 0-7 ms after the server writes them. Run: bun test packages/cursor (314 pass, 0 fail) and bun scripts/check.mjs cursor (ok), on mote. Broken by hand: on the old index.mjs all three listwait.test.mjs tests are red; with only answerOf back on usable(), the failed-list and stale- list tests are red. Not tried: a real Cursor account (its token is in the Keychain); whether ysm119's AvailableModels fails or is slow is not confirmed.
This commit is contained in:
@@ -227,6 +227,11 @@ minutes), the way pi-cursor-sdk lists Cursor's catalog:
|
||||
and `service_tier` counting as for a listed model. The list doesn't show
|
||||
these ids: pick the `@<size>` model for a window that is the model's.
|
||||
|
||||
A chat request picks its variant from the same list without waiting for it
|
||||
when it needn't: a list past its 10 minutes is used while a new one is
|
||||
asked for, requests at once share one ask, and after an ask fails requests
|
||||
go without the list for 5 minutes instead of each waiting for it again.
|
||||
|
||||
## Usage
|
||||
|
||||
magpie shows Cursor Models, Other Models and Total for the billing period.
|
||||
|
||||
+58
-17
@@ -981,22 +981,66 @@ function fitEffort(want, levels) {
|
||||
// can't give is a failure: magpie keeps the list it had. A usable list it
|
||||
// can't give leaves the picker as it is.
|
||||
const lists = new Map()
|
||||
// listings are the lists being asked for now, by token: callers at once
|
||||
// share one ask; listFailed when a token's last ask failed
|
||||
const listings = new Map()
|
||||
const listFailed = new Map()
|
||||
async function usable(tok) {
|
||||
const h = createHash("sha256").update(tok).digest("hex")
|
||||
const had = lists.get(h)
|
||||
if (had && Date.now() - had.at < MODELS_KEEP) return had.raw
|
||||
const [j, listed] = await Promise.all([
|
||||
unary(API, "aiserver.v1.AiService/AvailableModels", tok, { useModelParameters: true, doNotUseMarkdown: true }, 30_000),
|
||||
unary(API, "agent.v1.AgentService/GetUsableModels", tok, {}, 8_000).then(
|
||||
(u) => (Array.isArray(u?.models) ? u.models : []),
|
||||
() => [],
|
||||
),
|
||||
])
|
||||
const ids = new Set(listed.flatMap((m) => [m?.modelId, m?.displayModelId]).filter(Boolean))
|
||||
const raw = modelsOf(Array.isArray(j?.models) ? j.models : [], ids.size ? ids : null, listed)
|
||||
if (!raw.length) throw new Error("Cursor listed no models")
|
||||
lists.set(h, { at: Date.now(), raw })
|
||||
return raw
|
||||
return listing(tok, h)
|
||||
}
|
||||
function listing(tok, h) {
|
||||
let p = listings.get(h)
|
||||
if (p) return p
|
||||
p = (async () => {
|
||||
const [j, listed] = await Promise.all([
|
||||
unary(API, "aiserver.v1.AiService/AvailableModels", tok, { useModelParameters: true, doNotUseMarkdown: true }, 30_000),
|
||||
unary(API, "agent.v1.AgentService/GetUsableModels", tok, {}, 8_000).then(
|
||||
(u) => (Array.isArray(u?.models) ? u.models : []),
|
||||
() => [],
|
||||
),
|
||||
])
|
||||
const ids = new Set(listed.flatMap((m) => [m?.modelId, m?.displayModelId]).filter(Boolean))
|
||||
const raw = modelsOf(Array.isArray(j?.models) ? j.models : [], ids.size ? ids : null, listed)
|
||||
if (!raw.length) throw new Error("Cursor listed no models")
|
||||
lists.set(h, { at: Date.now(), raw })
|
||||
listFailed.delete(h)
|
||||
return raw
|
||||
})()
|
||||
.catch((e) => {
|
||||
listFailed.set(h, Date.now())
|
||||
throw e
|
||||
})
|
||||
.finally(() => listings.delete(h))
|
||||
listings.set(h, p)
|
||||
return p
|
||||
}
|
||||
|
||||
// LIST_RETRY is how long a request goes on without the list after Cursor
|
||||
// couldn't give it, before it waits for an ask again.
|
||||
const LIST_RETRY = 5 * 60_000
|
||||
|
||||
// listFor is the list a chat request picks its variant from. It is asked
|
||||
// before the Run, so a request never waits on it when it needn't: a list
|
||||
// past MODELS_KEEP is used as it is while a new one is asked for, and
|
||||
// after a failed ask the requests go without one for LIST_RETRY, as the
|
||||
// failed ask left them, instead of each waiting up to AvailableModels'
|
||||
// 30 s again before its Run (ysm119 on Discord: 33–36 s to the first
|
||||
// token on every Opus request). Only a token with no list at all, and no
|
||||
// failure lately, waits for it.
|
||||
async function listFor(tok) {
|
||||
const h = createHash("sha256").update(tok).digest("hex")
|
||||
const had = lists.get(h)
|
||||
if (had && Date.now() - had.at < MODELS_KEEP) return had.raw
|
||||
if (had) {
|
||||
listing(tok, h).catch(() => {})
|
||||
return had.raw
|
||||
}
|
||||
const failed = listFailed.get(h)
|
||||
if (failed && Date.now() - failed < LIST_RETRY) return []
|
||||
return listing(tok, h).catch(() => [])
|
||||
}
|
||||
|
||||
// named is the model and variant an id the list doesn't have stands for,
|
||||
@@ -2872,10 +2916,7 @@ async function answerOf(auth, chat, signal, session = "") {
|
||||
if (prepared.owner) r = prepared.owner.resume({ ...prepared, estimate: conversation(chat, tools).estimate }, signal)
|
||||
const model = String(chat.model ?? "")
|
||||
if (!r) {
|
||||
let raw = []
|
||||
try {
|
||||
raw = await usable(tok)
|
||||
} catch {}
|
||||
const raw = await listFor(tok)
|
||||
// fast only when asked: a service_tier of priority or fast is on; any
|
||||
// other tier, or none, is off, unless the id is a fast one of Cursor's own
|
||||
const tier = chat.service_tier
|
||||
@@ -3106,4 +3147,4 @@ export async function CursorAuthPlugin() {
|
||||
}
|
||||
|
||||
// for tests
|
||||
export const _internal = { 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 = { 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 }
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
// A chat request picks its variant from the account's model list, asked
|
||||
// before its Run. A list Cursor couldn't give was asked again by every
|
||||
// request, each waiting up to AvailableModels' 30 s before its Run, and a
|
||||
// list past its keep was waited for again (ysm119 on Discord: 33–36 s to
|
||||
// the first token on every Opus request). Against a fake Cursor: its API
|
||||
// by a stand-in fetch, its agent API by an HTTP/2 server here.
|
||||
import "./nonet.mjs" // first: no request leaves this machine
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, expect, test } from "bun:test"
|
||||
import { createHash } from "node:crypto"
|
||||
import http2 from "node:http2"
|
||||
import { CursorAuthPlugin, _internal } from "./index.mjs"
|
||||
import { NATIVE_LIMITS, nativeSessions } from "./native-session.mjs"
|
||||
|
||||
const { pb, frame, lists } = _internal
|
||||
const real = globalThis.fetch
|
||||
const retained = NATIVE_LIMITS.perProcess
|
||||
let server, base
|
||||
const events = [] // what happened, in order
|
||||
beforeAll(async () => {
|
||||
server = http2.createServer()
|
||||
server.on("stream", (stream) => {
|
||||
events.push("run")
|
||||
stream.respond({ ":status": 200, "content-type": "application/connect+proto" })
|
||||
let buf = Buffer.alloc(0)
|
||||
let started = false
|
||||
stream.on("data", (c) => {
|
||||
buf = Buffer.concat([buf, c])
|
||||
if (started || buf.length < 5 || buf.length < 5 + buf.readUInt32BE(1)) return
|
||||
started = true
|
||||
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, pb().varint(1, 100).varint(2, 1).done()))
|
||||
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())
|
||||
beforeEach(async () => {
|
||||
await nativeSessions.clear()
|
||||
NATIVE_LIMITS.perProcess = 0
|
||||
events.length = 0
|
||||
})
|
||||
afterEach(() => {
|
||||
NATIVE_LIMITS.perProcess = retained
|
||||
globalThis.fetch = real
|
||||
})
|
||||
|
||||
// Cursor's API; the picker answers (ok) or fails, after ms
|
||||
const PICKER = [{ name: "claude-opus-5-5", clientDisplayName: "Claude Opus 5.5", supportsNonMaxMode: true, contextTokenLimit: 300000 }]
|
||||
function fakeAPI(picker) {
|
||||
globalThis.fetch = async (url) => {
|
||||
const u = String(url)
|
||||
if (u.endsWith("/GetServerConfig")) return Response.json({ agentUrlConfig: { agentUrl: base } })
|
||||
if (u.endsWith("/GetUsableModels")) return Response.json({ models: [] })
|
||||
if (u.endsWith("/AvailableModels")) {
|
||||
events.push("list asked")
|
||||
await new Promise((r) => setTimeout(r, picker.ms))
|
||||
events.push("list answered")
|
||||
return picker.ok ? Response.json({ models: PICKER }) : new Response("down", { status: 503 })
|
||||
}
|
||||
if (u.endsWith("/GetFilteredUsageEvents")) return Response.json({ usageEventsDisplay: [] })
|
||||
throw new Error("the test asked " + u)
|
||||
}
|
||||
}
|
||||
|
||||
let n = 0
|
||||
const signIn = () => {
|
||||
const jwt = ["e30", Buffer.from(JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 7200 + ++n })).toString("base64url"), "sig"].join(".")
|
||||
return { type: "oauth", access: jwt, refresh: "", expires: 0, accountId: "a@b.c" }
|
||||
}
|
||||
|
||||
async function ask(auth) {
|
||||
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: "claude-opus-5-5", messages: [{ role: "user", content: "hi" }] }) })
|
||||
expect(res.status).toBe(200)
|
||||
return res.json()
|
||||
}
|
||||
|
||||
test("a list Cursor couldn't give is not waited for again by every request", async () => {
|
||||
fakeAPI({ ok: false, ms: 50 })
|
||||
const auth = signIn()
|
||||
for (let i = 0; i < 3; i++) await ask(auth)
|
||||
// the first request waited for the failed ask; the ones after it went
|
||||
// straight to their Runs
|
||||
expect(events).toEqual(["list asked", "list answered", "run", "run", "run"])
|
||||
})
|
||||
|
||||
test("a list past its keep is used while a new one is asked for", async () => {
|
||||
fakeAPI({ ok: true, ms: 50 })
|
||||
const auth = signIn()
|
||||
await ask(auth)
|
||||
expect(events).toEqual(["list asked", "list answered", "run"])
|
||||
// ten minutes on
|
||||
const h = createHash("sha256").update(auth.access).digest("hex")
|
||||
lists.get(h).at -= 11 * 60_000
|
||||
events.length = 0
|
||||
fakeAPI({ ok: true, ms: 300 })
|
||||
await ask(auth)
|
||||
// the Run went with the list it had, before the new one came
|
||||
expect(events.indexOf("run")).toBeLessThan(events.indexOf("list answered") === -1 ? Infinity : events.indexOf("list answered"))
|
||||
for (let i = 0; i < 100 && !events.includes("list answered"); i++) await new Promise((r) => setTimeout(r, 10))
|
||||
expect(events).toEqual(["list asked", "run", "list answered"])
|
||||
// and the new list is kept
|
||||
expect(Date.now() - lists.get(h).at).toBeLessThan(60_000)
|
||||
})
|
||||
|
||||
test("requests at once with no list share one ask", async () => {
|
||||
fakeAPI({ ok: true, ms: 100 })
|
||||
const auth = signIn()
|
||||
await Promise.all([ask(auth), ask(auth), ask(auth)])
|
||||
expect(events.filter((e) => e === "list asked")).toHaveLength(1)
|
||||
})
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-cursor-auth",
|
||||
"version": "0.2.26",
|
||||
"version": "0.2.27",
|
||||
"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