@offbynan/pi-cursor-provider 0.2.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 +21 -0
- package/README.md +194 -0
- package/auth.ts +165 -0
- package/cursor-models-raw.json +583 -0
- package/h2-bridge.mjs +175 -0
- package/index.ts +714 -0
- package/package.json +58 -0
- package/proto/agent_pb.ts +15294 -0
- package/proxy.ts +2761 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Netanel Draiman
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
# pi-cursor-provider
|
|
2
|
+
|
|
3
|
+
> **This fork improves on the upstream in three areas:** image support, correct `pi -p` exit behaviour, and removal of dead eviction code. See the sections below for details.
|
|
4
|
+
|
|
5
|
+
[](https://www.npmjs.com/package/@offbynan/pi-cursor-provider)
|
|
6
|
+
|
|
7
|
+
[Pi](https://github.com/badlogic/pi-mono) extension that provides access to [Cursor](https://cursor.com) models via OAuth authentication and a local OpenAI-compatible proxy.
|
|
8
|
+
|
|
9
|
+
Forked from [ndraiman/pi-cursor-provider](https://github.com/ndraiman/pi-cursor-provider).
|
|
10
|
+
|
|
11
|
+
## Changes vs upstream
|
|
12
|
+
|
|
13
|
+
### Image support
|
|
14
|
+
|
|
15
|
+
This fork extends the proxy to handle images in OpenAI-style `image_url` content parts:
|
|
16
|
+
|
|
17
|
+
- **Base64 images** — `data:image/png;base64,...` payloads are extracted from the request, stored as blobs in Cursor's protobuf format, and forwarded to the upstream API.
|
|
18
|
+
- **Multi-turn state** — images are tracked per conversation turn and threaded correctly through session checkpoints, forks, and resumes.
|
|
19
|
+
- **Transparent to callers** — no API changes; just include standard `image_url` content parts in your messages as you would with any OpenAI-compatible client.
|
|
20
|
+
|
|
21
|
+
The upstream repo does not support images at all — they are silently ignored or cause request failures. This fork handles them properly end-to-end.
|
|
22
|
+
|
|
23
|
+
### `pi -p` exit fix
|
|
24
|
+
|
|
25
|
+
The upstream repo causes `pi -p` (non-interactive mode) to hang indefinitely after printing a response. Two bugs were responsible:
|
|
26
|
+
|
|
27
|
+
1. **Empty end-stream body misclassified as error.** Cursor's Connect end-stream frame often has a 0-byte body. `JSON.parse("")` throws, so the proxy took the error path even on clean completions.
|
|
28
|
+
2. **Bridge never unref'd on error path.** `bridge.end()` and `bridge.unref()` were only called in the success branch. On the error path the h2-bridge child process stayed ref'd, blocking process exit.
|
|
29
|
+
|
|
30
|
+
This fork fixes both: empty and non-JSON end-stream bodies are treated as success, and the bridge is always unref'd regardless of the outcome.
|
|
31
|
+
|
|
32
|
+
### Removed dead eviction code
|
|
33
|
+
|
|
34
|
+
The upstream proxy included a 30-minute TTL eviction mechanism (`evictStaleConversations`, `CONVERSATION_TTL_MS`, `sessionScoped`, `lastAccessMs`). All conversations created by pi include a session ID, permanently exempting them from TTL eviction, so this code was never reachable. This fork removes it.
|
|
35
|
+
|
|
36
|
+
## How it works
|
|
37
|
+
|
|
38
|
+
```
|
|
39
|
+
pi → openai-completions → localhost:PORT/v1/chat/completions
|
|
40
|
+
↓
|
|
41
|
+
proxy.ts (HTTP server)
|
|
42
|
+
↓
|
|
43
|
+
h2-bridge.mjs (Node HTTP/2)
|
|
44
|
+
↓
|
|
45
|
+
api2.cursor.sh gRPC
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
1. **PKCE OAuth** — browser-based login to Cursor, no client secret needed
|
|
49
|
+
2. **Model discovery** — queries Cursor's `GetUsableModels` gRPC endpoint
|
|
50
|
+
3. **Local proxy** — translates OpenAI `/v1/chat/completions` to Cursor's protobuf/HTTP2 Connect protocol
|
|
51
|
+
4. **Tool routing** — rejects Cursor's native tools, exposes pi's tools via MCP
|
|
52
|
+
|
|
53
|
+
## Install
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
# Via pi install
|
|
57
|
+
pi install npm:@offbynan/pi-cursor-provider
|
|
58
|
+
|
|
59
|
+
# Or manually
|
|
60
|
+
git clone https://github.com/offbynan/pi-cursor-provider ~/.pi/agent/extensions/cursor-provider
|
|
61
|
+
cd ~/.pi/agent/extensions/cursor-provider
|
|
62
|
+
npm install
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## Usage
|
|
66
|
+
|
|
67
|
+
```
|
|
68
|
+
/login cursor # authenticate via browser
|
|
69
|
+
/model # select a Cursor model
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## Model Mapping
|
|
73
|
+
|
|
74
|
+
Cursor exposes many model variants that encode **effort level** (`low`, `medium`, `high`, `xhigh`, `max`, `none`) and **speed** (`-fast`) or **thinking** (`-thinking`) in the model ID. This extension deduplicates them so pi's reasoning effort setting controls the effort level.
|
|
75
|
+
|
|
76
|
+
### How it works
|
|
77
|
+
|
|
78
|
+
Each raw Cursor model ID is parsed into components:
|
|
79
|
+
|
|
80
|
+
```
|
|
81
|
+
{base}-{effort}[-fast|-thinking]
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Examples:
|
|
85
|
+
|
|
86
|
+
| Raw Cursor ID | Base | Effort | Variant |
|
|
87
|
+
| ------------------------------ | ------------------- | -------- | ----------- |
|
|
88
|
+
| `gpt-5.4-medium` | `gpt-5.4` | `medium` | — |
|
|
89
|
+
| `gpt-5.4-high-fast` | `gpt-5.4` | `high` | `-fast` |
|
|
90
|
+
| `claude-4.6-opus-max-thinking` | `claude-4.6-opus` | `max` | `-thinking` |
|
|
91
|
+
| `gpt-5.1-codex-max-high` | `gpt-5.1-codex-max` | `high` | — |
|
|
92
|
+
| `composer-2` | `composer-2` | — | — |
|
|
93
|
+
|
|
94
|
+
Models sharing the same `(base, variant)` with **≥2 effort levels** and a sensible default (`medium` or no-suffix) are collapsed into a single entry with `supportsReasoningEffort: true`. Pi's thinking level maps to the effort suffix:
|
|
95
|
+
|
|
96
|
+
| Pi Level | Cursor Suffix |
|
|
97
|
+
| --------- | ------------------------------- |
|
|
98
|
+
| `minimal` | `none` (if available) or `low` |
|
|
99
|
+
| `low` | `low` |
|
|
100
|
+
| `medium` | `medium` or no suffix (default) |
|
|
101
|
+
| `high` | `high` |
|
|
102
|
+
| `xhigh` | `max` (Claude) or `xhigh` (GPT) |
|
|
103
|
+
|
|
104
|
+
The proxy inserts the effort before `-fast`/`-thinking`:
|
|
105
|
+
|
|
106
|
+
```
|
|
107
|
+
pi selects: gpt-5.4-fast + effort: high → Cursor receives: gpt-5.4-high-fast
|
|
108
|
+
pi selects: gpt-5.4 + effort: medium → Cursor receives: gpt-5.4-medium
|
|
109
|
+
pi selects: composer-2 + (no effort) → Cursor receives: composer-2
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
When a group is **collapsed**, the proxy registers one model with `supportsReasoningEffort: true` and an internal effort map (see table above).
|
|
113
|
+
|
|
114
|
+
**Collapsed** when Cursor returns either:
|
|
115
|
+
|
|
116
|
+
- **Multiple** effort suffixes for the same `(base, -fast, -thinking)` group, or
|
|
117
|
+
- **A single** variant whose parsed effort suffix is **non-empty** (for example only `claude-4.5-opus-high` is listed). The suffix is removed from the displayed ID so Pi's reasoning-effort setting supplies it.
|
|
118
|
+
|
|
119
|
+
**Left as-is** (raw Cursor ID on that row, `supportsReasoningEffort: false`) when the group has **one** variant and the parsed effort suffix is **empty**—typically IDs with no effort segment, such as `composer-2`, `gemini-3.1-pro`, or `kimi-k2.5`.
|
|
120
|
+
|
|
121
|
+
### Disabling the mapping
|
|
122
|
+
|
|
123
|
+
To see all raw Cursor model variants without dedup:
|
|
124
|
+
|
|
125
|
+
```bash
|
|
126
|
+
PI_CURSOR_RAW_MODELS=1 pi
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
## Session Management
|
|
130
|
+
|
|
131
|
+
The proxy maintains conversation state per pi session, enabling multi-turn conversations with Cursor models while preserving forks, tool continuations, and interruptions correctly.
|
|
132
|
+
|
|
133
|
+
### How it works
|
|
134
|
+
|
|
135
|
+
- **Session tracking** — pi's session ID is injected into requests via a `before_provider_request` hook. The proxy keys bridge state and stored conversation state from that real session ID.
|
|
136
|
+
- **Checkpoints** — Cursor returns a conversation checkpoint after completed turns. The proxy stores that checkpoint, plus the completed-turn count and a fingerprint of the completed structured history, and reuses it only when the incoming history still matches.
|
|
137
|
+
- **Session-scoped state** — real pi session state is kept in memory until explicit cleanup or process restart. Anonymous fallback state can still be TTL-evicted.
|
|
138
|
+
- **Lifecycle cleanup** — session state is cleaned up on pi lifecycle events such as session switch, fork, `/tree`, and shutdown.
|
|
139
|
+
|
|
140
|
+
### Tool continuations
|
|
141
|
+
|
|
142
|
+
When Cursor pauses for a tool call, the proxy keeps the live upstream bridge open and waits for pi to send the tool result on the next request. That tool result is sent back into the same in-flight Cursor run, so the tool continuation stays part of the original user turn instead of inflating completed history.
|
|
143
|
+
|
|
144
|
+
### Interruptions
|
|
145
|
+
|
|
146
|
+
If the client disconnects or interrupts a turn mid-stream, the proxy cancels the upstream Cursor run and does **not** commit the pending checkpoint. Checkpoints are only committed after a turn finishes successfully.
|
|
147
|
+
|
|
148
|
+
### Session fork
|
|
149
|
+
|
|
150
|
+
When you navigate back in pi's session tree and branch from an earlier point, the proxy discards the stored checkpoint whenever the completed history no longer matches the stored checkpoint metadata. That includes both:
|
|
151
|
+
|
|
152
|
+
- completed turn count mismatches, and
|
|
153
|
+
- same-depth branch changes detected via completed-history fingerprint mismatch.
|
|
154
|
+
|
|
155
|
+
After discarding a stale checkpoint, the proxy reconstructs proper protobuf conversation turns from the message history pi sends, so Cursor sees the actual conversation structure at the fork point.
|
|
156
|
+
|
|
157
|
+
### Session resume
|
|
158
|
+
|
|
159
|
+
Conversation state is stored in memory. If the proxy restarts, checkpoints are lost. On the next request, pi sends the full conversation history, and the proxy reconstructs structured protobuf turns from that history instead of relying on an inline plaintext fallback.
|
|
160
|
+
|
|
161
|
+
That reconstruction preserves:
|
|
162
|
+
|
|
163
|
+
- assistant messages
|
|
164
|
+
- tool calls
|
|
165
|
+
- tool results
|
|
166
|
+
- final assistant text after tool results
|
|
167
|
+
|
|
168
|
+
## Requirements
|
|
169
|
+
|
|
170
|
+
- [Pi](https://github.com/badlogic/pi-mono)
|
|
171
|
+
- [Node.js](https://nodejs.org) >= 18
|
|
172
|
+
- Active [Cursor](https://cursor.com) subscription
|
|
173
|
+
|
|
174
|
+
## Development
|
|
175
|
+
|
|
176
|
+
```bash
|
|
177
|
+
npm install
|
|
178
|
+
npm test
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
## Debug log timeline
|
|
182
|
+
|
|
183
|
+
When `PI_CURSOR_PROVIDER_DEBUG=1` is enabled, the proxy writes timestamped JSONL logs to `os.tmpdir()` by default. You can turn a log into a compact human-readable timeline with:
|
|
184
|
+
|
|
185
|
+
```bash
|
|
186
|
+
npm run debug:timeline -- --latest
|
|
187
|
+
npm run debug:timeline -- /path/to/pi-cursor-provider-debug-2026-04-08T14-06-07-565Z-41184.log
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
Add `--json` if you want the parsed summary as JSON instead of formatted text.
|
|
191
|
+
|
|
192
|
+
## Credits
|
|
193
|
+
|
|
194
|
+
OAuth flow and gRPC proxy adapted from [opencode-cursor](https://github.com/ephraimduncan/opencode-cursor) by Ephraim Duncan.
|
package/auth.ts
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cursor OAuth authentication via PKCE.
|
|
3
|
+
*
|
|
4
|
+
* Flow:
|
|
5
|
+
* 1. Generate PKCE verifier + challenge
|
|
6
|
+
* 2. Open browser to cursor.com/loginDeepControl
|
|
7
|
+
* 3. Poll api2.cursor.sh/auth/poll until tokens arrive
|
|
8
|
+
* 4. Refresh via api2.cursor.sh/auth/exchange_user_api_key
|
|
9
|
+
*
|
|
10
|
+
* Based on https://github.com/ephraimduncan/opencode-cursor by Ephraim Duncan.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const CURSOR_LOGIN_URL = "https://cursor.com/loginDeepControl";
|
|
14
|
+
const CURSOR_POLL_URL = "https://api2.cursor.sh/auth/poll";
|
|
15
|
+
const CURSOR_REFRESH_URL = "https://api2.cursor.sh/auth/exchange_user_api_key";
|
|
16
|
+
|
|
17
|
+
const POLL_MAX_ATTEMPTS = 150;
|
|
18
|
+
const POLL_BASE_DELAY = 1000;
|
|
19
|
+
const POLL_MAX_DELAY = 10_000;
|
|
20
|
+
const POLL_BACKOFF_MULTIPLIER = 1.2;
|
|
21
|
+
|
|
22
|
+
// ── PKCE ──
|
|
23
|
+
|
|
24
|
+
async function generatePKCE(): Promise<{ verifier: string; challenge: string }> {
|
|
25
|
+
const verifierBytes = new Uint8Array(96);
|
|
26
|
+
crypto.getRandomValues(verifierBytes);
|
|
27
|
+
const verifier = Buffer.from(verifierBytes).toString("base64url");
|
|
28
|
+
|
|
29
|
+
const data = new TextEncoder().encode(verifier);
|
|
30
|
+
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
|
|
31
|
+
const challenge = Buffer.from(hashBuffer).toString("base64url");
|
|
32
|
+
|
|
33
|
+
return { verifier, challenge };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// ── Login params ──
|
|
37
|
+
|
|
38
|
+
export interface CursorAuthParams {
|
|
39
|
+
verifier: string;
|
|
40
|
+
challenge: string;
|
|
41
|
+
uuid: string;
|
|
42
|
+
loginUrl: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export async function generateCursorAuthParams(): Promise<CursorAuthParams> {
|
|
46
|
+
const { verifier, challenge } = await generatePKCE();
|
|
47
|
+
const uuid = crypto.randomUUID();
|
|
48
|
+
|
|
49
|
+
const params = new URLSearchParams({
|
|
50
|
+
challenge,
|
|
51
|
+
uuid,
|
|
52
|
+
mode: "login",
|
|
53
|
+
redirectTarget: "cli",
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
const loginUrl = `${CURSOR_LOGIN_URL}?${params.toString()}`;
|
|
57
|
+
return { verifier, challenge, uuid, loginUrl };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// ── Poll for auth completion ──
|
|
61
|
+
|
|
62
|
+
export async function pollCursorAuth(
|
|
63
|
+
uuid: string,
|
|
64
|
+
verifier: string,
|
|
65
|
+
): Promise<{ accessToken: string; refreshToken: string }> {
|
|
66
|
+
let delay = POLL_BASE_DELAY;
|
|
67
|
+
let consecutiveErrors = 0;
|
|
68
|
+
|
|
69
|
+
for (let attempt = 0; attempt < POLL_MAX_ATTEMPTS; attempt++) {
|
|
70
|
+
await new Promise((r) => setTimeout(r, delay));
|
|
71
|
+
|
|
72
|
+
try {
|
|
73
|
+
const response = await fetch(
|
|
74
|
+
`${CURSOR_POLL_URL}?uuid=${uuid}&verifier=${verifier}`,
|
|
75
|
+
);
|
|
76
|
+
|
|
77
|
+
if (response.status === 404) {
|
|
78
|
+
consecutiveErrors = 0;
|
|
79
|
+
delay = Math.min(delay * POLL_BACKOFF_MULTIPLIER, POLL_MAX_DELAY);
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
if (response.ok) {
|
|
84
|
+
const data = (await response.json()) as {
|
|
85
|
+
accessToken: string;
|
|
86
|
+
refreshToken: string;
|
|
87
|
+
};
|
|
88
|
+
return {
|
|
89
|
+
accessToken: data.accessToken,
|
|
90
|
+
refreshToken: data.refreshToken,
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
throw new Error(`Poll failed: ${response.status}`);
|
|
95
|
+
} catch (err) {
|
|
96
|
+
consecutiveErrors++;
|
|
97
|
+
if (consecutiveErrors >= 3) {
|
|
98
|
+
throw new Error(
|
|
99
|
+
"Too many consecutive errors during Cursor auth polling",
|
|
100
|
+
);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
throw new Error("Cursor authentication polling timeout");
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// ── Token refresh ──
|
|
109
|
+
|
|
110
|
+
export interface CursorCredentials {
|
|
111
|
+
access: string;
|
|
112
|
+
refresh: string;
|
|
113
|
+
expires: number;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export async function refreshCursorToken(
|
|
117
|
+
refreshToken: string,
|
|
118
|
+
): Promise<CursorCredentials> {
|
|
119
|
+
const response = await fetch(CURSOR_REFRESH_URL, {
|
|
120
|
+
method: "POST",
|
|
121
|
+
headers: {
|
|
122
|
+
Authorization: `Bearer ${refreshToken}`,
|
|
123
|
+
"Content-Type": "application/json",
|
|
124
|
+
},
|
|
125
|
+
body: "{}",
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
if (!response.ok) {
|
|
129
|
+
const error = await response.text();
|
|
130
|
+
throw new Error(`Cursor token refresh failed: ${error}`);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const data = (await response.json()) as {
|
|
134
|
+
accessToken: string;
|
|
135
|
+
refreshToken: string;
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
return {
|
|
139
|
+
access: data.accessToken,
|
|
140
|
+
refresh: data.refreshToken || refreshToken,
|
|
141
|
+
expires: getTokenExpiry(data.accessToken),
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// ── JWT expiry extraction ──
|
|
146
|
+
|
|
147
|
+
export function getTokenExpiry(token: string): number {
|
|
148
|
+
try {
|
|
149
|
+
const parts = token.split(".");
|
|
150
|
+
if (parts.length !== 3 || !parts[1]) {
|
|
151
|
+
return Date.now() + 3600 * 1000;
|
|
152
|
+
}
|
|
153
|
+
const decoded = JSON.parse(
|
|
154
|
+
atob(parts[1].replace(/-/g, "+").replace(/_/g, "/")),
|
|
155
|
+
);
|
|
156
|
+
if (
|
|
157
|
+
decoded &&
|
|
158
|
+
typeof decoded === "object" &&
|
|
159
|
+
typeof decoded.exp === "number"
|
|
160
|
+
) {
|
|
161
|
+
return decoded.exp * 1000 - 5 * 60 * 1000;
|
|
162
|
+
}
|
|
163
|
+
} catch {}
|
|
164
|
+
return Date.now() + 3600 * 1000;
|
|
165
|
+
}
|