cursor 0.2.18: a failed tool result tells Cursor isError, and a refused keychain read is not asked again for ten minutes

Two things magpie's built-in Cursor did that the plugin didn't, ahead of
the built-in's retirement:

- The stateless path (conversation) sent every tool result with
  isError false. A chat tool message with is_error: true (what magpie now
  sends for a failed tool, as the built-in's cursorResult told Cursor
  isError) is marked isError, as the native path already did.
- cliToken ran `security` on every call. It now reads the Keychain as the
  built-in's cursorKeychainToken (internal/provider/cursor.go; magpie
  #746, #2408): a read is kept 10s; a read that failed with anything but
  exit 44 (no such item) may have been a dialog the user said no to, and
  is not asked again for 10 minutes; reads go one at a time, so callers
  at once share one run. A sign-in and the read after `cursor-agent
  status` read afresh, as forgetCursorStatus / cursorTokenOf(true) did.
  README's "read on every request" says so now.

What was run (bun 1.4.2, macOS, load average ~280-300):
- parity.test.mjs (new, 5 tests): green. Broken by hand, each watched
  red, then restored: is_error ignored (1 red), cache check removed
  (3 red), denied backoff at 10s (1 red), exit 44 treated as refusal
  (1 red), no read serialisation (1 red).
- `security find-generic-password` for a missing item gives execFile
  err.code 44 (number) on this Mac, as the mapping assumes.
