@caph42/pi-cursor-provider 0.0.0-stage → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +23 -0
- package/README.md +147 -2
- package/package.json +43 -4
- package/src/auth.ts +272 -0
- package/src/client.ts +90 -0
- package/src/codec.ts +235 -0
- package/src/config.ts +76 -0
- package/src/index.ts +105 -0
- package/src/ledger.ts +292 -0
- package/src/models.ts +336 -0
- package/src/native-session.ts +958 -0
- package/src/pi-stream.ts +330 -0
- package/src/run.ts +1268 -0
- package/src/usage.ts +257 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 pi-magpie-cursor contributors
|
|
4
|
+
Copyright (c) 2026 magpie-community contributors
|
|
5
|
+
Copyright (c) 2026 Rahul Arya
|
|
6
|
+
|
|
7
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
8
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
9
|
+
in the Software without restriction, including without limitation the rights
|
|
10
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
11
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
12
|
+
furnished to do so, subject to the following conditions:
|
|
13
|
+
|
|
14
|
+
The above copyright notice and this permission notice shall be included in all
|
|
15
|
+
copies or substantial portions of the Software.
|
|
16
|
+
|
|
17
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
18
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
19
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
20
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
21
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
22
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
23
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,148 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @caph42/pi-cursor-provider
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Pi extension. Provider id: `cursor`. A turn is one `AgentService/Run` (HTTP/2, with HTTP/1.1 RunSSE + BidiAppend when HTTP/2 cannot open).
|
|
4
|
+
|
|
5
|
+
When this process still holds that Run, and the next turn's tool results use ids of the form `call_cursor_<hex>_<seg>_<i>`, those results are written to the open Run. If that owner is gone, the turn opens a new Run and sends the results as history. A stateless Run still closes after it returns tools. The same Pi session and the first user message keep a stable `conversation_id`.
|
|
6
|
+
|
|
7
|
+
Pi 扩展,provider id 为 `cursor`。每一回合是一条 `AgentService/Run`(默认 HTTP/2;HTTP/2 打不开时走 HTTP/1.1 的 RunSSE + BidiAppend)。同一进程仍持有这条 Run,且下一回合的工具结果 id 为 `call_cursor_<hex>_<seg>_<i>` 时,结果写回这条未关闭的 Run。找不到 owner 时退回新的 Run,把结果放进历史。无主的 Run 在返回工具后仍会关闭。同一会话加上第一条用户消息对应稳定的 `conversation_id`。
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
Node.js ≥ 22. This package peers `@earendil-works/pi-ai` and `@earendil-works/pi-coding-agent` (Pi already provides them).
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
pi install npm:@caph42/pi-cursor-provider
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
From a local checkout, install or link that directory:
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
pi install ./path/to/pi-cursor-provider
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Leave `@rahularya01/pi-cursor` and `cursor-for-pi` disabled. Those packages register the same provider id, `cursor`.
|
|
24
|
+
|
|
25
|
+
## Sign in
|
|
26
|
+
|
|
27
|
+
Use one of these. `/cursor.doctor` reports which source matched and does not print the token.
|
|
28
|
+
|
|
29
|
+
1. `/login cursor` — browser PKCE, stored as Pi OAuth.
|
|
30
|
+
2. Environment variable `CURSOR_ACCESS_TOKEN`.
|
|
31
|
+
3. An existing cursor-agent `auth.json` (`accessToken` is read, never written):
|
|
32
|
+
- macOS: `~/.cursor/auth.json`
|
|
33
|
+
- Windows: `%APPDATA%/Cursor/auth.json`
|
|
34
|
+
- Linux and others: `$XDG_CONFIG_HOME/cursor/auth.json`, or `~/.config/cursor/auth.json`
|
|
35
|
+
4. macOS keychain item `cursor-access-token`.
|
|
36
|
+
5. Cursor IDE state (`state.vscdb`, key `cursorAuth/accessToken`).
|
|
37
|
+
|
|
38
|
+
Then select a model:
|
|
39
|
+
|
|
40
|
+
```text
|
|
41
|
+
/model cursor/<id>
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Hide models
|
|
45
|
+
|
|
46
|
+
`/model` lists every model Cursor offers the account. To shorten it, put `cursor.json` beside Pi's config (`$PI_CODING_AGENT_DIR/cursor.json`, else `~/.pi/agent/cursor.json`):
|
|
47
|
+
|
|
48
|
+
```json
|
|
49
|
+
{ "hiddenModels": ["claude-*", "gpt-5", "cursor/gpt-5-mini"] }
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
A pattern matches the whole id `/model` shows (the part after `cursor/`), ignoring case. `*` stands for any run of characters; every other character, `?` included, is literal. A pattern without the `@300k` size suffix hides every context size of that model. A missing or malformed file hides nothing, and `/cursor.doctor` prints the patterns in force. Reopen `/model` to see the new list.
|
|
53
|
+
|
|
54
|
+
Pi resolves models through the provider's list, so a hidden model is also unselectable by id, and a session resumed on one falls back to another model with Pi's "model no longer exists" warning. A session already running on a hidden model keeps it until the model changes. `/cursor.usage` still classifies usage by every model the account has.
|
|
55
|
+
|
|
56
|
+
If resume must keep working for the scoped-away models, Pi's own `enabledModels` setting scopes `/model` without removing anything from the registry: `{ "enabledModels": ["cursor/*sonnet*"] }` opens the picker on that scope, and Tab still reaches the rest.
|
|
57
|
+
|
|
58
|
+
## How this relates to other Cursor packages
|
|
59
|
+
|
|
60
|
+
| Package | Role |
|
|
61
|
+
| --- | --- |
|
|
62
|
+
| `@rahularya01/pi-cursor` | Pi provider that keeps a long-lived HTTP/2 bridge, with checkpoint resume and a run journal. |
|
|
63
|
+
| `cursor-for-pi` | The same per-turn AgentService/Run protocol. `@caph42/pi-cursor-provider` is that port under the magpie-aligned package name. |
|
|
64
|
+
| `@magpie-community/opencode-cursor-auth` | Cursor auth and Run for the OpenCode / magpie host. This package speaks Pi `streamSimple`. |
|
|
65
|
+
|
|
66
|
+
## Usage
|
|
67
|
+
|
|
68
|
+
`/cursor.usage` prints the plan and the billing-period windows. The command reads the same credential as `/cursor.doctor`. If nothing is signed in, it warns and does not print a token.
|
|
69
|
+
|
|
70
|
+
The same report is exported from the package.
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
import { fetchUsage, formatUsage, onDemandOf } from "@caph42/pi-cursor-provider"
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
`fetchUsage(token, modelIds)` returns `{ plan?, windows, error? }`. `formatUsage` turns that into the text the command shows. `onDemandOf` reads a period payload and a hard-limit payload into `fixed`, `unlimited`, `disabled`, or `unavailable`.
|
|
77
|
+
|
|
78
|
+
Windows follow magpie, in this order.
|
|
79
|
+
|
|
80
|
+
- Cursor Models
|
|
81
|
+
- Other Models
|
|
82
|
+
- On-demand, when the account has a dollar limit or an open on-demand spend
|
|
83
|
+
- Grok Bot, or Grok Bot (trial), when the dashboard reports that allowance
|
|
84
|
+
- Total
|
|
85
|
+
|
|
86
|
+
Grok Bot is placed before an On-demand window that has no limit, and after one that has a limit. Total stays last.
|
|
87
|
+
|
|
88
|
+
```text
|
|
89
|
+
Plan: Pro
|
|
90
|
+
Cursor Models: 42% (resets 2026-11-01T00:00:00.000Z)
|
|
91
|
+
Other Models: 10%
|
|
92
|
+
On-demand: $1.23 / $10.00
|
|
93
|
+
Total: 35%
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
### Step usage (deferred ledger)
|
|
97
|
+
|
|
98
|
+
A finished Run reports token counts from `TurnEnded` when Cursor sends them. A tool step has no `TurnEnded` until results return on the same Run: after the Run closes, this package reads the dashboard's usage events (`GetFilteredUsageEvents`) by `conversation_id`, as magpie does.
|
|
99
|
+
|
|
100
|
+
Far from Cursor the event can land after the short poll. That step then reports 0 used and the conversation owes the event. Later steps collect it in the background. What a step collected of earlier steps is not added to its own `prompt_tokens` (Pi reads that as context fill); it is `usage.magpie_deferred` (`prompt_tokens`, `completion_tokens`, `cached_tokens`, `cache_write_tokens`). Pi ignores that field for context size.
|
|
101
|
+
|
|
102
|
+
A step that ends the turn waits for remaining debt. After three misses in a row for an account, steps stop waiting (retrying every tenth). Unreadable accounts (4xx on the events API) fall back to the previous estimate. Native finals also settle earlier debt into `magpie_deferred`, separately from the last call's share of `TurnEnded`.
|
|
103
|
+
|
|
104
|
+
## Native Run continuation
|
|
105
|
+
|
|
106
|
+
A native Run stays open in this process when the model returns tools. Each call id is `call_cursor_<hex>_<seg>_<i>`. The next turn in the same process resumes that Run and writes the matching tool results to it.
|
|
107
|
+
|
|
108
|
+
Resume happens only when every id in the trailing tool-result batch belongs to one live owner, and the history still matches that batch. Any of these opens a new stateless Run instead, and sends the results as history.
|
|
109
|
+
|
|
110
|
+
- The id is not a live handle.
|
|
111
|
+
- The process restarted, so the owner is gone.
|
|
112
|
+
- The history does not match the sealed batch.
|
|
113
|
+
- The owner is busy, expired, or near its lifetime deadline.
|
|
114
|
+
|
|
115
|
+
The stateless path still cancels the stream after tools. The native path does not.
|
|
116
|
+
|
|
117
|
+
## Transport
|
|
118
|
+
|
|
119
|
+
- Default: HTTP/2 `AgentService/Run` at the agent host from `ServerConfigService/GetServerConfig` (else the global agent URL).
|
|
120
|
+
- When HTTP/2 cannot open (no response head in 15s, ALPN / "h2 is not supported" / HTTP/2 protocol errors), the Run goes as Cursor's clients do without HTTP/2: `AgentService/RunSSE` down and `BidiService/BidiAppend` up over HTTP/1.1 on `api2.cursor.sh`. Blocked HTTP/2 keeps later Runs on HTTP/1.1 for 10 minutes; a plain connection failure leaves the next Run to try HTTP/2 again.
|
|
121
|
+
- A regional refusal refreshes GetServerConfig and retries once when the agent URL changed (or the failed attempt was already on HTTP/1.1). That refresh clears the HTTP/1.1 stickiness so the region's agent host can use HTTP/2 again.
|
|
122
|
+
- "Max Mode Required" retries once with Max Mode and remembers that model id for the process.
|
|
123
|
+
|
|
124
|
+
## Known gaps
|
|
125
|
+
|
|
126
|
+
Compared with magpie [`packages/cursor`](https://github.com/magpie-community/plugins/tree/main/packages/cursor), this package still does not include:
|
|
127
|
+
|
|
128
|
+
- Parked long-lived HTTP/2 bridge, checkpoint resume, and run journal (that is `@rahularya01/pi-cursor`'s model; this package stays per-turn Run + optional same-process native continuation).
|
|
129
|
+
- OpenCode chat-completions adapter surface (`X-Magpie-Cursor-Continuity` headers, AI SDK message shapes beyond what Pi `streamSimple` needs).
|
|
130
|
+
- Multi-account switching; web search and other Cursor-owned tools (refused like magpie).
|
|
131
|
+
- Client-side context compaction / summarization when the window fills (Pi or the host may compact before calling; this provider only maps Cursor's "input is too long" / context-length errors, same as magpie).
|
|
132
|
+
- Full empty-reply diagnostics (`emptyWhy` field inventory) and some magpie-only decode edge reporting.
|
|
133
|
+
- Browser / API-key exchange login paths that magpie implements for OpenCode (Pi uses `/login cursor` and the credential sources above).
|
|
134
|
+
|
|
135
|
+
## Development
|
|
136
|
+
|
|
137
|
+
```bash
|
|
138
|
+
npm install
|
|
139
|
+
npm run check
|
|
140
|
+
npm test
|
|
141
|
+
CURSOR_E2E=1 npm run test:e2e
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
`npm test` stays off the Cursor network (fetch is mocked where the dashboard is involved). `npm run test:e2e` hits a real Cursor account (cursor-agent `auth.json`, `CURSOR_ACCESS_TOKEN`, or `/login cursor`) and never prints the token. `codec.ts`, `run.ts`, `models.ts`, `client.ts`, `ledger.ts`, and `native-session.ts` keep their `// @ts-nocheck` magpie-port headers.
|
|
145
|
+
|
|
146
|
+
## License
|
|
147
|
+
|
|
148
|
+
MIT. The Run protocol comes from magpie [`packages/cursor`](https://github.com/magpie-community/plugins/tree/main/packages/cursor). Login patterns follow [pi-cursor](https://github.com/Rahularya01/pi-cursor).
|
package/package.json
CHANGED
|
@@ -1,6 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@caph42/pi-cursor-provider",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"description": "Cursor provider for Pi: one HTTP/2 AgentService/Run per turn (magpie-aligned).",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"keywords": [
|
|
8
|
+
"pi-package",
|
|
9
|
+
"pi-extension",
|
|
10
|
+
"cursor",
|
|
11
|
+
"magpie"
|
|
12
|
+
],
|
|
13
|
+
"engines": {
|
|
14
|
+
"node": ">=22"
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"src",
|
|
18
|
+
"LICENSE",
|
|
19
|
+
"README.md"
|
|
20
|
+
],
|
|
21
|
+
"main": "./src/index.ts",
|
|
22
|
+
"pi": {
|
|
23
|
+
"extensions": [
|
|
24
|
+
"./src/index.ts"
|
|
25
|
+
]
|
|
26
|
+
},
|
|
27
|
+
"scripts": {
|
|
28
|
+
"test": "node --experimental-strip-types --test test/*.ts",
|
|
29
|
+
"check": "tsc --noEmit",
|
|
30
|
+
"test:e2e": "CURSOR_E2E=1 node --experimental-strip-types --test test/e2e-live.ts"
|
|
31
|
+
},
|
|
32
|
+
"peerDependencies": {
|
|
33
|
+
"@earendil-works/pi-ai": "*",
|
|
34
|
+
"@earendil-works/pi-coding-agent": "*"
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"@earendil-works/pi-ai": "1.4.0",
|
|
38
|
+
"@earendil-works/pi-coding-agent": "1.4.0",
|
|
39
|
+
"@types/node": "^22.20.5",
|
|
40
|
+
"typescript": "5.9"
|
|
41
|
+
},
|
|
42
|
+
"publishConfig": {
|
|
43
|
+
"access": "public"
|
|
44
|
+
}
|
|
45
|
+
}
|
package/src/auth.ts
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cursor credentials for Pi.
|
|
3
|
+
*
|
|
4
|
+
* Login and the Pi / keychain / IDE lookups follow pi-cursor (MIT):
|
|
5
|
+
* https://github.com/Rahularya01/pi-cursor
|
|
6
|
+
* cursor-agent's auth.json is read the way magpie reads it, and never written.
|
|
7
|
+
* Browser sign-in is the deep-control PKCE flow, polled at api2.cursor.sh.
|
|
8
|
+
* Tokens are never written to logs.
|
|
9
|
+
*/
|
|
10
|
+
import { execFile, spawn } from "node:child_process"
|
|
11
|
+
import { createHash, randomUUID } from "node:crypto"
|
|
12
|
+
import { existsSync, readFileSync } from "node:fs"
|
|
13
|
+
import { homedir } from "node:os"
|
|
14
|
+
import { join } from "node:path"
|
|
15
|
+
import type { OAuthCredentials, OAuthLoginCallbacks } from "@earendil-works/pi-ai"
|
|
16
|
+
import { readStoredCredential } from "@earendil-works/pi-coding-agent"
|
|
17
|
+
import { API, clientVersion } from "./client.ts"
|
|
18
|
+
|
|
19
|
+
const LOGIN_URL = "https://cursor.com/loginDeepControl"
|
|
20
|
+
const POLL_URL = `${API}/auth/poll`
|
|
21
|
+
const EXCHANGE_URL = `${API}/auth/exchange_user_api_key`
|
|
22
|
+
|
|
23
|
+
export type AuthSource = "environment" | "pi-oauth" | "cursor-agent" | "keychain" | "ide-state"
|
|
24
|
+
|
|
25
|
+
export interface ResolvedAuth {
|
|
26
|
+
token: string
|
|
27
|
+
source: AuthSource
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function trimmed(value: unknown): string {
|
|
31
|
+
return typeof value === "string" ? value.trim() : ""
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function plausible(token: string): boolean {
|
|
35
|
+
return token.length >= 20 && !/\s/.test(token) && !token.startsWith("$")
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** A token with no exp is kept. One whose exp has passed is not. */
|
|
39
|
+
function current(token: string): boolean {
|
|
40
|
+
if (!plausible(token)) return false
|
|
41
|
+
const exp = jwtExpiryMs(token)
|
|
42
|
+
return exp === 0 || exp > Date.now()
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function jwtExpiryMs(token: string): number {
|
|
46
|
+
const parts = token.split(".")
|
|
47
|
+
if (parts.length !== 3) return 0
|
|
48
|
+
try {
|
|
49
|
+
const payload = JSON.parse(Buffer.from(parts[1] ?? "", "base64url").toString("utf8")) as { exp?: unknown }
|
|
50
|
+
return typeof payload.exp === "number" && payload.exp > 0 ? payload.exp * 1000 : 0
|
|
51
|
+
} catch {
|
|
52
|
+
return 0
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Refresh a few minutes early. Fall back to an hour when the token has no exp. */
|
|
57
|
+
export function expiresAt(token: string): number {
|
|
58
|
+
const exp = jwtExpiryMs(token)
|
|
59
|
+
if (!exp) return Date.now() + 60 * 60 * 1000
|
|
60
|
+
return Math.max(exp - 5 * 60 * 1000, Date.now() + 60 * 1000)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function sleep(ms: number, signal?: AbortSignal): Promise<void> {
|
|
64
|
+
return new Promise((resolve, reject) => {
|
|
65
|
+
if (signal?.aborted) {
|
|
66
|
+
reject(new Error("Cursor sign-in cancelled"))
|
|
67
|
+
return
|
|
68
|
+
}
|
|
69
|
+
const timer = setTimeout(resolve, ms)
|
|
70
|
+
signal?.addEventListener(
|
|
71
|
+
"abort",
|
|
72
|
+
() => {
|
|
73
|
+
clearTimeout(timer)
|
|
74
|
+
reject(new Error("Cursor sign-in cancelled"))
|
|
75
|
+
},
|
|
76
|
+
{ once: true },
|
|
77
|
+
)
|
|
78
|
+
})
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function openBrowser(url: string) {
|
|
82
|
+
try {
|
|
83
|
+
const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open"
|
|
84
|
+
const args = process.platform === "win32" ? ["/c", "start", "", url] : [url]
|
|
85
|
+
const child = spawn(command, args, { stdio: "ignore", detached: true })
|
|
86
|
+
child.on("error", () => {})
|
|
87
|
+
child.unref()
|
|
88
|
+
} catch {
|
|
89
|
+
// The URL is already on screen via onAuth.
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function securityPassword(service: string): Promise<string> {
|
|
94
|
+
if (process.platform !== "darwin") return Promise.resolve("")
|
|
95
|
+
return new Promise((resolve) => {
|
|
96
|
+
execFile(
|
|
97
|
+
"security",
|
|
98
|
+
["find-generic-password", "-s", service, "-a", "cursor-user", "-w"],
|
|
99
|
+
{ timeout: 2000 },
|
|
100
|
+
(err, stdout) => resolve(err ? "" : String(stdout ?? "").trim()),
|
|
101
|
+
)
|
|
102
|
+
})
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function ideDbPath(): string {
|
|
106
|
+
const home = homedir()
|
|
107
|
+
if (process.platform === "darwin") return join(home, "Library/Application Support/Cursor/User/globalStorage/state.vscdb")
|
|
108
|
+
if (process.platform === "win32") {
|
|
109
|
+
return join(process.env.APPDATA || join(home, "AppData", "Roaming"), "Cursor", "User", "globalStorage", "state.vscdb")
|
|
110
|
+
}
|
|
111
|
+
const config = process.env.XDG_CONFIG_HOME || join(home, ".config")
|
|
112
|
+
return join(config, "Cursor", "User", "globalStorage", "state.vscdb")
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async function ideToken(): Promise<string> {
|
|
116
|
+
const path = ideDbPath()
|
|
117
|
+
if (!existsSync(path)) return ""
|
|
118
|
+
try {
|
|
119
|
+
const mod = (await import("node:sqlite")) as {
|
|
120
|
+
DatabaseSync: new (filename: string, options: { readOnly: boolean }) => {
|
|
121
|
+
prepare(sql: string): { get(key: string): { value?: unknown } | undefined }
|
|
122
|
+
close(): void
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
const db = new mod.DatabaseSync(path, { readOnly: true })
|
|
126
|
+
try {
|
|
127
|
+
const row = db.prepare("SELECT value FROM ItemTable WHERE key = ?").get("cursorAuth/accessToken")
|
|
128
|
+
return trimmed(row?.value)
|
|
129
|
+
} finally {
|
|
130
|
+
db.close()
|
|
131
|
+
}
|
|
132
|
+
} catch {
|
|
133
|
+
return ""
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export interface CredentialLookup {
|
|
138
|
+
stored?: () => string
|
|
139
|
+
/** cursor-agent auth.json `accessToken`. Tests inject this; the default reads the file. */
|
|
140
|
+
cliAuth?: () => Promise<string> | string
|
|
141
|
+
keychain?: () => Promise<string> | string
|
|
142
|
+
ide?: () => Promise<string> | string
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** cursor-agent auth.json. Read-only. Darwin, Windows, and XDG paths differ. */
|
|
146
|
+
function cliAuthPath(): string {
|
|
147
|
+
const home = homedir()
|
|
148
|
+
if (process.platform === "darwin") return join(home, ".cursor", "auth.json")
|
|
149
|
+
if (process.platform === "win32") {
|
|
150
|
+
return join(process.env.APPDATA || join(home, "AppData", "Roaming"), "Cursor", "auth.json")
|
|
151
|
+
}
|
|
152
|
+
const config = process.env.XDG_CONFIG_HOME || join(home, ".config")
|
|
153
|
+
return join(config, "cursor", "auth.json")
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
async function cliAuthToken(): Promise<string> {
|
|
157
|
+
const path = cliAuthPath()
|
|
158
|
+
if (!existsSync(path)) return ""
|
|
159
|
+
try {
|
|
160
|
+
const raw = readFileSync(path, "utf8").replace(/^\uFEFF/, "")
|
|
161
|
+
const parsed = JSON.parse(raw) as { accessToken?: unknown }
|
|
162
|
+
return trimmed(parsed?.accessToken)
|
|
163
|
+
} catch {
|
|
164
|
+
return ""
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function storedToken(): string {
|
|
169
|
+
try {
|
|
170
|
+
const cred = readStoredCredential("cursor")
|
|
171
|
+
if (cred?.type === "oauth") return trimmed(cred.access)
|
|
172
|
+
} catch {
|
|
173
|
+
// Pi's auth store isn't available to this process.
|
|
174
|
+
}
|
|
175
|
+
return ""
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** CURSOR_ACCESS_TOKEN, Pi OAuth, cursor-agent auth.json, macOS keychain, then Cursor IDE state. */
|
|
179
|
+
export async function resolveAccessToken(opts?: {
|
|
180
|
+
apiKey?: string
|
|
181
|
+
env?: Record<string, string | undefined>
|
|
182
|
+
lookup?: CredentialLookup
|
|
183
|
+
}): Promise<ResolvedAuth | undefined> {
|
|
184
|
+
const envToken = trimmed(opts?.env?.CURSOR_ACCESS_TOKEN ?? process.env.CURSOR_ACCESS_TOKEN)
|
|
185
|
+
if (plausible(envToken)) return { token: envToken, source: "environment" }
|
|
186
|
+
const apiKey = trimmed(opts?.apiKey)
|
|
187
|
+
if (plausible(apiKey)) return { token: apiKey, source: "pi-oauth" }
|
|
188
|
+
const stored = opts?.lookup?.stored ? opts.lookup.stored() : storedToken()
|
|
189
|
+
if (current(stored)) return { token: stored, source: "pi-oauth" }
|
|
190
|
+
const cli = opts?.lookup?.cliAuth ? await opts.lookup.cliAuth() : await cliAuthToken()
|
|
191
|
+
if (current(cli)) return { token: cli, source: "cursor-agent" }
|
|
192
|
+
const keychain = opts?.lookup?.keychain ? await opts.lookup.keychain() : await securityPassword("cursor-access-token")
|
|
193
|
+
if (current(keychain)) return { token: keychain, source: "keychain" }
|
|
194
|
+
const ide = opts?.lookup?.ide ? await opts.lookup.ide() : await ideToken()
|
|
195
|
+
if (current(ide)) return { token: ide, source: "ide-state" }
|
|
196
|
+
return undefined
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export async function login(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {
|
|
200
|
+
const verifierBytes = new Uint8Array(32)
|
|
201
|
+
crypto.getRandomValues(verifierBytes)
|
|
202
|
+
const verifier = Buffer.from(verifierBytes).toString("base64url")
|
|
203
|
+
const challenge = createHash("sha256").update(verifier).digest("base64url")
|
|
204
|
+
const uuid = randomUUID()
|
|
205
|
+
const params = new URLSearchParams({ challenge, uuid, mode: "login", redirectTarget: "cli" })
|
|
206
|
+
const url = `${LOGIN_URL}?${params.toString()}`
|
|
207
|
+
callbacks.onAuth({
|
|
208
|
+
url,
|
|
209
|
+
instructions: "Sign in to Cursor in the browser. This finishes once the page confirms it.",
|
|
210
|
+
})
|
|
211
|
+
openBrowser(url)
|
|
212
|
+
const headers = {
|
|
213
|
+
"Content-Type": "application/json",
|
|
214
|
+
"x-cursor-client-version": await clientVersion(),
|
|
215
|
+
"x-cursor-client-type": "cli",
|
|
216
|
+
}
|
|
217
|
+
let errors = 0
|
|
218
|
+
for (let attempt = 0; attempt < 150; attempt++) {
|
|
219
|
+
const wait = Math.min(1000 * 1.2 ** attempt, 10_000)
|
|
220
|
+
await sleep(wait, callbacks.signal)
|
|
221
|
+
if (attempt > 0 && attempt % 8 === 0) callbacks.onProgress?.("Still waiting for the Cursor sign-in.")
|
|
222
|
+
let res: Response
|
|
223
|
+
try {
|
|
224
|
+
const signals = [AbortSignal.timeout(15_000)]
|
|
225
|
+
if (callbacks.signal) signals.push(callbacks.signal)
|
|
226
|
+
res = await fetch(`${POLL_URL}?uuid=${encodeURIComponent(uuid)}&verifier=${encodeURIComponent(verifier)}`, {
|
|
227
|
+
headers,
|
|
228
|
+
signal: AbortSignal.any(signals),
|
|
229
|
+
})
|
|
230
|
+
} catch {
|
|
231
|
+
if (callbacks.signal?.aborted) throw new Error("Cursor sign-in cancelled")
|
|
232
|
+
if (++errors >= 3) throw new Error("Couldn't reach Cursor to finish sign-in")
|
|
233
|
+
continue
|
|
234
|
+
}
|
|
235
|
+
if (res.status === 404) {
|
|
236
|
+
errors = 0
|
|
237
|
+
continue
|
|
238
|
+
}
|
|
239
|
+
if (!res.ok) {
|
|
240
|
+
if (res.status === 403 || ++errors >= 3) {
|
|
241
|
+
throw new Error(res.status === 403 ? "Cursor refused the sign-in (403)" : `Cursor sign-in failed (HTTP ${res.status})`)
|
|
242
|
+
}
|
|
243
|
+
continue
|
|
244
|
+
}
|
|
245
|
+
const body = (await res.json().catch(() => null)) as { accessToken?: unknown; refreshToken?: unknown } | null
|
|
246
|
+
const access = trimmed(body?.accessToken)
|
|
247
|
+
if (!access) throw new Error("Cursor sent back no access token")
|
|
248
|
+
const refresh = trimmed(body?.refreshToken)
|
|
249
|
+
return { access, refresh, expires: expiresAt(access) }
|
|
250
|
+
}
|
|
251
|
+
throw new Error("Cursor sign-in timed out")
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
export async function refresh(credentials: OAuthCredentials, signal?: AbortSignal): Promise<OAuthCredentials> {
|
|
255
|
+
const res = await fetch(EXCHANGE_URL, {
|
|
256
|
+
method: "POST",
|
|
257
|
+
headers: {
|
|
258
|
+
Authorization: `Bearer ${credentials.access}`,
|
|
259
|
+
"Content-Type": "application/json",
|
|
260
|
+
"connect-protocol-version": "1",
|
|
261
|
+
"x-cursor-client-type": "cli",
|
|
262
|
+
"x-cursor-client-version": await clientVersion(),
|
|
263
|
+
},
|
|
264
|
+
body: "{}",
|
|
265
|
+
signal,
|
|
266
|
+
})
|
|
267
|
+
if (!res.ok) throw new Error(`Cursor sign-in could not be refreshed (HTTP ${res.status})`)
|
|
268
|
+
const body = (await res.json().catch(() => null)) as { accessToken?: unknown; refreshToken?: unknown; access?: unknown; refresh?: unknown } | null
|
|
269
|
+
const access = trimmed(body?.accessToken) || trimmed(body?.access) || credentials.access
|
|
270
|
+
const nextRefresh = trimmed(body?.refreshToken) || trimmed(body?.refresh) || credentials.refresh
|
|
271
|
+
return { access, refresh: nextRefresh, expires: expiresAt(access) }
|
|
272
|
+
}
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cursor client version and Connect JSON calls.
|
|
3
|
+
*
|
|
4
|
+
* Ported from magpie's Cursor provider (MIT):
|
|
5
|
+
* https://github.com/magpie-community/plugins/tree/main/packages/cursor
|
|
6
|
+
*/
|
|
7
|
+
// @ts-nocheck
|
|
8
|
+
import { basename, dirname, join } from "node:path"
|
|
9
|
+
import { homedir, platform, tmpdir } from "node:os"
|
|
10
|
+
import { readdir, realpath, stat } from "node:fs/promises"
|
|
11
|
+
import { failure } from "./codec.ts"
|
|
12
|
+
|
|
13
|
+
export const API = "https://api2.cursor.sh"
|
|
14
|
+
export const AGENT = "https://agentn.global.api5.cursor.sh"
|
|
15
|
+
export const VERSION_FALLBACK = "2026.09.23-86fc751"
|
|
16
|
+
export const CALL = "CallDynamicTool"
|
|
17
|
+
export const NAMESPACE = "pi"
|
|
18
|
+
export const DEFAULT_CONTEXT = 200_000
|
|
19
|
+
export const MODELS_KEEP = 10 * 60 * 1000
|
|
20
|
+
export const GOOS = { win32: "windows" }[platform()] ?? platform()
|
|
21
|
+
export const tempDir = tmpdir
|
|
22
|
+
|
|
23
|
+
const exists = (p) => stat(p).then((s) => !s.isDirectory(), () => false)
|
|
24
|
+
|
|
25
|
+
async function cursorExecutable() {
|
|
26
|
+
const dirs = (process.env.PATH ?? "").split(GOOS === "windows" ? ";" : ":").filter(Boolean)
|
|
27
|
+
for (const name of ["cursor-agent", "agent"]) {
|
|
28
|
+
for (const d of dirs) {
|
|
29
|
+
const p = join(d, GOOS === "windows" ? name + ".exe" : name)
|
|
30
|
+
if (!(await exists(p))) continue
|
|
31
|
+
if (name === "cursor-agent") return p
|
|
32
|
+
if ((await realpath(p).catch(() => "")).includes("cursor-agent")) return p
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
const home = homedir()
|
|
36
|
+
for (const p of [join(home, ".local", "bin", "cursor-agent"), "/usr/local/bin/cursor-agent", "/opt/homebrew/bin/cursor-agent"])
|
|
37
|
+
if (await exists(p)) return p
|
|
38
|
+
return ""
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const VERSION_RE = /^\d{4}\.\d{2}\.\d{2}-[0-9a-f]+$/
|
|
42
|
+
let versionSaid = ""
|
|
43
|
+
|
|
44
|
+
/** "cli-<installed cursor-agent version>", or the fallback the API still accepts. */
|
|
45
|
+
export async function clientVersion() {
|
|
46
|
+
if (versionSaid) return versionSaid
|
|
47
|
+
let v = ""
|
|
48
|
+
const exe = await cursorExecutable()
|
|
49
|
+
if (exe) {
|
|
50
|
+
const d = basename(dirname(await realpath(exe).catch(() => exe)))
|
|
51
|
+
if (VERSION_RE.test(d)) v = d
|
|
52
|
+
}
|
|
53
|
+
if (!v) {
|
|
54
|
+
const dirs = [join(homedir(), ".local", "share", "cursor-agent", "versions")]
|
|
55
|
+
if (GOOS === "windows") dirs.push(join(process.env.LOCALAPPDATA ?? "", "cursor-agent", "versions"))
|
|
56
|
+
for (const dir of dirs)
|
|
57
|
+
for (const n of await readdir(dir).catch(() => [])) if (VERSION_RE.test(n) && n > v) v = n
|
|
58
|
+
}
|
|
59
|
+
versionSaid = "cli-" + (v || VERSION_FALLBACK)
|
|
60
|
+
return versionSaid
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export async function headersFor(tok) {
|
|
64
|
+
return {
|
|
65
|
+
"Content-Type": "application/json",
|
|
66
|
+
"Connect-Protocol-Version": "1",
|
|
67
|
+
...(tok ? { Authorization: `Bearer ${tok}` } : {}),
|
|
68
|
+
"x-cursor-client-version": await clientVersion(),
|
|
69
|
+
"x-cursor-client-type": "cli",
|
|
70
|
+
"x-ghost-mode": "true",
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Connect unary call in JSON. */
|
|
75
|
+
export async function unary(base, path, tok, body = {}, timeout = 15_000) {
|
|
76
|
+
const res = await fetch(base + "/" + path, {
|
|
77
|
+
method: "POST",
|
|
78
|
+
headers: await headersFor(tok),
|
|
79
|
+
body: JSON.stringify(body),
|
|
80
|
+
signal: AbortSignal.timeout(timeout),
|
|
81
|
+
})
|
|
82
|
+
const text = await res.text()
|
|
83
|
+
if (!res.ok) {
|
|
84
|
+
const f = failure(res.status, text)
|
|
85
|
+
const e = new Error(f.message)
|
|
86
|
+
e.status = f.status
|
|
87
|
+
throw e
|
|
88
|
+
}
|
|
89
|
+
return JSON.parse(text || "{}")
|
|
90
|
+
}
|