// Cursor subscriptions as an OpenCode provider plugin, served through the // API cursor-agent talks to. Ported from magpie's built-in Cursor account // (internal/provider/cursor*.go, internal/gateway/cursor.go). // // An account is a Cursor access token, got one of three ways: // - the sign-in cursor-agent does (cursor.com/loginDeepControl with a PKCE // challenge, then /auth/poll until the browser has signed in); // - the token cursor-agent itself keeps (the Mac keychain, else its // auth.json), read each time and never written; // - a Cursor API key, exchanged for a token as the CLI does with // 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 // a conversation, the caller's system prompt at its head; the Run only // resumes it. The caller's tools are MCP tools, which the model calls // through Cursor's CallDynamicTool: the server hands each call to the // client to run, and once it has said how many a step made, the calls // go back to OpenCode. When the owner is available their results continue // that Run; otherwise the caller's history starts a stateless Run. Nothing // else the server asks the client to run (a shell, a file read) is run. // // OpenCode speaks chat completions to it (@ai-sdk/openai-compatible); the // fetch here answers them. import { NATIVE_LIMITS, nativeSessions, NativeSessionError, nativeFields, nativeMcpArgs, pendingCalls, Quiet, setWebSearch, setWireTrace, StepCalls, webSearchAnswer, webSearchDir, webSearchQuery } from "./native-session.mjs" import { isDeepStrictEqual } from "node:util" 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, writeFile, mkdir, rename } from "node:fs/promises" import { homedir, platform, tmpdir } from "node:os" import { basename, dirname, join } from "node:path" const ID = "cursor" const API = "https://api2.cursor.sh" const WEBSITE = "https://cursor.com" const AGENT = "https://agentn.global.api5.cursor.sh" // when the server config can't say const CHAT = "@ai-sdk/openai-compatible" const VERSION_FALLBACK = "2026.09.23-86fc751" // the CLI version said when no install names one const DEFAULT_CONTEXT = 200_000 // a model Cursor gives no limit for const MODELS_KEEP = 10 * 60 * 1000 const CALL = "CallDynamicTool" // how the model calls an MCP tool const NO_RESULT = "Tool use was interrupted and did not produce a result." const CLI_MARK = "cursor-agent" // an oauth sign-in's refresh when the token is cursor-agent's own const GOOS = { win32: "windows" }[platform()] ?? platform() const EMPTY = Buffer.alloc(0) const enc = new TextEncoder() // ---- cursor-agent --------------------------------------------------------------- const exists = (p) => stat(p).then((s) => !s.isDirectory(), () => false) function run(file, args, { timeout = 10_000, env } = {}) { return new Promise((resolve) => { execFile(file, args, { timeout, env: env ?? process.env, maxBuffer: 8 << 20 }, (err, stdout) => resolve({ ok: !err, out: String(stdout ?? ""), code: typeof err?.code === "number" ? err.code : err ? -1 : 0 })) }) } // cursorExecutable finds the cursor-agent CLI, or Cursor's `agent` by that // name. async function cursorExecutable() { const dirs = (process.env.PATH ?? "").split(GOOS === "windows" ? ";" : ":").filter(Boolean) for (const name of ["cursor-agent", "agent"]) { for (const d of dirs) { const p = join(d, GOOS === "windows" ? name + ".exe" : name) if (!(await exists(p))) continue if (name === "cursor-agent") return p if ((await realpath(p).catch(() => "")).includes("cursor-agent")) return p } } const home = homedir() for (const p of [join(home, ".local", "bin", "cursor-agent"), "/usr/local/bin/cursor-agent", "/opt/homebrew/bin/cursor-agent"]) if (await exists(p)) return p return "" } const VERSION_RE = /^\d{4}\.\d{2}\.\d{2}-[0-9a-f]+$/ // clientVersion is the cursor-agent the API is told it is talking to, // "cli-": the installed one, as the API turns away a version it no // longer supports. let versionSaid = "" async function clientVersion() { if (versionSaid) return versionSaid let v = "" const exe = await cursorExecutable() if (exe) { const d = basename(dirname(await realpath(exe).catch(() => exe))) if (VERSION_RE.test(d)) v = d } if (!v) { const dirs = [join(homedir(), ".local", "share", "cursor-agent", "versions")] if (GOOS === "windows") dirs.push(join(process.env.LOCALAPPDATA ?? "", "cursor-agent", "versions")) for (const dir of dirs) for (const n of await readdir(dir).catch(() => [])) if (VERSION_RE.test(n) && n > v) v = n } versionSaid = "cli-" + (v || VERSION_FALLBACK) return versionSaid } // authFile is where cursor-agent keeps its sign-in off a Mac's keychain. function authFile() { const home = homedir() if (GOOS === "windows") return join(process.env.APPDATA || join(home, "AppData", "Roaming"), "Cursor", "auth.json") if (GOOS === "darwin") return join(home, ".cursor", "auth.json") return join(process.env.XDG_CONFIG_HOME || join(home, ".config"), "cursor", "auth.json") } // cliConfigFile is cursor-agent's cli-config.json, where it keeps the team // it signed in to (authInfo.activeTeamId); its directory found as the CLI // finds it, on every OS. function cliConfigFile() { const dir = process.env.CURSOR_CONFIG_DIR?.trim() || (process.env.XDG_CONFIG_HOME?.trim() ? join(process.env.XDG_CONFIG_HOME, "cursor") : join(homedir(), ".cursor")) return join(dir, "cli-config.json") } // tokenSub is a JWT's subject (the auth id, "auth0|user_…"); "" when it // doesn't say. function tokenSub(tok) { const parts = String(tok ?? "").split(".") if (parts.length !== 3) return "" try { const sub = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"))?.sub return typeof sub === "string" ? sub : "" } catch { return "" } } const teamOf = (v) => (Number.isSafeInteger(v) && v > 0 ? v : undefined) // activeTeamId is the team a request is billed to, as cursor-agent sends it // (x-cursor-team-id): cli-config.json's authInfo.activeTeamId. Without it // Cursor takes the token's default team, which in an organization may be one // with on-demand spend turned off ("Team budget limit reached"). The config's // team is only taken for the account cursor-agent signed in to: a token // whose subject isn't its authInfo.authId, or a config with none, gets none. // Read again after 10 s; cursor-agent rewrites the file in place, so a read // that fails to parse keeps the last one, and only a missing file clears it. const TEAM_TTL = 10_000 const teamRead = { at: 0, info: null } async function activeTeamId(tok) { if (Date.now() - teamRead.at >= TEAM_TTL) { try { teamRead.info = JSON.parse(await readFile(cliConfigFile(), "utf8"))?.authInfo ?? null } catch (e) { if (e?.code === "ENOENT") teamRead.info = null } teamRead.at = Date.now() } const info = teamRead.info if (!info) return undefined if (!info.authId || info.authId !== tokenSub(tok)) return undefined return teamOf(info.activeTeamId) } // teamHeader names that team in a request's headers, and teamBody in // GetFilteredUsageEvents' body; neither says anything when there is none. // GetHardLimit and GetCurrentPeriodUsage go out with "{}", as cursor-agent // sends them: the team rides in the header only. async function teamHeader(tok) { const id = await activeTeamId(tok) return id ? { "x-cursor-team-id": String(id) } : {} } async function teamBody(tok) { const id = await activeTeamId(tok) return id ? { teamId: id } : {} } // TOKEN_TTL is how long a token read from the Keychain is taken as it: a // sign-in reads it afresh, one made in cursor-agent is seen within it. // KEYCHAIN_DENIED is how long a read the user may have been asked about, // and answered no to, is not asked again: with the item's trust list // holding no `security`, every ask can show the dialog again. Both as the // built-in's cursorKeychainToken (magpie #746, #2408). const TOKEN_TTL = 10_000 const KEYCHAIN_DENIED = 10 * 60_000 const keychain = { tok: "", at: 0, ask: 0, busy: null, now: () => Date.now(), read: (args) => run("security", args) } // keychainToken is cursor-agent's token in the Keychain, "" for none; fresh // reads it whatever was read last. Reads go one at a time, so callers at // once share one `security` run (and one dialog). function keychainToken(fresh = false) { const go = async () => { const now = keychain.now() const ttl = !keychain.tok && now - keychain.ask < KEYCHAIN_DENIED ? KEYCHAIN_DENIED : TOKEN_TTL if (!fresh && now - keychain.at < ttl) return keychain.tok const r = await keychain.read(["find-generic-password", "-s", "cursor-access-token", "-a", "cursor-user", "-w"]) keychain.tok = "" keychain.at = keychain.now() if (r.ok) { keychain.tok = r.out.trim() keychain.ask = 0 } else if (r.code !== 44) { // 44 is "no such item"; anything else may have been a dialog the // user said no to, or a keychain that refused keychain.ask = keychain.at } else keychain.ask = 0 return keychain.tok } const p = (keychain.busy ?? Promise.resolve()).then(go, go) keychain.busy = p.catch(() => {}) return p } // cliToken is the access token cursor-agent signed in with; read, never // written. fresh reads the Keychain whatever was read last. async function cliToken(fresh = false) { if (GOOS === "darwin") { const t = await keychainToken(fresh) if (t) return t } try { return JSON.parse(await readFile(authFile(), "utf8"))?.accessToken ?? "" } catch { return "" } } // expiry is when a JWT runs out, in ms; 0 when it doesn't say. function expiry(tok) { const parts = String(tok ?? "").split(".") if (parts.length !== 3) return 0 try { const exp = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"))?.exp return typeof exp === "number" && exp > 0 ? exp * 1000 : 0 } catch { return 0 } } const SOON = 5 * 60 * 1000 class AuthError extends Error { constructor(msg) { super(msg) this.status = 401 } } // cliTokenNow is cursor-agent's token; one about to run out is renewed by // cursor-agent, which does that whenever it runs. let cliRefresh = null async function cliTokenNow() { let tok = await cliToken() const exp = expiry(tok) if (tok && (!exp || exp - Date.now() > SOON)) return tok const exe = await cursorExecutable() if (exe) { cliRefresh ??= run(exe, ["status"], { timeout: 30_000 }).finally(() => (cliRefresh = null)) await cliRefresh tok = await cliToken(true) } // the built-in's words (provider.CursorToken) if (!tok) throw new AuthError("Cursor isn't signed in; sign in from magpie's Providers page or run `cursor-agent login`") const e = expiry(tok) if (e && e <= Date.now()) throw new AuthError("Cursor's sign-in has run out; sign in again from magpie's Providers page or run `cursor-agent login`") return tok } // ---- the account ----------------------------------------------------------------- async function headersFor(tok) { return { "Content-Type": "application/json", "Connect-Protocol-Version": "1", ...(tok ? { Authorization: `Bearer ${tok}` } : {}), "x-cursor-client-version": await clientVersion(), "x-cursor-client-type": "cli", "x-ghost-mode": "true", ...await teamHeader(tok), } } // unary is a Connect call in JSON. async function unary(base, path, tok, body = {}, timeout = 15_000) { const res = await fetch(base + "/" + path, { method: "POST", headers: await headersFor(tok), body: JSON.stringify(body), signal: AbortSignal.timeout(timeout), }) const text = await res.text() if (!res.ok) { const f = failure(res.status, text) const e = new Error(f.message) e.status = f.status throw e } return JSON.parse(text || "{}") } // whoIs is the account's email and plan, as `cursor-agent about` says them. async function whoIs(tok) { const [me, plan] = await Promise.allSettled([ unary(API, "aiserver.v1.DashboardService/GetMe", tok), unary(API, "aiserver.v1.DashboardService/GetPlanInfo", tok), ]) return { email: me.status === "fulfilled" ? String(me.value?.email ?? "").trim() : "", plan: plan.status === "fulfilled" ? String(plan.value?.planInfo?.planName ?? "").trim() : "", } } // plans are the plan each token's account is on, as `cursor-agent about` // names it (GetPlanInfo's planName, magpie's card title), asked again after // an hour. merged is GetPlanInfo's isMerged: a plan of Cursor's merged // (xAI) billing, whose included usage is one allowance for every model, // most of them a week long (includedUsagePeriod), and has no Other Models // pool (majiang_ai on X). The dashboard's usage page shows such a plan one // meter, the period's totalPercentUsed. period is "weekly", "monthly" or // "" (not said). A reply that couldn't be read keeps the last one, else // says nothing: undefined merged, which the pools are kept for. const plans = new Map() const PLAN_TTL = 3600_000 const PERIODS = { INCLUDED_USAGE_PERIOD_WEEKLY: "weekly", INCLUDED_USAGE_PERIOD_MONTHLY: "monthly", 1: "monthly", 2: "weekly" } async function planOf(tok) { const had = plans.get(tok) if (had && Date.now() - had.at < PLAN_TTL) return had try { const info = await unary(API, "aiserver.v1.DashboardService/GetPlanInfo", tok) const plan = String(info?.planInfo?.planName ?? "").trim() const got = { plan: plan || had?.plan || "", merged: info?.isMerged === true, period: PERIODS[info?.planInfo?.includedUsagePeriod] ?? "", at: Date.now() } if (plan || got.merged) plans.set(tok, got) return got } catch { return had ?? { plan: "" } } } // exchanged are API keys' tokens, by the key's hash. const exchanged = new Map() // keyToken is the access token for a Cursor API key, as the CLI gets it // for CURSOR_API_KEY: /auth/exchange_user_api_key, again when it runs out. async function keyToken(key) { const h = createHash("sha256").update(key).digest("hex") const had = exchanged.get(h) if (had && (!had.exp || had.exp - Date.now() > SOON)) return had.tok const res = await fetch(API + "/auth/exchange_user_api_key", { method: "POST", headers: { ...(await headersFor(key)), "Connect-Protocol-Version": undefined }, body: "{}", signal: AbortSignal.timeout(15_000), }).catch((e) => { throw Object.assign(new Error("couldn't reach Cursor's API: " + e.message), { status: 502 }) }) if (res.status >= 500) throw Object.assign(new Error(`exchange_user_api_key: HTTP ${res.status}`), { status: 502 }) const j = res.ok ? await res.json().catch(() => null) : null if (!j?.accessToken) throw new AuthError("Cursor didn't take this API key") exchanged.set(h, { tok: j.accessToken, exp: expiry(j.accessToken) }) return j.accessToken } // tokenOf is the token to call Cursor's API with, for a sign-in. async function tokenOf(auth) { if (auth?.type === "api" && auth.key) return keyToken(auth.key) if (auth?.type !== "oauth") throw new AuthError("Cursor isn't signed in") if (auth.refresh === CLI_MARK) return cliTokenNow() const exp = auth.expires || expiry(auth.access) if (!auth.access) throw new AuthError("Cursor isn't signed in") // Cursor's sign-in has nothing to renew it with: cursor-agent itself // signs in again when it runs out (about two months) if (exp && exp <= Date.now()) throw new AuthError("Cursor's sign-in has run out; sign in to Cursor again") return auth.access } // browserSignIn is cursor-agent's `login`: the page signs in, and // /auth/poll hands the tokens over once it has. async function browserSignIn() { const verifier = randomBytes(32).toString("base64url") const challenge = createHash("sha256").update(verifier).digest("base64url") const uuid = randomUUID() const url = new URL("/loginDeepControl", WEBSITE) url.searchParams.set("challenge", challenge) url.searchParams.set("uuid", uuid) url.searchParams.set("mode", "login") url.searchParams.set("redirectTarget", "cli") return { url: url.toString(), instructions: "Sign in to Cursor in the browser; this finishes by itself.", method: "auto", async callback() { const headers = { "Content-Type": "application/json", "x-cursor-client-version": await clientVersion(), "x-cursor-client-type": "cli" } let errors = 0 for (let r = 0; r < 150; r++) { const wait = Math.min(1000 * 1.2 ** r, 10_000) let res try { res = await fetch(`${API}/auth/poll?uuid=${uuid}&verifier=${verifier}`, { headers, signal: AbortSignal.timeout(15_000) }) } catch { if (++errors >= 3) return { type: "failed", error: "couldn't reach Cursor" } await sleep(wait) continue } if (res.status === 404) { errors = 0 await sleep(wait) continue } if (!res.ok) { if (res.status === 403 || ++errors >= 3) return { type: "failed", error: res.status === 403 ? "Cursor refused the sign-in (403)" : `Cursor's sign-in answered HTTP ${res.status}` } await sleep(wait) continue } const j = await res.json().catch(() => null) if (!j?.accessToken || !("refreshToken" in j)) return { type: "failed", error: "Cursor sent back no token" } const who = await whoIs(j.accessToken) return { type: "success", access: j.accessToken, refresh: j.refreshToken || "none", expires: expiry(j.accessToken) || Date.now() + 30 * 24 * 3600 * 1000, ...(who.email ? { accountId: who.email } : {}), ...(who.plan ? { plan: who.plan } : {}), } } return { type: "failed", error: "the sign-in timed out" } }, } } // cliSignIn takes the account cursor-agent is signed in to; its token is // read each time from where cursor-agent keeps it. async function cliSignIn() { return { url: "", instructions: "Uses the account `cursor-agent login` signed in to.", method: "auto", async callback() { const tok = await cliToken(true) const exp = expiry(tok) if (!tok) return { type: "failed", error: "cursor-agent isn't signed in: run `cursor-agent login`" } if (exp && exp <= Date.now()) return { type: "failed", error: "cursor-agent's sign-in has run out: run `cursor-agent login` again" } const who = await whoIs(tok) if (!who.email) return { type: "failed", error: "Cursor couldn't say which account is signed in" } return { type: "success", access: "", refresh: CLI_MARK, expires: 0, accountId: who.email, ...(who.plan ? { plan: who.plan } : {}) } }, } } const sleep = (ms) => new Promise((r) => setTimeout(r, ms)) // ---- usage ------------------------------------------------------------------------ // // How much of the plan's included usage is gone, as magpie's built-in Cursor // account shows it (internal/provider/cursor_usage.go): the dashboard's // current period, split into the Cursor Models and Other Models pools. // statusText is a refused request's status as magpie says it (Go's // http.StatusText). const statusText = (s) => ({ 413: "Request Entity Too Large", 414: "Request URI Too Long", 416: "Requested Range Not Satisfiable", 418: "I'm a teapot", 509: "" })[s] ?? STATUS_CODES[s] ?? "" const POOL_VARIANT = /-(fast|none|low|medium|high|xhigh|extra-high|max|thinking)$/ // poolBase names a model's family: lower case, without cursor-, the // context size the list adds to it (@300k) and the effort and speed the // CLI adds to it. function poolBase(model) { model = String(model).trim().toLowerCase().replace(/@[^@]*$/, "") if (model.startsWith("cursor-")) model = model.slice("cursor-".length) for (;;) { const b = model.replace(POOL_VARIANT, "") if (b === model) return model model = b } } // Cursor's autoBucketModels can lag model releases: it still omitted Grok // 4.6/4.7 when the published Cursor Models pool already included them. // Keep those documented families alongside the server's exact model list. // See https://cursor.com/docs/models-and-pricing. function firstParty(model) { model = model.replace(/@[^@]*$/, "") if (model.startsWith("cursor-")) model = model.slice("cursor-".length) if (model === "default" || model === "composer" || model.startsWith("composer-")) return true return ["grok-4.5", "grok-4.6", "grok-4.7"].some((b) => model === b || model.startsWith(b + "-")) } // onDemandOf is what Cursor still serves once the included usage is spent, // as cursor-agent's own usage view tells it (its On-demand line): from the // period's spendLimitUsage (cents) and, where that sets no limit of the // user's, GetHardLimit's reply (dollars; undefined when it couldn't be // read). kind is "fixed" (up to limitDollars), "unlimited", "disabled" or // "unavailable" (not known). A team member with no limit of their own // spends the team's pool, which cursor-agent's view calls unlimited but // which runs out at pooledLimit for the whole team (magpie #1868): that is // a fixed limit on the pool's spend, with the member's own in mineDollars. function onDemandOf(data, hard) { const s = data?.spendLimitUsage const usedDollars = Number(s?.individualUsed ?? 0) / 100 const own = s?.individualLimit === undefined ? undefined : Number(s.individualLimit) > 0 ? { kind: "fixed", usedDollars, limitDollars: Number(s.individualLimit) / 100 } : { kind: "disabled", usedDollars } if (s?.limitType === "team") { if (own) return own if (hard && (hard.noUsageBasedAllowed || !(Number(hard.hardLimit) > 0))) return { kind: "disabled", usedDollars } // pooledLimit and pooledRemaining come as int64 strings, pooledUsed as a number const pool = Number(s.pooledLimit ?? 0) if (pool > 0) return { kind: "fixed", usedDollars: Number(s.pooledUsed ?? 0) / 100, limitDollars: pool / 100, mineDollars: usedDollars } return hard ? { kind: "unlimited", usedDollars } : { kind: "unavailable", usedDollars } } if (!hard) return own ?? { kind: "unavailable", usedDollars } if (hard.noUsageBasedAllowed) return { kind: "disabled", usedDollars } const limit = Number(hard.hardLimit ?? 0) if (limit >= 2147483647) return { kind: "unlimited", usedDollars } return limit > 0 ? { kind: "fixed", usedDollars, limitDollars: limit } : { kind: "disabled", usedDollars } } // hardLimit is GetHardLimit's reply, undefined when it couldn't be read. async function hardLimit(tok) { try { const res = await fetch(API + "/aiserver.v1.DashboardService/GetHardLimit", { method: "POST", headers: { Authorization: `Bearer ${tok}`, "Content-Type": "application/json", "Connect-Protocol-Version": "1", ...await teamHeader(tok) }, body: "{}", signal: AbortSignal.timeout(15_000), }) return res.ok ? ((await res.json()) ?? undefined) : undefined } catch { return undefined } } // dollars, thousands grouped: a team's pool runs to six figures ($451,200.00) const dollars = (n) => "$" + n.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 }) // ---- free credit ------------------------------------------------------------------ // // Cursor gives free usage two ways (CryptoSarom on X, "赠金"), as Cursor // 3.x's own client reads them: // // - the plan's bonus, "+$X free usage on us" under the included usage in // the IDE's usage tooltip: GetCurrentPeriodUsage's planUsage.bonusSpend // (cents spent from it this period), remainingBonus (whether any is // left; no amount is given) and bonusTooltip ("We work with model // providers to give you free usage beyond what you've purchased. Amounts // may vary."). It isn't tied to a model. // - credit grants, the IDE's "Use your $X free … credits" banner: // DashboardService/GetUsageLimitStatusAndActiveGrants' activeGrants, each // with totalCents and remainingCents (int64 strings), expiresAtMs, and // its limits: allowedModelIds, allowedModelTags and allowedModelSelections // (the models it may be spent on; none listed is every model) and // allowedClientTypes (the clients that may spend it; none listed is any; // "glass" without "ide" is the IDE's Cloud Agent credits). magpie talks // as cursor-agent, clientType "cli". // // creditGrants is that reply's activeGrants, [] when it couldn't be read. async function creditGrants(tok) { try { const res = await fetch(API + "/aiserver.v1.DashboardService/GetUsageLimitStatusAndActiveGrants", { method: "POST", headers: { Authorization: `Bearer ${tok}`, "Content-Type": "application/json", "Connect-Protocol-Version": "1", ...await teamHeader(tok) }, body: "{}", signal: AbortSignal.timeout(15_000), }) if (!res.ok) return [] const g = (await res.json())?.activeGrants return Array.isArray(g) ? g : [] } catch { return [] } } // tagOf is a model name as the IDE matches a grant's allowedModelTags to // it: lower case, "-" read as "."; a tag matches a name it is part of. const tagOf = (s) => String(s).toLowerCase().replace(/-/g, ".") // credits are the windows of the account's free credit, and what it lets // Cursor go on serving once the included usage is spent: all (a bonus or // grant magpie can spend on every model still has some left) and covers // (the account's model ids a grant limited to some models still pays // for). Every credit window is shown only: what stops an account is the // included usage it outlasts, which usage() sets aside. plan is // planUsage, resets its period's end, ids the account's model ids. function credits(plan, grants, ids, resets, now = Date.now()) { const windows = [] const covers = new Set() let all = false const bonus = Number(plan?.bonusSpend ?? 0) / 100 if (bonus > 0 || plan?.remainingBonus === true) { windows.push({ name: "Free usage", used: 0, display: `+${dollars(bonus)} on us` + (plan?.remainingBonus === true ? ", more left" : ""), ...resets, aside: true }) if (plan?.remainingBonus === true) all = true } for (const g of grants) { const total = Number(g?.totalCents ?? 0) / 100 const left = Math.max(0, Number(g?.remainingCents ?? 0) / 100) if (!(total > 0) || !Number.isFinite(total) || !Number.isFinite(left)) continue const exp = Number(g.expiresAtMs ?? 0) if (exp > 0 && exp <= now) continue const clients = (g.allowedClientTypes ?? []).map(String) const mine = clients.length === 0 || clients.includes("cli") const named = [...(g.allowedModelIds ?? []), ...(g.allowedModelSelections ?? []).map((m) => m?.modelId).filter(Boolean)].map(String) const tags = (g.allowedModelTags ?? []).map(String) const limited = named.length > 0 || tags.length > 0 const bases = new Set(named.map((m) => (poolBase(m) === "auto" ? "default" : poolBase(m)))) const fits = (id) => { const b = poolBase(id) === "auto" ? "default" : poolBase(id) return bases.has(b) || tags.some((t) => tagOf(id).includes(tagOf(t))) } const matched = limited ? ids.filter(fits) : [] const name = (String(g.campaignName ?? "").trim() || "Free credit") + (mine ? "" : clients.includes("glass") && !clients.includes("ide") ? " (Cloud Agents only)" : ` (${clients.join(", ")} only)`) windows.push({ name, used: Math.max(0, Math.min(100, (100 * (total - left)) / total)), display: `${dollars(total - left)} / ${dollars(total)}`, amount: total - left, limit: total, unit: "USD", ...(exp > 0 ? { runsOutAt: new Date(exp).toISOString(), runsOut: left } : {}), ...(limited ? { models: matched.length ? matched : [...named, ...tags] } : {}), aside: true, }) if (!mine || !(left > 0)) continue if (!limited) all = true else for (const id of matched) covers.add(id) } return { windows, all, covers } } // INCLUDED_ONLY is the switch (magpie's plugin options, off by default) // that keeps an account in routing only while its included usage lasts // (magpie-community/plugins#485): on, the included pools (Cursor Models and // Other Models; an Enterprise account's allowance) are what stops it, and // On-demand and Total are shown only, a budget with room or none at all // keeping nothing in routing. Off, on-demand that can still pay keeps it. const INCLUDED_ONLY = "included_only" // WIRE_TRACE is the switch (magpie's plugin options, off by default) that // saves a failed Run's frames, scrubbed, as a JSON file in cursor-traces in // magpie's folder (plugins#550): see WireTrace for what one holds. const WIRE_TRACE = "wire_trace" // WEB_SEARCH is a test switch (off by default) for plugins#635: on, a Run // lets Cursor's own web search through and approves it when Cursor asks, // and a Run in which Cursor asked to search saves its frames as Wire trace // does, whether it succeeded or failed. Off, Cursor's web search is refused // like its other tools. const WEB_SEARCH = "web_search_test" // allowedTools is x-cursor-agent-allowed-tools: names of ToolCall's oneof // fields. Only the caller's tools (MCP), and Cursor's web search // (web_search_tool_call, 18) under the web-search test switch. function allowedTools(search) { return "mcp_tool_call,get_mcp_tools_tool_call" + (search ? ",web_search_tool_call" : "") } // enterpriseUsage is the allowance GetCurrentPeriodUsage leaves out on an // Enterprise account. That call answers with only the billing cycle there; // the website's usage-summary has individualUsage.overall, in cents, and // the account's membership. The CLI JWT is also the website's dashboard // session, as botUsage builds it. undefined when the summary says nothing // this can show, so a failed read stays an empty card, as before. async function enterpriseUsage(tok, includedOnly = false) { try { const subject = JSON.parse(Buffer.from(tok.split(".")[1], "base64url").toString()).sub if (typeof subject !== "string") return undefined const user = subject.split("|").filter(Boolean).at(-1) if (!user || !/^[a-zA-Z0-9._-]+$/.test(user)) return undefined const res = await fetch(WEBSITE + "/api/usage-summary", { method: "GET", headers: { Accept: "application/json", Origin: WEBSITE, Cookie: "WorkosCursorSessionToken=" + encodeURIComponent(user + "::" + tok), }, redirect: "error", signal: AbortSignal.timeout(15_000), }) if (!res.ok) return undefined const data = await res.json() if (String(data?.membershipType).toLowerCase() !== "enterprise") return undefined const overall = data?.individualUsage?.overall if (overall?.enabled !== true) return undefined const { used, limit } = overall if (typeof used !== "number" || !Number.isFinite(used) || used < 0) return undefined if (typeof limit !== "number" || !Number.isFinite(limit) || limit <= 0) return undefined const end = Date.parse(data.billingCycleEnd ?? "") const resets = Number.isFinite(end) ? { resetsAt: new Date(end).toISOString() } : {} const od = data.teamUsage?.onDemand const spent = typeof od?.used === "number" && Number.isFinite(od.used) && od.used >= 0 const unlimited = od?.enabled === true && od.limit === null const fixed = od?.enabled === true && typeof od.limit === "number" && Number.isFinite(od.limit) && od.limit > 0 && spent // Only an explicitly unlimited budget or a measured budget with room // lets a spent included allowance stay available to magpie's routing, // and neither does with INCLUDED_ONLY on. const aside = !includedOnly && (unlimited || (fixed && od.used < od.limit)) const windows = [{ name: "Enterprise", used: Math.max(0, Math.min(100, (100 * used) / limit)), display: `${dollars(used / 100)} / ${dollars(limit / 100)}`, amount: used / 100, limit: limit / 100, unit: "USD", ...resets, ...(aside ? { aside: true } : {}), }] if (fixed) windows.push({ name: "On-demand", used: Math.min(100, (100 * od.used) / od.limit), display: `${dollars(od.used / 100)} / ${dollars(od.limit / 100)}`, amount: od.used / 100, limit: od.limit / 100, unit: "USD", ...resets, ...(includedOnly ? { aside: true } : {}), }) else if (unlimited && spent) windows.push({ name: "On-demand", used: 0, display: dollars(od.used / 100), ...resets, aside: true }) return windows } catch { return undefined } } // usage is the account's windows this billing period. ids are the models it // can be asked for, each counted by the pool Cursor bills it to. An account // that may spend on-demand once its included usage is gone (fottencity on // Discord: a team that pays for more) is still served when the pools are // spent, so they are shown aside, and its On-demand spend is what can run // out: at its limit (a team member with none of their own: the team's // pool), or never when it has none. With includedOnly (INCLUDED_ONLY on) // the pools are the allowance whatever on-demand allows, and On-demand is // shown only. An Enterprise account's period has no planUsage; its // allowance comes from usage-summary instead. // plan is planOf's answer, asked alongside (a promise): a merged plan's // included usage is one window, Weekly on a weekly plan, for every model. async function usage(tok, ids, includedOnly = false, plan = undefined) { const [res, hard] = await Promise.all([ fetch(API + "/aiserver.v1.DashboardService/GetCurrentPeriodUsage", { method: "POST", headers: { Authorization: `Bearer ${tok}`, "Content-Type": "application/json", "Connect-Protocol-Version": "1", ...await teamHeader(tok) }, body: "{}", signal: AbortSignal.timeout(15_000), }), hardLimit(tok), ]) const grants = creditGrants(tok) if (!res.ok) return { error: statusText(res.status), windows: [] } const data = await res.json() const u = data?.planUsage if (!u) { // Prefer measured Enterprise usage before any reset-date-only fallback. const windows = await enterpriseUsage(tok, includedOnly) return { windows: windows ?? [], credits: credits(undefined, await grants, ids, {}).windows } } const ms = /^[+-]?\d+$/.test(data.billingCycleEnd ?? "") ? Number(data.billingCycleEnd) : 0 const resets = ms > 0 ? { resetsAt: new Date(ms).toISOString() } : {} const bucket = new Set((data.autoBucketModels ?? []).map(poolBase)) const inPool = (model) => { model = poolBase(model) if (model === "auto") model = "default" // the CLI's Auto is default in Cursor's API // the server names a family (grok-4.8); the CLI asks for one at an // effort or speed (grok-4.8-high-fast) return bucket.has(model) || firstParty(model) } // Auto is always one, so the pool's list is never empty (which would // count every model). A model listed at its context sizes (grok-4.7@256k) // is still asked for by its bare name (grok-4.7) where it was picked // before the list had sizes, and runs as its default, so the pool names // that too (Will on Discord) const asked = ids.flatMap((id) => [id, id.replace(/@[^@]*$/, "")]) const pool = [...new Set(["auto", ...asked, ...(data.autoBucketModels ?? [])])].filter(inPool) const num = (v) => (typeof v === "number" ? v : 0) const od = onDemandOf(data, hard) // free credit that magpie can spend on every model keeps the account // served past its included usage, as on-demand that can pay does; one // limited to some models keeps those models served past a spent pool. // Neither does with includedOnly. const free = credits(u, await grants, [...new Set(asked)], resets) const pooled = !includedOnly && (od.kind === "fixed" || od.kind === "unlimited" || free.all) ? { aside: true } : {} const covers = includedOnly ? new Set() : free.covers const onDemand = od.kind === "fixed" ? [{ name: "On-demand", used: Math.max(0, Math.min(100, (100 * od.usedDollars) / od.limitDollars)), display: `${dollars(od.usedDollars)} / ${dollars(od.limitDollars)}` + (od.mineDollars === undefined ? "" : ` (you: ${dollars(od.mineDollars)})`), ...resets, ...(includedOnly || free.all ? { aside: true } : {}) }] : od.kind === "unlimited" ? [{ name: "On-demand", used: 0, display: dollars(od.usedDollars), ...resets, aside: true }] : [] // A merged plan has no pools: its included usage is one allowance every // model draws on, which the dashboard shows as the period's // totalPercentUsed, autoPercentUsed the same and apiPercentUsed 0 always. const info = await plan // spent is whether a pool no longer pays: then the models a credit still // pays for are left out of it const spent = (used) => covers.size > 0 && !pooled.aside && used >= 100 if (info?.merged === true) { const weekly = info.period === "weekly" const used = num(u.totalPercentUsed) return { windows: [ { name: weekly ? "Weekly" : info.period === "monthly" ? "Monthly" : "Included", used, ...resets, ...(weekly ? { span: 604800 } : {}), ...(spent(used) ? { notModels: [...covers] } : {}), ...pooled }, ...onDemand, ], credits: free.windows, } } // the two pools fit the line; the total goes in its tooltip. A spent // Cursor Models pool every model of which a credit pays for is aside: // an empty models list would count every model. const auto = num(u.autoPercentUsed), api = num(u.apiPercentUsed) const cursorModels = spent(auto) ? pool.filter((m) => !covers.has(m)) : pool return { windows: [ { name: "Cursor Models", used: auto, ...resets, models: cursorModels.length ? cursorModels : pool, ...(cursorModels.length ? pooled : { aside: true }) }, { name: "Other Models", used: api, ...resets, notModels: spent(api) ? [...new Set([...pool, ...covers])] : pool, ...pooled }, ...onDemand, { name: "Total", used: num(u.totalPercentUsed), ...resets, aside: true }, ], credits: free.windows, } } // Grok Bot's separate allowance, using the CLI JWT as a dashboard session. async function botUsage(tok) { try { const subject = JSON.parse(Buffer.from(tok.split(".")[1], "base64url").toString()).sub if (typeof subject !== "string") return [] const user = subject.split("|").filter(Boolean).at(-1) if (!user || !/^[a-zA-Z0-9._-]+$/.test(user)) return [] const res = await fetch(WEBSITE + "/api/dashboard/get-sand-usage-status", { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json", Origin: WEBSITE, Cookie: "WorkosCursorSessionToken=" + encodeURIComponent(user + "::" + tok), }, body: "{}", redirect: "error", signal: AbortSignal.timeout(5_000), }) if (!res.ok) return [] const data = await res.json() const paid = typeof data?.includedLimitZero === "boolean" ? !data.includedLimitZero : data?.hasNonZeroIncludedLimit === true const trial = !paid && typeof data?.sandTrialExpiresAt === "string" && Date.parse(data.sandTrialExpiresAt) > Date.now() if ((!paid && !trial) || typeof data?.usagePercent !== "number" || !Number.isFinite(data.usagePercent)) return [] const reset = paid && typeof data.nextResetTimestampUtc === "string" ? Date.parse(data.nextResetTimestampUtc) : NaN return [{ name: trial ? "Grok Bot (trial)" : "Grok Bot", used: Math.max(0, Math.min(100, data.usagePercent)), aside: true, // Bot exhaustion must not stop Cursor model requests. ...(Number.isFinite(reset) ? { resetsAt: new Date(reset).toISOString(), span: 604800 } : {}), }] } catch { return [] } } // ---- models ---------------------------------------------------------------------- // // The list is Cursor's model picker (AiService/AvailableModels, asked as the // CLI asks it), the way pi-cursor-sdk lists Cursor's SDK catalog: each model // is offered once for each of its context sizes, named "Claude Opus 5.5 @ // 300k" and with that many tokens as its window; one without a context // parameter is offered once, with Cursor's limit for it. Effort is the // request's reasoning_effort and fast its service_tier, sent as the model's // own parameters, so neither is a model of its own. A request goes as the // variant those parameters pick, in Max Mode when that variant is Max Mode's. const LEVEL_RANK = ["none", "minimal", "low", "medium", "high", "xhigh", "max"] const EFFORT_PARAMS = ["effort", "reasoning_effort", "reasoning"] // the effort words of Cursor's own ids and the levels they are; extra-high // before high const ID_EFFORTS = [["extra-high", "xhigh"], ["xhigh", "xhigh"], ["minimal", "minimal"], ["none", "none"], ["low", "low"], ["medium", "medium"], ["high", "high"], ["max", "max"]] const cut = (s, suffix) => (s.endsWith(suffix) && s.length > suffix.length ? s.slice(0, -suffix.length) : null) // splitID is one of Cursor's own ids (a variant's legacySlug, as // cursor-agent models lists it) taken apart: its family, and the effort // ("" for none named) it is at. Thinking comes before the effort or after // it; in the family it goes after, as does fast. The family is the id 0.1.x // listed a model by. function splitID(id) { let s = id let fast = false let thinking = false let effort = "" let b if ((b = cut(s, "-fast")) !== null) [s, fast] = [b, true] if ((b = cut(s, "-thinking")) !== null) [s, thinking] = [b, true] for (const [word, level] of ID_EFFORTS) { if ((b = cut(s, "-" + word)) !== null) { ;[s, effort] = [b, level] break } } if (!thinking && (b = cut(s, "-thinking")) !== null) [s, thinking] = [b, true] if (thinking) s += "-thinking" if (fast) s += "-fast" return [s, effort] } // left out of the CLI's picker as it leaves them out (model-service.ts) const PICKER_SKIP = new Set(["claude-4.5-haiku", "claude-4.5-haiku-thinking", "gemini-2.5-pro", "gemini-2.5-flash", "claude-haiku-4-5"]) const clean = (s) => String(s ?? "").replaceAll("\u200b", "").split(/\s+/).filter(Boolean).join(" ") // tokensOf is a context value as tokens: "300k" 300000, "1m" 1000000. function tokensOf(value) { const m = /^(\d+(?:\.\d+)?)([km])$/i.exec(String(value ?? "").trim()) return m ? Math.round(Number(m[1]) * (m[2].toLowerCase() === "m" ? 1_000_000 : 1_000)) : 0 } // paramDefs is a picker model's parameters: id to the values it takes. function paramDefs(m) { const out = {} for (const d of m.parameterDefinitions ?? []) { const t = d?.parameterType ?? {} const vs = (t.enumParameter ?? t.booleanParameter)?.values ?? [] if (d?.id) out[d.id] = vs.map((v) => String(v.value)) } return out } const valuesOf = (v) => Object.fromEntries((v?.parameterValues ?? []).map((p) => [String(p.id), String(p.value)])) // defaultVariant is the variant the CLI picks for a model asked for by // name: its default without Max Mode, else with it, else the first. const defaultVariant = (m) => { const vs = m?.variants ?? [] return vs.find((v) => v.isDefaultNonMaxConfig) ?? vs.find((v) => v.isDefaultMaxConfig) ?? vs[0] } // needsMax is whether a variant is run in Max Mode only, as the CLI reads // it: a model with no other mode, or a Max Mode variant. const needsMax = (m, v) => m?.supportsNonMaxMode === false || v?.isMaxMode === true // effortsOf is the efforts a model takes, as pi's levels, each with the // value Cursor's parameter has for it (extra-high is xhigh). function effortsOf(defs) { const pid = EFFORT_PARAMS.find((p) => defs[p]?.length) // thinking alone, on or off: high and none if (!pid && defs.thinking?.includes("true") && defs.thinking.includes("false")) return { pid: "thinking", levels: { none: "false", high: "true" } } if (!pid) return { pid: "", levels: {} } const levels = {} for (const v of defs[pid]) { const l = v === "extra-high" ? "xhigh" : v if (LEVEL_RANK.includes(l)) levels[l] = v } return { pid, levels } } // served is a picker model's variants the account is served. With the // usable list at hand (the ids cursor-agent models shows), a variant whose // own id isn't in it is one the account hasn't got (Sonnet 4.6 at any effort // but medium, say). A model the usable list has nothing of is the picker's // alone (GLM-5.3), and is kept whole. function served(m, ids) { const vs = m.variants ?? [] if (!ids) return vs const got = vs.filter((v) => !v.legacySlug || ids.has(v.legacySlug)) return got.some((v) => v.legacySlug) ? got : vs } // familyOf is the family one of Cursor's own ids is of, fast or not: // claude-opus-5-5-low-fast is of claude-opus-5-5, at low, fast. function familyOf(id) { let [family, effort] = splitID(id) const fast = family.endsWith("-fast") && family.length > "-fast".length if (fast) family = family.slice(0, -"-fast".length) return { family, effort, fast } } // familiesOf is the usable list (GetUsableModels, what cursor-agent models // shows: claude-opus-5-5-low, claude-opus-5-5-low-fast, …) by family: each // id with its effort, whether it is fast, whether Cursor runs it in Max // Mode, and its name. function familiesOf(listed) { const fams = new Map() for (const u of listed ?? []) { const id = String(u?.modelId ?? "") if (!id) continue const { family, effort, fast } = familyOf(id) if (!fams.has(family)) fams.set(family, []) fams.get(family).push({ id, effort, fast, maxMode: u.maxMode === true, name: clean(u.displayName || id) }) } return fams } // fromUsable is the id of a family of the usable list's that a request // runs as: fast as asked (when the family has both), at the effort asked or // the nearest it has; with none asked, the one without an effort in its // id, else medium, as Cursor's default is (claude-opus-5-5-medium), else // the first. function fromUsable(fam, effort, fast) { let vs = fam.filter((u) => u.fast === !!fast) if (!vs.length) vs = fam if (effort === "off") effort = "none" const at = effort ? fitEffort(effort, vs.map((u) => u.effort).filter(Boolean)) : "" return (at && vs.find((u) => u.effort === at)) || vs.find((u) => u.effort === "") || vs.find((u) => u.effort === "medium") || vs[0] } // usableTitle is a usable id's name without what the id says apart: its // effort, fast, and the 1M Cursor names every Max-capable Claude with // ("Claude Opus 5.5 1M Low" is Claude Opus 5.5), wherever Cursor puts // them: "Claude Opus 5 1M Medium Thinking" is Claude Opus 5 Thinking, as // its efforts are magpie's reasoning levels and not models of their own // (ysm119 on Discord read "Medium" in the name as the only tier). A word // of the model's own name stays: GPT-5.1 Codex Max at high is "GPT-5.1 // Codex Max". const EFFORT_WORDS = { none: ["None"], minimal: ["Minimal"], low: ["Low"], medium: ["Medium"], high: ["High"], xhigh: ["Extra High", "XHigh"], max: ["Max"] } function usableTitle(u) { const ws = u.name.split(" ") // the last time a phrase is said, past the name's first word const cutLast = (phrase) => { const p = phrase.toLowerCase().split(" ") for (let i = ws.length - p.length; i >= 1; i--) { if (p.every((w, k) => ws[i + k].toLowerCase() === w)) { ws.splice(i, p.length) return true } } return false } for (const p of EFFORT_WORDS[u.effort] ?? []) if (cutLast(p)) break if (u.fast) cutLast("fast") return ws.filter((w, i) => i === 0 || !/^\(?1m\)?$/i.test(w)).join(" ") || u.name } // modelsOf is the picker's models as offered: one entry for each context // size a model has, or one with Cursor's limit when it has none. A model // served in part is offered at the sizes and efforts it is served at. // listed is the usable list: a family of its ids the picker has nothing of // (a Team's picker can leave out what cursor-agent models lists, magpie // #3150 ysm119 on Discord) is offered too, once, with its efforts, and each // entry keeps its family's usable ids, so a request goes as one of those // and never as a name Cursor would answer "AI Model Not Found". function modelsOf(picker, ids, listed = []) { const out = [] const used = new Set() const fams = familiesOf(listed) // every id the picker names at all, shown or left out const named = new Set() for (const m of picker) { if (!m?.name) continue for (const x of [m.name, ...(m.legacySlugs ?? []), ...(m.idAliases ?? []), ...(m.variants ?? []).map((v) => v.legacySlug)]) if (x) named.add(x) } for (const m of picker) { if (!m?.name || m.isHidden || m.isChatOnly || m.onlySupportsCmdK || m.supportsAgent === false || PICKER_SKIP.has(m.name)) continue const defs = paramDefs(m) const variants = served(m, ids) const partial = variants.length < (m.variants ?? []).length const has = (pid, value) => !partial || !variants.some((v) => pid in valuesOf(v)) || variants.some((v) => valuesOf(v)[pid] === value) const def = defaultVariant({ variants }) const { pid, levels: all } = effortsOf(defs) const levels = Object.fromEntries(Object.entries(all).filter(([, value]) => has(pid, value))) // the usable ids of its default's family, else of the same model with // thinking or without it: a Team's picker can default Claude Haiku 5.5 // to thinking while cursor-agent lists it as claude-haiku-5-5 alone // (ysm119 on Discord, after 0.2.25), and a variant id it lacks is then // asked as that one, as named() takes such an id const own = familyOf(def?.legacySlug || m.name).family const bare = own.replace(/-thinking$/, "") const fam = fams.get(own) ?? fams.get(bare) ?? fams.get(bare + "-thinking") ?? [] const base = { run: m.name, title: clean(m.clientDisplayName || m.name), pid, levels, fast: !!defs.fast?.length, variants, def, partial, model: m, fam, ids } const contexts = (defs.context ?? []).filter((c) => has("context", c)) if (contexts.length) { for (const c of contexts) { const id = m.name + "@" + c if (used.has(id)) continue used.add(id) out.push({ ...base, id, name: base.title + " @ " + c, context: tokensOf(c) || DEFAULT_CONTEXT, size: c, offersFast: fastAt(variants, c) }) } } else if (!used.has(m.name)) { used.add(m.name) const limit = needsMax(m, def) ? m.contextTokenLimitForMaxMode || m.contextTokenLimit : m.contextTokenLimit out.push({ ...base, id: m.name === "default" ? "auto" : m.name, name: base.title, context: limit > 0 ? limit : DEFAULT_CONTEXT, size: "", offersFast: fastAt(variants, "") }) } } for (const [family, fam] of fams) { if (fam.some((u) => named.has(u.id)) || named.has(family) || used.has(family)) continue used.add(family) const levels = Object.fromEntries(fam.filter((u) => LEVEL_RANK.includes(u.effort)).map((u) => [u.effort, u.effort])) const def = fromUsable(fam, "", false) // Cursor's context for it isn't known: its default's, as for a model // the picker gives no limit for out.push({ id: family, run: family, name: usableTitle(def), title: usableTitle(def), pid: "", levels, fast: false, variants: [], def: undefined, partial: false, model: { name: family }, fam, ids, usableOnly: true, context: DEFAULT_CONTEXT, size: "", offersFast: fam.some((u) => u.fast) }) } return out } // slugFor is the id of a variant the full catalog (AvailableModels with // scope 3) gives no legacySlug: the one of the model's legacySlugs that says // the variant's effort (any, when it has none), thinking and fast; an id // with no effort in it (gpt-5.3-codex) stands for the default's effort. With // none, or more than one, "": a guess could send an id Cursor refuses. function slugFor(m, v) { if (v.legacySlug) return v.legacySlug const have = valuesOf(v) const level = (p) => String(p[EFFORT_PARAMS.find((k) => p[k])] ?? "").replace("extra-high", "xhigh") const effort = level(have) const slugs = (Array.isArray(m.legacySlugs) ? m.legacySlugs : []).filter((id) => typeof id === "string" && id).map((id) => ({ id, ...familyOf(id) })) const says = (s, at) => (at === null || s.effort === at) && (have.thinking === undefined || s.family.endsWith("-thinking") === (have.thinking === "true")) && (have.fast === undefined || s.fast === (have.fast === "true")) let hits = slugs.filter((s) => says(s, effort || null)) const def = m.variants.find((x) => x?.isDefaultNonMaxConfig) if (!hits.length && effort && level(valuesOf(def)) === effort) hits = slugs.filter((s) => says(s, "")) return hits.length === 1 ? hits[0].id : "" } // withSlugs is a catalog model with each variant's own id filled in, and // only the parameters the model defines: the full catalog is the admin // settings one, and carries what the picker's variants don't (cyber=false // on Opus 4.7 to 5.5, which cursor-agent never sends). A variant slugFor // can't name keeps no id of its own, but never goes without one: served() // leaves a variant with no legacySlug in, and one the account can't run // would be listed. So it gets a mark no usable id has, and modelsOf lists // it as it does a variant the account hasn't got. The variants are never // null. const NO_ID = "\u0000no-id" function withSlugs(m) { const defined = new Set((Array.isArray(m.parameterDefinitions) ? m.parameterDefinitions : []).map((d) => d?.id)) const vs = (Array.isArray(m.variants) ? m.variants : []) .filter((v) => v && typeof v === "object" && Array.isArray(v.parameterValues ?? [])) .map((v) => ({ ...v, parameterValues: (v.parameterValues ?? []).filter((p) => defined.has(p?.id)) })) const full = { ...m, variants: vs } return { ...full, variants: vs.map((v) => (v.legacySlug ? v : { ...v, legacySlug: slugFor(full, v) || NO_ID })) } } // fromCatalog is the live models of Cursor's full catalog (AvailableModels // with scope 3, which also lists the models Cursor hides from some accounts: // Claude, from a Pro one) that the picker lacks, as picker models, with only // the variants the account can run (withSlugs). modelsOf lists them as it // does the picker's: once for each context size, thinking a parameter, the // efforts the account is served. Only Anthropic's are taken: the models the // picker lists, and every other id of the usable list, stay as they are. // Not offered: one the picker has or lists under another name, a hidden one // (isHidden: no longer offered), Auto, one the picker leaves out (chat-only, // Tab-only, no agent), and one with no variant the account has an id for. function fromCatalog(picker, catalog, ids) { const have = new Set(picker.map((m) => m?.name)) const out = [] for (const m of Array.isArray(catalog) ? catalog : []) { if (!m?.name || have.has(m.name) || m.isHidden || m.name === "default") continue if (m.vendor?.id !== "MODEL_VENDOR_ID_ANTHROPIC") continue if (m.isChatOnly || m.onlySupportsCmdK || m.supportsAgent === false || PICKER_SKIP.has(m.name)) continue const full = withSlugs(m) if (full.variants.some((v) => ids.has(v.legacySlug))) out.push(full) } return out } // fastAt is whether Cursor has a fast variant the account is served at // the context size (any, for a model without sizes): what magpie offers // fast for, which 0.1.x said with a -fast model of its own. const fastAt = (variants, size) => variants.some((v) => { const have = valuesOf(v) return have.fast === "true" && (!size || have.context === undefined || have.context === size) }) // nearest is the variant of vs most like the parameters wanted, one at // their context size before any other. function nearest(vs, want) { let best let most = -1 for (const v of vs) { const have = valuesOf(v) const n = Object.keys(want).filter((k) => have[k] === want[k]).length + (have.context === want.context ? 100 : 0) if (n > most) [best, most] = [v, n] } return best } // pick is the variant a request runs as: the model's context size, the // effort asked for (else the default's) and fast as asked, matched against // Cursor's variants. With no variant that matches, the parameters go as // they are, from the default's; of a model served in part, as the nearest // variant the account has. seed is the variant an id of Cursor's own named // (request), in the default's place. function pick(entry, effort, fast, seed) { // a family the usable list has and the picker doesn't: its own id if (entry.usableOnly) { const u = fromUsable(entry.fam, effort, fast) return { id: u.id, params: [], maxMode: u.maxMode } } const def = entry.def const want = { ...valuesOf(seed ?? def) } if (entry.size) want.context = entry.size if (effort === "off") effort = "none" if (entry.pid && entry.pid !== "thinking" && effort === "none" && !("none" in entry.levels) && "thinking" in want) { // a Claude asked not to think: thinking off at its default effort want.thinking = "false" } else if (entry.pid) { const at = effort ? fitEffort(effort, Object.keys(entry.levels)) : "" if (at && entry.levels[at]) want[entry.pid] = entry.levels[at] // a variant named says for itself whether it thinks if (!seed && entry.pid !== "thinking" && "thinking" in want && at) want.thinking = "true" } // fast only when asked: it costs more if (entry.fast) want.fast = fast ? "true" : "false" const same = (v) => { const have = valuesOf(v) return Object.keys({ ...have, ...want }).every((k) => have[k] === undefined || want[k] === undefined || have[k] === want[k]) } const v = entry.variants.find(same) ?? (seed ? branch(entry, want) : undefined) ?? (entry.partial ? nearest(entry.variants, want) : undefined) const params = Object.entries(v ? { ...want, ...valuesOf(v) } : want).map(([id, value]) => ({ id, value })) // no variant: Max Mode when the size is more than Cursor allows outside it const maxMode = v ? needsMax(entry.model, v) : needsMax(entry.model, def) || tokensOf(entry.size) > (entry.model.contextTokenLimit || Infinity) // the agent API takes the variant's own id (its legacySlug, as // cursor-agent models lists it: claude-opus-5-5-high), not the picker's // model name; the default's when no variant matched const id = v?.legacySlug || def?.legacySlug || entry.run // an id the usable list doesn't have, when it has the family's (a // picker model without variants goes by its name, claude-opus-5-5, // which Cursor doesn't serve): the family's usable id at the effort if (entry.ids && !entry.ids.has(id) && entry.fam?.length) { const level = entry.pid && entry.pid !== "thinking" ? String(want[entry.pid] ?? "").replace("extra-high", "xhigh") : "" const u = fromUsable(entry.fam, effort || level, fast) return { id: u.id, params: [], maxMode: maxMode || u.maxMode } } return { id, params, maxMode } } // branch is, for an id of Cursor's own asked at an effort no variant has // with the rest of its parameters (claude-opus-5-low at xhigh: Opus 5 // without thinking stops at high), the variant with those parameters at the // nearest effort it has, not the default's id with parameters that // contradict it (claude-opus-5-thinking-high with thinking=false). Where // the default differs from what is asked in the effort alone, and no // variant at all is named for that effort, the effort goes as asked, as for // a listed model (claude-opus-5-5-xhigh). When another branch has it, the // default's own branch stops short there, and its nearest goes (#55). function branch(entry, want) { if (!entry.pid || entry.pid === "thinking") return undefined const level = (x) => (x === "extra-high" ? "xhigh" : x) const def = valuesOf(entry.def) const named = entry.variants.some((v) => level(valuesOf(v)[entry.pid]) === level(want[entry.pid])) if (!named && Object.keys(want).every((k) => k === entry.pid || k === "context" || def[k] === undefined || def[k] === want[k])) return undefined const vs = entry.variants.filter((v) => { const have = valuesOf(v) return entry.pid in have && Object.keys(want).every((k) => k === entry.pid || have[k] === undefined || have[k] === want[k]) }) const at = fitEffort(level(want[entry.pid]), vs.map((v) => level(valuesOf(v)[entry.pid]))) return at ? vs.find((v) => level(valuesOf(v)[entry.pid]) === at) : undefined } // fitEffort is the nearest effort a model has to the one asked for; max // for ultra, and none only when asked. function fitEffort(want, levels) { if (want === "ultra") want = "max" if (!levels.length || levels.includes(want)) return want const at = LEVEL_RANK.indexOf(want) if (at < 0) return "" let best = "" let dist = LEVEL_RANK.length for (const l of levels) { const i = LEVEL_RANK.indexOf(l) if (i < 0 || l === "none") continue const d = Math.abs(i - at) if (d < dist || (d === dist && i > at)) [best, dist] = [l, d] } return best } // usable is the account's list, kept a while, by token: Cursor's picker, // less the variants the usable list (AgentService/GetUsableModels, what // cursor-agent models shows) says the account hasn't got. A picker Cursor // 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 return listing(tok, h) } function listing(tok, h) { let p = listings.get(h) if (p) return p p = (async () => { const [j, listed, catalog] = 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 : []), () => [], ), // the full catalog, scope 3: the live models the picker lacks (Claude, // on an account Cursor blocks it for); without it the list is the // picker's and the usable list's, as before unary(API, "aiserver.v1.AiService/AvailableModels", tok, { useModelParameters: true, doNotUseMarkdown: true, scope: 3 }, 8_000).then( (c) => (Array.isArray(c?.models) ? c.models : []), () => [], ), ]) const ids = new Set(listed.flatMap((m) => [m?.modelId, m?.displayModelId]).filter(Boolean)) const picker = Array.isArray(j?.models) ? j.models : [] const raw = modelsOf(ids.size ? [...picker, ...fromCatalog(picker, catalog, ids)] : picker, 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, // when it is one of Cursor's own, as the CLI reads one and as 0.1.x listed // them, so a model picked before the list changed still runs: a variant's // own id (claude-opus-5-5-high) is that variant; a family of them, the id // 0.1.x listed (claude-opus-5-5, claude-opus-5-5-fast, cursor-grok-4.6, // or with an effort the account lacks), is the family's variant nearest // the default, fast when the family is and at the id's effort; the picker's // name for a model, or a legacy slug of it, is its default. Each at the // variant's context size, the default's when the id doesn't say. function named(raw, id) { const models = raw.filter((e, i) => raw.findIndex((x) => x.model === e.model) === i) const at = (e, v) => raw.find((x) => x.model === e.model && x.size === (valuesOf(v).context ?? "")) ?? e const as = (e, vs, effort) => { const seed = nearest(vs, valuesOf(e.def)) return { entry: at(e, seed), seed, effort, fast: valuesOf(seed).fast === "true" } } for (const e of models) { const vs = e.variants.filter((v) => v.legacySlug === id) if (vs.length) return as(e, vs, "") } const [family, effort] = splitID(id) for (const e of models) { const vs = e.variants.filter((v) => v.legacySlug && splitID(v.legacySlug)[0] === family) if (vs.length) return as(e, vs, effort) } for (const e of models) { const m = e.model if (e.usableOnly) continue if ([m.name, ...(m.legacySlugs ?? []), ...(m.idAliases ?? [])].includes(id)) return { entry: at(e, e.def), seed: undefined, effort: "", fast: false } } // one of the usable list's own ids, or a family of them, that the picker // has nothing of: that family at the id's effort, fast when it is const of = familyOf(id) for (const e of models) { if (!e.usableOnly) continue const u = e.fam.find((x) => x.id === id) if (u) return { entry: e, seed: undefined, effort: u.effort, fast: u.fast } if (e.id === of.family) return { entry: e, seed: undefined, effort: of.effort, fast: of.fast } } // a family neither has, where the account has the same model with // thinking or without it (claude-haiku-5-5-thinking, which 0.1.x listed, // on a Team account whose list has Claude Haiku 5.5 without a thinking // id; ysm119 on Discord): that one, at the id's effort, never the id as // it is, which Cursor answers "AI Model Not Found" const loose = (f) => f.replace(/-thinking$/, "") const key = loose(of.family) for (const e of models) { if (e.usableOnly) { if (loose(e.id) === key) return { entry: e, seed: undefined, effort: of.effort, fast: of.fast } continue } const vs = e.variants.filter((v) => v.legacySlug && loose(familyOf(v.legacySlug).family) === key) if (vs.length) return as(e, vs, of.effort) } // an id at a context size the list no longer has (claude-opus-5-5@1m, // picked from an earlier list, or from another account's): the model at // the nearest size it has; a model listed without sizes, in Max Mode for // a size over its window const sized = /^(.+)@([^@]+)$/.exec(id) if (sized) { const want = tokensOf(sized[2]) const same = raw.filter((e) => e.run === sized[1] && e.size) if (same.length) { const near = same.reduce((a, b) => (Math.abs(tokensOf(b.size) - want) < Math.abs(tokensOf(a.size) - want) ? b : a)) return { entry: near, seed: undefined, effort: "", fast: false } } const old = named(raw, sized[1]) if (old) { // the name's model at the nearest size it has (claude-opus-4-8-thinking@1m, // an id an earlier list had, is Opus 4.8 at 1m with thinking) const sizes = raw.filter((e) => e.size && e.model === old.entry.model) if (old.entry.size && sizes.length) { const near = sizes.reduce((a, b) => (Math.abs(tokensOf(b.size) - want) < Math.abs(tokensOf(a.size) - want) ? b : a)) return { ...old, entry: near } } return { ...old, max: !old.entry.size && want > old.entry.context } } } return null } // request is how a chat's model is asked of Cursor: the variant's own id, // its parameters and its mode. An id the list doesn't have that is one of // Cursor's own goes as the variant it names, at the effort asked for, fast // when it says so or the request does; any other goes as it is named. function request(raw, model, effort, fast) { const entry = raw.find((m) => m.id === model) if (entry) return pick(entry, effort, fast) const bare = raw.find((m) => m.id === model.replace(/@[^@]*$/, "")) if (bare && model !== bare.id && !bare.size) { // a model now listed without sizes, asked at one const r = pick(bare, effort, fast) return tokensOf(model.split("@").at(-1)) > bare.context ? { ...r, maxMode: true } : r } const old = named(raw, model) if (old) { const r = pick(old.entry, effort || old.effort, fast || old.fast, old.seed) return old.max ? { ...r, maxMode: true } : r } return { id: model === "auto" ? "default" : model, params: [], maxMode: false } } function runtimeModel(m) { const efforts = LEVEL_RANK.filter((l) => l in m.levels) return { id: m.id, providerID: ID, name: m.name, api: { id: m.id, url: AGENT, npm: CHAT }, status: "active", headers: {}, options: {}, cost: { input: 0, output: 0, cache: { read: 0, write: 0 } }, limit: { context: m.context || DEFAULT_CONTEXT, output: 0 }, capabilities: { temperature: false, reasoning: efforts.length > 0, attachment: true, toolcall: true, input: { text: true, image: true, audio: false, video: false, pdf: false }, output: { text: true, image: false, audio: false, video: false, pdf: false }, interleaved: false, }, release_date: "", variants: Object.fromEntries(efforts.map((e) => [e, { reasoningEffort: e }])), // a request's service_tier priority (or fast) runs it as Cursor's fast // variant: magpie offers Fast for the models that have one ...(m.offersFast ? { fast: true } : {}), } } // ---- protobuf, by hand ------------------------------------------------------------ class PB { parts = [] push(b) { this.parts.push(b) return this } uv(v) { const out = [] while (v >= 0x80) { out.push((v % 128) | 0x80) v = Math.floor(v / 128) } out.push(v) return this.push(Uint8Array.from(out)) } tag(num, wire) { return this.uv(num * 8 + wire) } varint(num, v) { return this.tag(num, 0).uv(v) } bytes(num, v) { const b = v instanceof PB ? v.done() : v ?? EMPTY return this.tag(num, 2).uv(b.length).push(b) } str(num, s) { return this.bytes(num, Buffer.from(s, "utf8")) } double(num, v) { const b = Buffer.alloc(8) b.writeDoubleLE(v) return this.tag(num, 1).push(b) } done() { return Buffer.concat(this.parts) } } const pb = () => new PB() // fields reads a message's fields; a malformed tail is dropped. function fields(b) { b = Buffer.isBuffer(b) ? b : Buffer.from(b ?? EMPTY) const out = [] let i = 0 const uv = () => { let v = 0 let m = 1 while (i < b.length) { const c = b[i++] v += (c & 0x7f) * m if (c < 0x80) return v m *= 128 } return -1 } while (i < b.length) { const key = uv() if (key < 0) break const f = { num: Math.floor(key / 8), wire: key % 8, n: 0, data: EMPTY } switch (f.wire) { case 0: { const v = uv() if (v < 0) return out f.n = v break } case 1: if (i + 8 > b.length) return out f.data = b.subarray(i, i + 8) f.n = Number(b.readBigUInt64LE(i)) i += 8 break case 2: { const l = uv() if (l < 0 || i + l > b.length) return out f.data = b.subarray(i, i + l) i += l break } case 5: if (i + 4 > b.length) return out f.n = b.readUInt32LE(i) i += 4 break default: return out } out.push(f) } return out } const field = (fs, num) => fs.find((f) => f.num === num) const pbStr = (fs, num) => field(fs, num)?.data.toString("utf8") ?? "" const pbNum = (fs, num) => field(fs, num)?.n ?? 0 // pbValue is a google.protobuf.Value. function pbValue(v) { if (v === null || v === undefined) return pb().varint(1, 0) if (typeof v === "number") return pb().double(2, v) if (typeof v === "string") return pb().str(3, v) if (typeof v === "boolean") return pb().varint(4, v ? 1 : 0) if (Array.isArray(v)) { const l = pb() for (const e of v) l.bytes(1, pbValue(e)) return pb().bytes(6, l) } if (typeof v === "object") { const st = pb() for (const k of Object.keys(v).sort()) st.bytes(1, pb().str(1, k).bytes(2, pbValue(v[k]))) return pb().bytes(5, st) } return pb().varint(1, 0) } // pbAny reads a google.protobuf.Value. function pbAny(b) { for (const f of fields(b)) { switch (f.num) { case 1: return null case 2: return f.data.length === 8 ? f.data.readDoubleLE(0) : 0 case 3: return f.data.toString("utf8") case 4: return f.n !== 0 case 5: { const m = {} for (const e of fields(f.data)) { if (e.num !== 1) continue const kv = fields(e.data) const v = field(kv, 2) m[pbStr(kv, 1)] = v ? pbAny(v.data) : null } return m } case 6: return fields(f.data).filter((e) => e.num === 1).map((e) => pbAny(e.data)) } } return null } // frame wraps a message as one frame of a Connect stream. function frame(msg) { const head = Buffer.alloc(5) head.writeUInt32BE(msg.length, 1) return Buffer.concat([head, msg]) } // frames reads a Connect stream's frames: a message, or the stream's end // with its JSON. async function* frames(body) { let buf = EMPTY for await (const chunk of body) { buf = buf.length ? Buffer.concat([buf, chunk]) : Buffer.from(chunk) while (buf.length >= 5) { const n = buf.readUInt32BE(1) if (n > 64 << 20) throw new Error("a malformed stream") if (buf.length < 5 + n) break const flags = buf[0] let data = buf.subarray(5, 5 + n) buf = buf.subarray(5 + n) if (flags & 1) data = gunzipSync(data) yield { end: (flags & 2) !== 0, data } } } if (buf.length) throw new Error("unexpected EOF") } // ---- failures ----------------------------------------------------------------------- const regional = (msg) => msg.toLowerCase().includes("region") // failure is the status and message for Cursor's Connect error, whose // details say it best: {"code", "message", "details": [{"debug": {"error", // "details": {"title", "detail"}}}]}, or the same under "error" at a // stream's end. function failure(status, text) { let e try { e = JSON.parse(typeof text === "string" ? text : Buffer.from(text).toString("utf8")) } catch { return statusOf(status, "", String(text ?? "").trim()) } const f = e?.error && typeof e.error === "object" ? e.error : e ?? {} let msg = f.message ?? "" for (const d of f.details ?? []) { const t = `${d?.debug?.details?.title ?? ""}: ${d?.debug?.details?.detail ?? ""}`.trim() if (t !== ":") msg = t.replace(/^[:\s]+|[:\s]+$/g, "") } if (!msg || msg === "Error") msg = f.code ?? "" if (!f.code && status >= 200 && status < 300) return { status, message: msg } // a stream that ended well return statusOf(status, f.code ?? "", msg) } // statusOf is the status and words for Cursor's error of this code and // message. A region the team isn't served in says so, not to sign in. function statusOf(status, code, msg) { msg ||= statusText(status) const low = msg.toLowerCase() // magpie names the provider before the message itself const out = (status, message) => ({ status, message }) if (regional(msg)) return out(403, msg + " — Cursor serves your team only in some regions and turned this request away; signing in again won't change that") if (code === "permission_denied") return out(403, msg) if (code === "unauthenticated" || status === 401 || low.includes("expired")) return out(401, msg + " — sign in to Cursor again in magpie") if (code === "resource_exhausted" || low.includes("quota") || low.includes("rate limit") || low.includes("usage limit")) return out(429, "usage limit reached: " + msg) if (low.includes("too long") || low.includes("context length") || low.includes("too many tokens")) return out(400, "input is too long for the model's context: " + msg) if (code === "invalid_argument") return out(400, msg) if (code === "unavailable") return out(503, msg) if (code) return out(502, msg) return out(status, msg) } // ---- the conversation ------------------------------------------------------------- const textOf = (c) => typeof c === "string" ? c : Array.isArray(c) ? c.filter((p) => p?.type === "text").map((p) => p.text ?? "").join("") : "" // Chat clients replay thinking beside content. Cursor's transcript blobs // use AI SDK reasoning parts; putting it in text would change its role. const reasoningOf = (m) => [m.reasoning_content, m.reasoning].find((s) => typeof s === "string" && s.trim()) ?? "" // joinSplitCalls joins an assistant message onto the assistant message // before it when that one made tool calls: Anthropic takes consecutive // assistant messages as one turn, and an agent can send a turn's parallel // calls split over two of them, answered together after (yetone/magpie#1275). // Answered at the second message, the first calls would be marked // interrupted and their real results dropped. msgs is left as it is. function joinSplitCalls(msgs) { const out = [] for (const m of msgs) { const prev = out.at(-1) if (m?.role === "assistant" && prev?.role === "assistant" && prev.tool_calls?.length) { const content = [textOf(prev.content), textOf(m.content)].filter(Boolean).join("\n\n") const reasoning_content = [reasoningOf(prev), reasoningOf(m)].filter(Boolean).join("\n\n") out[out.length - 1] = { ...prev, content, reasoning_content, tool_calls: [...prev.tool_calls, ...(m.tool_calls ?? [])] } continue } out.push(m) } return out } function parseArgs(s) { if (s && typeof s === "object") return s try { const v = JSON.parse(s || "{}") return v && typeof v === "object" ? v : {} } catch { return {} } } // tools are the caller's tools the model may call: none for tool_choice // "none", the one named when one is. function toolsOf(chat) { const choice = chat.tool_choice const only = typeof choice === "object" ? choice?.function?.name : "" if (choice === "none") return [] return (chat.tools ?? []) .filter((t) => t?.type === "function" && t.function?.name && (!only || t.function.name === only)) .map((t) => { const schema = t.function.parameters ?? { type: "object", properties: {} } return { name: t.function.name, description: t.function.description ?? "", schema, schemaText: JSON.stringify(schema) } }) } // NS is the MCP server the caller's tools are served as, the way Cursor's // own client names a user's server by its mcp.json label (providerIdentifier, // with "