- Full `bun test` in packages/cursor, 7 runs: 272/272 green in 4; the
  other 3 red only in latency.test.mjs ("events never show in time",
  #159; "nothing naming the session", #162), which the change doesn't
  touch. On clean origin/main aec06bd, latency.test.mjs alone is red
  too, including "far from Cursor ... cache and all" (filed as #165).
- Not tried: a real Keychain dialog denial; the backoff is checked with
  a fake `security`.
This commit is contained in:
yetone
2026-10-16 17:36:57 +08:00
parent 47a8bb40d2
commit 0c35adbf03
4 changed files with 144 additions and 15 deletions
+7 -5
View File
@@ -13,11 +13,13 @@ An account is a Cursor access token. There are three ways to get one:
plugin polls `api2.cursor.sh/auth/poll` until the browser has signed in.
The account is named by its email (`DashboardService/GetMe`).
- **cursor-agent's sign-in**: takes the account `cursor-agent login`
signed in to. Its token is read on every request from where the CLI
keeps it: the macOS keychain (`cursor-access-token`), else its
`auth.json` (`~/.cursor/`, `$XDG_CONFIG_HOME/cursor/` or
`%APPDATA%\Cursor\`). The plugin never writes it; when it has less than
5 minutes left, `cursor-agent status` is run, which renews it.
signed in to. Its token is read from where the CLI keeps it: the macOS
keychain (`cursor-access-token`), else its `auth.json` (`~/.cursor/`,
`$XDG_CONFIG_HOME/cursor/` or `%APPDATA%\Cursor\`). A keychain read is
kept for 10 seconds, and one the keychain refused (the user said no to
its dialog) is not asked again for 10 minutes; signing in reads it
afresh. The plugin never writes it; when it has less than 5 minutes
left, `cursor-agent status` is run, which renews it.
- **Cursor API key**: a key from cursor.com/dashboard → Integrations. It is
exchanged for a token at `/auth/exchange_user_api_key`, as the CLI does
with `CURSOR_API_KEY`, and exchanged again when the token runs out.
+47 -9
View File
@@ -63,7 +63,7 @@ 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 ?? "") }))
resolve({ ok: !err, out: String(stdout ?? ""), code: typeof err?.code === "number" ? err.code : err ? -1 : 0 }))
})
}
@@ -117,12 +117,48 @@ function authFile() {
return join(process.env.XDG_CONFIG_HOME || join(home, ".config"), "cursor", "auth.json")
}
// 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.
async function cliToken() {
// written. fresh reads the Keychain whatever was read last.
async function cliToken(fresh = false) {
if (GOOS === "darwin") {
const r = await run("security", ["find-generic-password", "-s", "cursor-access-token", "-a", "cursor-user", "-w"])
if (r.ok && r.out.trim()) return r.out.trim()
const t = await keychainToken(fresh)
if (t) return t
}
try {
return JSON.parse(await readFile(authFile(), "utf8"))?.accessToken ?? ""
@@ -163,7 +199,7 @@ async function cliTokenNow() {
if (exe) {
cliRefresh ??= run(exe, ["status"], { timeout: 30_000 }).finally(() => (cliRefresh = null))
await cliRefresh
tok = await cliToken()
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`")
@@ -332,7 +368,7 @@ async function cliSignIn() {
instructions: "Uses the account `cursor-agent login` signed in to.",
method: "auto",
async callback() {
const tok = await cliToken()
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" }
@@ -1209,7 +1245,9 @@ function conversation(chat, tools) {
pending.splice(i, 1)
const text = textOf(m.content)
size += text.length
results.push(result(id, text, false))
// a failed tool's result says so, as the built-in's cursorResult
// told Cursor isError
results.push(result(id, text, m.is_error === true || m.isError === true))
}
continue
}
@@ -2828,4 +2866,4 @@ export async function CursorAuthPlugin() {
}
// for tests
export const _internal = { nativeTransport, onDemandOf,resetH1: () => (h1Until = 0), onH1: () => Date.now() < h1Until, 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 = { keychain, keychainToken, nativeTransport, onDemandOf,resetH1: () => (h1Until = 0), onH1: () => Date.now() < h1Until, 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 }
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-cursor-auth",
"version": "0.2.17",
"version": "0.2.18",
"description": "Cursor subscriptions (Pro, Pro+, Ultra, Teams) in OpenCode and magpie, through the API cursor-agent talks to",
"type": "module",
"main": "./index.mjs",
+89
View File
@@ -0,0 +1,89 @@
// What magpie's built-in Cursor did that the plugin does too, ahead of the
// built-in's retirement: a failed tool result tells Cursor isError
// (internal/gateway/cursor.go, cursorResult), and the Keychain is read as
// cursorKeychainToken reads it (internal/provider/cursor.go; magpie #746,
// #2408).
import "./nonet.mjs" // first: no request leaves this machine
import { afterEach, expect, test } from "bun:test"
import { _internal } from "./index.mjs"
const { conversation, keychain, keychainToken } = _internal
const call = (id) => ({ role: "assistant", content: "", tool_calls: [{ id, type: "function", function: { name: "bash", arguments: "{}" } }] })
const results = (chat) =>
conversation(chat, []).msgs.map((b) => JSON.parse(b.toString())).filter((m) => m.role === "tool").flatMap((m) => m.content)
test("a tool result marked is_error tells Cursor isError on the stateless path; a good one doesn't", () => {
const got = results({
messages: [
{ role: "user", content: "go" },
call("call_a"),
{ role: "tool", tool_call_id: "call_a", content: "exit status 1", is_error: true },
call("call_b"),
{ role: "tool", tool_call_id: "call_b", content: "ok" },
{ role: "user", content: "and?" },
],
})
expect(got.map((r) => [r.toolCallId, r.isError === true])).toEqual([["call_a", true], ["call_b", false]])
})
// a fake clock and `security`: each read counted, its answer set per test
let clock = 0
let reads = 0
let answer = { ok: true, out: "tok\n", code: 0 }
const real = { now: keychain.now, read: keychain.read }
const fake = () => {
clock = 1_000_000
reads = 0
Object.assign(keychain, { tok: "", at: 0, ask: 0, busy: null, now: () => clock, read: async () => (reads++, answer) })
}
afterEach(() => Object.assign(keychain, { tok: "", at: 0, ask: 0, busy: null }, real))
test("a token read from the Keychain is taken as it for ten seconds, then read again", async () => {
fake()
answer = { ok: true, out: "tok\n", code: 0 }
expect(await keychainToken()).toBe("tok")
clock += 9_999
expect(await keychainToken()).toBe("tok")
expect(reads).toBe(1)
clock += 2
expect(await keychainToken()).toBe("tok")
expect(reads).toBe(2)
})
test("callers at once share one `security` run", async () => {
fake()
answer = { ok: true, out: "tok", code: 0 }
const got = await Promise.all([keychainToken(), keychainToken(), keychainToken()])
expect(got).toEqual(["tok", "tok", "tok"])
expect(reads).toBe(1)
})
test("a refused read is not asked again for ten minutes; a fresh read asks", async () => {
fake()
answer = { ok: false, out: "", code: 128 } // the user said no to the dialog
expect(await keychainToken()).toBe("")
clock += 9 * 60_000
expect(await keychainToken()).toBe("")
expect(reads).toBe(1)
clock += 60_001
answer = { ok: true, out: "tok", code: 0 }
expect(await keychainToken()).toBe("tok")
expect(reads).toBe(2)
// after a refusal, a sign-in (fresh) still reads at once
answer = { ok: false, out: "", code: 51 }
expect(await keychainToken(true)).toBe("")
answer = { ok: true, out: "tok2", code: 0 }
expect(await keychainToken(true)).toBe("tok2")
expect(reads).toBe(4)
})
test("no item (exit 44) is no refusal: asked again after ten seconds", async () => {
fake()
answer = { ok: false, out: "", code: 44 }
expect(await keychainToken()).toBe("")
clock += 10_001
answer = { ok: true, out: "tok", code: 0 }
expect(await keychainToken()).toBe("tok")
expect(reads).toBe(2)
})