@caph42/pi-cursor-provider 0.5.0 → 0.5.2

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/CHANGELOG.md ADDED
@@ -0,0 +1,24 @@
1
+ # Changelog
2
+
3
+ ## 0.5.2
4
+
5
+ - The `cursor-fast` status is always published with `ctx.ui.setStatus`, not only when Pi's own footer is in use. A footer that renders extension statuses — including pi-ccline, which takes the only custom-footer slot on Pi 1.4 — now shows `fast: on/off/unavailable` instead of losing it. Cursor's own footer still filters that key out, so the inline badge never appears twice.
6
+
7
+ ## 0.5.1
8
+
9
+ - A stored login renews the way the Cursor IDE does: a `refresh_token` grant at `api2.cursor.sh/oauth/token`, using the stored refresh token rather than the access token. A session Cursor ends asks for `/login cursor` instead of reporting a bare HTTP status. Checked against the real service: the grant minted a new access token, and that token opened a Run, listed models, and read usage. Offline tests cover the grant, rotation, and the failures.
10
+ - `/cursor.doctor` shows the transport, the agent host, native owners, and the usage ledger, with UTC times. It prints no token, header, or token hash, and reading it changes nothing.
11
+ - `CURSOR_DEBUG=1` keeps an in-memory journal of each turn's decisions, which `/cursor.doctor` prints. It records retry, fallback, and failure reasons that were dropped before.
12
+ - A native Run that cannot be created names its reason instead of returning `null`. A history mismatch keeps the specific error as `detail`.
13
+ - A finished login wait removes its abort listener.
14
+ - `headerWaitMs` is the HTTP/2 header timer. Callers who omit it still wait 15 seconds.
15
+ - Cancelling a request aborts the Connect call. A late model catalog is not cached.
16
+ - A failed model refresh returns that credential's last catalog, or an empty list when it has none.
17
+ - Tool names, descriptions, and schemas cannot close the catalog tags.
18
+ - Offline tests cover assistant events, Run retries, and HTTP/2 stickiness.
19
+ - `run.ts` is split by seam: the agent host cache is `endpoint.ts`, the HTTP/1.1 fallback is `transport.ts`, chat encoding and `exec` are `protocol.ts`, a single Run (stateless or native) is `agent-run.ts`. `run.ts` keeps `runAnswer` and its retry rules, and it is typechecked now. The unused exec refusal counter is gone.
20
+
21
+ ## 0.3.0
22
+
23
+ - Pi provider for one HTTP/2 AgentService/Run per turn, with same-process native continuation, a deferred usage ledger, and an HTTP/1.1 fallback.
24
+ - The package entry is `src/index.ts`. Pi loads it. Plain Node does not.
package/README.md CHANGED
@@ -35,6 +35,8 @@ Use one of these. `/cursor.doctor` reports which source matched and does not pri
35
35
  4. macOS keychain item `cursor-access-token`.
36
36
  5. Cursor IDE state (`state.vscdb`, key `cursorAuth/accessToken`).
37
37
 
38
+ `/login cursor` stores a Pi OAuth credential. Renewal follows the Cursor IDE: a `refresh_token` grant at `api2.cursor.sh/oauth/token` with the stored refresh token, not the access token. When Cursor ends the session, the next turn asks you to run `/login cursor` again.
39
+
38
40
  Then select a model:
39
41
 
40
42
  ```text
@@ -71,13 +73,13 @@ Select a Cursor model, then use:
71
73
  /cursor.fast off
72
74
  ```
73
75
 
74
- With no argument, `/cursor.fast` shows the current status. In the TUI, type `/cursor.fast ` and press Tab to choose `on` or `off`; a unique prefix such as `of` completes to `off` without executing the command. You can still type `/cursor.fast status` explicitly to query the status. In the TUI, `fast: on`, `fast: off`, or `fast: unavailable` appears on the second footer row beside the model/thinking information. Other extension statuses retain their own row. RPC clients continue receiving the `cursor-fast` status text. Enabling fast preserves the selected model ID, context size, and thinking level. It requires an account-available fast variant at the same context and effective thinking parameters; unsupported combinations are rejected.
76
+ With no argument, `/cursor.fast` shows the current status. In the TUI, type `/cursor.fast ` and press Tab to choose `on` or `off`; a unique prefix such as `of` completes to `off` without executing the command. You can still type `/cursor.fast status` explicitly to query the status. In the TUI, `fast: on`, `fast: off`, or `fast: unavailable` appears on the second footer row beside the model/thinking information. Other extension statuses retain their own row. The same text is also published through `ctx.ui.setStatus`, so a footer that renders extension statuses — Pi's own footer, or pi-ccline's — still shows it when another extension owns the footer slot; Cursor's footer filters that key out, so it never appears twice. RPC clients continue receiving the `cursor-fast` status text. Enabling fast preserves the selected model ID, context size, and thinking level. It requires an account-available fast variant at the same context and effective thinking parameters; unsupported combinations are rejected.
75
77
 
76
78
  The setting defaults to off and belongs to the current model in the current session. Other models keep their own settings. Reloading or resuming that session restores the setting from its current branch; a new session starts with fast off. Changes apply to the next request and require the current response to finish first.
77
79
 
78
80
  If fast is enabled and a later thinking change or catalogue update removes support, the footer shows `fast: on (unavailable)` and requests report an error until you select a supported thinking level or run `/cursor.fast off`. The command does not add duplicate fast models to `/model`.
79
81
 
80
- The second-row display uses Pi 1.4's custom-footer slot and its default renderer. On other Pi versions it falls back to the standard status row until the footer adapter is verified. Extensions that replace the same footer slot can replace this layout; Cursor yields if another extension takes ownership.
82
+ The second-row display uses Pi 1.4's custom-footer slot and its default renderer. On other Pi versions it falls back to the standard status row until the footer adapter is verified. Extensions that replace the same footer slot can replace this layout; Cursor yields if another extension takes ownership. The `cursor-fast` status row is still set in that case, so a footer that renders extension statuses keeps showing the fast state; otherwise `/cursor.fast status` remains the source of truth.
81
83
 
82
84
  ## How this relates to other Cursor packages
83
85
 
@@ -97,6 +99,8 @@ The same report is exported from the package.
97
99
  import { fetchUsage, formatUsage, onDemandOf } from "@caph42/pi-cursor-provider"
98
100
  ```
99
101
 
102
+ Pi loads the package through `pi.extensions`, which points at `src/index.ts`. The import above also works under a TypeScript loader such as `tsx`, and under `node --experimental-strip-types` when the files are outside `node_modules`. Node does not strip types for files inside `node_modules`. A normal Node program that imports the installed package fails with `ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING`. `main` is the same TypeScript file Pi loads. It is not a compiled JavaScript entry.
103
+
100
104
  `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`.
101
105
 
102
106
  Windows follow magpie, in this order.
@@ -145,6 +149,22 @@ The stateless path still cancels the stream after tools. The native path does no
145
149
  - 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.
146
150
  - "Max Mode Required" retries once with Max Mode and remembers that model id for the process.
147
151
 
152
+ ## Doctor
153
+
154
+ `/cursor.doctor` shows what this process holds for Cursor. The report has these lines.
155
+
156
+ - The credential source and the client version. The token is never shown.
157
+ - The models `cursor.json` hides.
158
+ - The transport, HTTP/2 or HTTP/1.1. After HTTP/2 fails on this network, Runs stay on HTTP/1.1 until the time shown.
159
+ - This account's agent host, without its path, and when GetServerConfig is asked again.
160
+ - Max-mode models this process learned.
161
+ - Native owners. Each line gives the state, model, tool rounds, and lifetime deadline, and says whether the owner belongs to this account. Complete owners kept for replay are listed too.
162
+ - The usage ledger, as counts of Runs owed, usage misses in a row, and accounts whose usage events Cursor refuses.
163
+
164
+ "This account" is the token `/cursor.doctor` resolves, the same way `/cursor.usage` does. The doctor does not refresh OAuth. A token near expiry may be refreshed by the next turn, so until then the doctor can name the account that token had. Every time is UTC, written `HH:MM:SSZ`. No line holds a token, an authorization header, or a hash of a token. Reading the report changes nothing and sends no request.
165
+
166
+ Start Pi with `CURSOR_DEBUG=1` to keep a decision journal. The doctor then lists the last 16 turns, oldest first, with what each turn decided. That covers the agent host lookup, HTTP/2 or HTTP/1.1, whether the turn went native and why not, why a native owner ended, region and max-mode retries, why the turn failed, and usage reads that failed or were refused. A decision that repeats shows once with a count. A turn keeps 32 decisions and counts the rest. The journal lives in memory. Nothing is written to the terminal, a file, or the session. Without the variable nothing is recorded. Pi reads `CURSOR_DEBUG` at startup, and `0`, `false`, `off`, and `no` leave the journal off.
167
+
148
168
  ## Known gaps
149
169
 
150
170
  Compared with magpie [`packages/cursor`](https://github.com/magpie-community/plugins/tree/main/packages/cursor), this package still does not include:
@@ -165,8 +185,10 @@ npm test
165
185
  CURSOR_E2E=1 npm run test:e2e
166
186
  ```
167
187
 
168
- `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.
188
+ `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. The checker reads `client.ts` and `run.ts`. `codec.ts`, `ledger.ts`, `models.ts`, and `native-session.ts` still keep their `// @ts-nocheck` magpie-port headers.
189
+
190
+ The renewal grant is checked against the real service: `POST api2.cursor.sh/oauth/token` answered with a new access token, and that token listed models, read usage, and completed a Run. `npm test` covers the request shape, the rotation, and the failures offline; how the server itself answers still needs a live check.
169
191
 
170
192
  ## License
171
193
 
172
- 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).
194
+ 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). Session renewal follows [oh-my-pi](https://github.com/can1357/oh-my-pi).
package/package.json CHANGED
@@ -1,8 +1,16 @@
1
1
  {
2
2
  "name": "@caph42/pi-cursor-provider",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
4
4
  "description": "Cursor provider for Pi: one HTTP/2 AgentService/Run per turn (magpie-aligned).",
5
5
  "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/Caph-dev/pi-cursor-provider.git"
9
+ },
10
+ "homepage": "https://github.com/Caph-dev/pi-cursor-provider#readme",
11
+ "bugs": {
12
+ "url": "https://github.com/Caph-dev/pi-cursor-provider/issues"
13
+ },
6
14
  "type": "module",
7
15
  "keywords": [
8
16
  "pi-package",
@@ -16,7 +24,8 @@
16
24
  "files": [
17
25
  "src",
18
26
  "LICENSE",
19
- "README.md"
27
+ "README.md",
28
+ "CHANGELOG.md"
20
29
  ],
21
30
  "main": "./src/index.ts",
22
31
  "pi": {
@@ -27,7 +36,8 @@
27
36
  "scripts": {
28
37
  "test": "node --experimental-strip-types --test test/*.ts",
29
38
  "check": "tsc --noEmit",
30
- "test:e2e": "CURSOR_E2E=1 node --experimental-strip-types --test test/e2e-live.ts"
39
+ "test:e2e": "CURSOR_E2E=1 node --experimental-strip-types --test test/e2e-live.ts",
40
+ "prepublishOnly": "npm run check && npm test"
31
41
  },
32
42
  "peerDependencies": {
33
43
  "@earendil-works/pi-ai": "*",
@@ -0,0 +1,430 @@
1
+ /**
2
+ * Ported from magpie's Cursor provider (MIT):
3
+ * https://github.com/magpie-community/plugins/tree/main/packages/cursor
4
+ */
5
+ import { randomUUID } from "node:crypto"
6
+ import http2 from "node:http2"
7
+ import { EMPTY, failure, frame, frames, pb } from "./codec.ts"
8
+ import { clientVersion } from "./client.ts"
9
+ import { canRead, ledger, owe, STEP_WAIT, usageKey } from "./ledger.ts"
10
+ import { NATIVE_LIMITS, NativeSessionError, nativeSessions } from "./native-session.ts"
11
+ import { buildRun, decode, exec, usageOf, type BlobStore, type ChatTool, type Conversation, type Frame, type ModelParam, type Payload, type RunError, type RunEvent } from "./protocol.ts"
12
+ import { cancelledOpen, open, type Connect, type RunStream } from "./transport.ts"
13
+ import { trace } from "./trace.ts"
14
+
15
+ export type RunArgs = {
16
+ tok: string
17
+ base: string
18
+ id: string
19
+ maxMode: boolean
20
+ params: readonly ModelParam[]
21
+ tools: readonly ChatTool[]
22
+ conv: Conversation
23
+ /** "" without a session: the Run gets an id of its own. */
24
+ convID: string
25
+ signal?: AbortSignal
26
+ connect?: Connect
27
+ onResponse?: (response: { status: number; headers: Record<string, string> }) => unknown
28
+ onPayload?: (payload: Payload) => unknown
29
+ headers?: Record<string, string | null | undefined>
30
+ headerWaitMs?: number
31
+ toolIdleMs?: number
32
+ }
33
+
34
+ /** A Run's events, or the error it ended on. h1: the Run went over HTTP/1.1. */
35
+ export type RunResult =
36
+ | { error: RunError & { bodyCut?: boolean; retentionIneligible?: boolean }; h1?: boolean; conversationId?: undefined; events?: undefined }
37
+ | { error?: undefined; conversationId: string; h1?: boolean; events: AsyncIterable<RunEvent> }
38
+
39
+ export type Prepared = { owner: NativeOwner } | { owner?: undefined; fallback?: string }
40
+
41
+ type Thrown = { status?: number; message?: string }
42
+
43
+ type SegmentEvents = {
44
+ next(): Promise<IteratorResult<RunEvent>>
45
+ return(): Promise<IteratorResult<RunEvent>>
46
+ [Symbol.asyncIterator](): SegmentEvents
47
+ }
48
+
49
+ type NativeTransport = {
50
+ outbound: { bytes: number; messages: number }
51
+ send(message: Buffer): void
52
+ room(size: number): Promise<void>
53
+ close(): void
54
+ }
55
+
56
+ type NativeAccounting = {
57
+ started(): void
58
+ settle(): Promise<unknown>
59
+ delivered(): void
60
+ abandon(): void
61
+ }
62
+
63
+ type NativeOwner = {
64
+ accounting?: NativeAccounting
65
+ chatTools?: readonly ChatTool[]
66
+ pumpTask?: Promise<void>
67
+ readonly error?: RunError & { retentionIneligible?: boolean }
68
+ readonly ac: AbortController
69
+ readonly limits: typeof NATIVE_LIMITS
70
+ readonly segments: number
71
+ readonly finalUsage?: unknown
72
+ attach(signal?: AbortSignal): void
73
+ fail(error: { status: number; message?: string }): void
74
+ bind(transport: NativeTransport, blobs: BlobStore, estimate: number): void
75
+ send(message: Buffer): void
76
+ pump(stream: AsyncIterable<Frame>): Promise<void>
77
+ response(): { events: SegmentEvents }
78
+ resume(prepared: object, signal?: AbortSignal): { events: SegmentEvents }
79
+ cancel(message: string): Promise<void>
80
+ delivered(): void
81
+ }
82
+
83
+ export async function startRun(prepared: Prepared, args: RunArgs): Promise<RunResult> {
84
+ const { id, maxMode, params, signal } = args
85
+ const made = nativeSessions.create(prepared, { id, maxMode, params }, { pb, exec, usageOf, failure, trace })
86
+ const native: NativeOwner | null = made.fallback ? null : made
87
+ trace?.note("native", native ? { path: "created" } : { path: "declined", fallback: made.fallback, detail: made.detail })
88
+ let response = native ? await runNative({ ...args, native }) : await runOnce(args)
89
+ if (response.error?.retentionIneligible && !signal?.aborted) {
90
+ trace?.note("native", { path: "abandoned", error: response.error })
91
+ response = await runOnce(args)
92
+ }
93
+ return response
94
+ }
95
+
96
+ /** Writes the caller's tool results to the native Run that asked for them. Throws when the owner refuses them. */
97
+ export function resumeRun(prepared: { owner: NativeOwner }, estimate: number, signal?: AbortSignal): AsyncIterable<RunEvent> {
98
+ const resumed = prepared.owner.resume({ ...prepared, estimate }, signal)
99
+ trace?.note("native", { path: "resumed" })
100
+ return withDelivery(prepared.owner, resumed.events)
101
+ }
102
+
103
+ async function runOnce({ tok, base, id, tools, conv, convID, signal, maxMode, params, connect, onResponse, onPayload, headers, headerWaitMs, toolIdleMs }: RunArgs): Promise<RunResult> {
104
+ const cid = convID || randomUUID()
105
+ const since = Date.now()
106
+ const book = ledger(tok, cid, since, signal, !!convID)
107
+ let modelId = id
108
+ if (onPayload) {
109
+ const replaced = await onPayload({ model: modelId, maxMode: !!maxMode, params, conversationId: cid, tools: tools.map((t) => t.name) })
110
+ if (replaced && typeof replaced === "object" && !Buffer.isBuffer(replaced) && "model" in replaced && typeof replaced.model === "string" && replaced.model) {
111
+ modelId = replaced.model
112
+ }
113
+ }
114
+ const { first, blobs } = buildRun(conv.msgs, conv.last, tools, modelId, cid, { maxMode, params })
115
+ const version = await clientVersion()
116
+ const o = await open({ base, tok, headers, version, signal, connect, headerWaitMs })
117
+ if (o.error) return book.done(), { ...o, h1: !!o.h1 }
118
+ if (onResponse) await onResponse({ status: o.status, headers: o.headers ?? {} })
119
+ const { session, req } = o
120
+ let closed = false
121
+ const send = (msg: Buffer) => {
122
+ if (!closed && !req.destroyed && req.writable) req.write(frame(msg))
123
+ }
124
+ const heartbeat = setInterval(() => send(pb().bytes(7, EMPTY).done()), 5000)
125
+ heartbeat.unref?.()
126
+ const close = () => {
127
+ if (closed) return
128
+ closed = true
129
+ clearInterval(heartbeat)
130
+ try {
131
+ req.close(http2.constants.NGHTTP2_CANCEL)
132
+ } catch {}
133
+ try {
134
+ session.close()
135
+ } catch {}
136
+ setTimeout(() => {
137
+ try {
138
+ session.destroy()
139
+ } catch {}
140
+ }, 1000).unref?.()
141
+ }
142
+ signal?.addEventListener("abort", close, { once: true })
143
+ if (signal?.aborted) {
144
+ close()
145
+ book.done()
146
+ return cancelledOpen()
147
+ }
148
+ send(first)
149
+ if (o.status < 200 || o.status > 299) {
150
+ const chunks: Buffer[] = []
151
+ let bodyCut = false
152
+ try {
153
+ for await (const c of req) chunks.push(c)
154
+ } catch {
155
+ bodyCut = true
156
+ }
157
+ close()
158
+ book.done()
159
+ const error = failure(o.status, Buffer.concat(chunks).toString("utf8").slice(0, 1 << 20))
160
+ return { error: bodyCut ? { ...error, bodyCut } : error, h1: !!o.h1 }
161
+ }
162
+ const it = decode(frames(req), {
163
+ send,
164
+ blobs,
165
+ tools,
166
+ estimate: conv.estimate,
167
+ close,
168
+ stepUsage: book.own,
169
+ owedUsage: book.owed,
170
+ toolIdleMs,
171
+ })
172
+ const wrapped = (async function* () {
173
+ try {
174
+ yield* it
175
+ } finally {
176
+ close()
177
+ book.done()
178
+ }
179
+ })()
180
+ const head = await wrapped.next()
181
+ if (head.done) return book.done(), { error: { status: 502, message: "an empty reply" }, h1: !!o.h1 }
182
+ if (head.value?.error) {
183
+ await wrapped.return?.()
184
+ return { error: head.value.error, h1: !!o.h1 }
185
+ }
186
+ return {
187
+ conversationId: cid,
188
+ h1: !!o.h1,
189
+ events: (async function* () {
190
+ yield head.value
191
+ yield* wrapped
192
+ })(),
193
+ }
194
+ }
195
+
196
+ function withDelivery(owner: { delivered(): void }, events: SegmentEvents): AsyncIterableIterator<RunEvent> {
197
+ const it = events[Symbol.asyncIterator]()
198
+ return {
199
+ async next() {
200
+ const r = await it.next()
201
+ if (r.value?.stop) owner.delivered()
202
+ return r
203
+ },
204
+ return: () => it.return?.(),
205
+ [Symbol.asyncIterator]() { return this },
206
+ }
207
+ }
208
+
209
+ function nativeTransport(req: RunStream, close: () => void, fail: (e: unknown) => void, limits = NATIVE_LIMITS): NativeTransport {
210
+ const outbound = { bytes: 0, messages: 0 }
211
+ const queue: Buffer[] = []
212
+ let closed = false, flushing = false, rejectWrite: ((error: unknown) => void) | undefined
213
+ type Waiter = { size: number; done(): void; timer?: ReturnType<typeof setTimeout> }
214
+ const waiters = new Set<Waiter>()
215
+ const spare = (n: number) => Math.floor(n / 8)
216
+ const fits = (size: number) => outbound.messages === 0 || (outbound.messages + 1 + spare(limits.outboundMessages) <= limits.outboundMessages
217
+ && outbound.bytes + size + spare(limits.outboundBytes) <= limits.outboundBytes)
218
+ const wake = () => {
219
+ for (const w of waiters) if (closed || fits(w.size)) w.done()
220
+ }
221
+ const flush = async () => {
222
+ if (closed || flushing) return
223
+ flushing = true
224
+ try {
225
+ while (!closed && queue.length) {
226
+ const packet = queue.shift()!
227
+ await new Promise<void>((resolve, reject) => {
228
+ let written = false, drained = false, started = false, settled = false
229
+ const finish = (error?: unknown) => {
230
+ if (settled) return
231
+ settled = true
232
+ rejectWrite = undefined
233
+ req.removeListener("drain", drain)
234
+ req.removeListener("error", failed)
235
+ req.removeListener("close", lost)
236
+ error ? reject(error) : resolve()
237
+ }
238
+ const check = () => { if (started && written && drained) finish() }
239
+ const drain = () => { drained = true; check() }
240
+ const failed = (e: unknown) => finish(e)
241
+ const lost = () => finish(new NativeSessionError(502, "native transport closed during a write; its outcome is uncertain"))
242
+ rejectWrite = finish
243
+ req.once("drain", drain)
244
+ req.once("error", failed)
245
+ req.once("close", lost)
246
+ try {
247
+ drained = req.write(packet, (e) => {
248
+ if (e) return finish(e)
249
+ written = true
250
+ check()
251
+ }) || drained
252
+ started = true
253
+ if (drained) req.removeListener("drain", drain)
254
+ check()
255
+ } catch (e) { finish(e) }
256
+ })
257
+ if (!closed) { outbound.bytes -= packet.length; outbound.messages--; wake() }
258
+ }
259
+ } catch (e) {
260
+ if (!closed) fail(e)
261
+ } finally { flushing = false }
262
+ }
263
+ return {
264
+ outbound,
265
+ send(message) {
266
+ if (closed || req.destroyed || !req.writable) throw new NativeSessionError(502, "native transport is no longer writable")
267
+ const size = message.length + 5
268
+ if (outbound.bytes + size > limits.outboundBytes) throw new NativeSessionError(503, "native outbound bytes limit reached")
269
+ if (outbound.messages + 1 > limits.outboundMessages) throw new NativeSessionError(503, "native outbound messages limit reached")
270
+ outbound.bytes += size
271
+ outbound.messages++
272
+ queue.push(frame(message))
273
+ void flush()
274
+ },
275
+ room(size) {
276
+ if (closed || fits(size)) return Promise.resolve()
277
+ return new Promise((resolve, reject) => {
278
+ const w: Waiter = {
279
+ size,
280
+ done() {
281
+ waiters.delete(w)
282
+ clearTimeout(w.timer)
283
+ resolve()
284
+ },
285
+ }
286
+ w.timer = setTimeout(() => {
287
+ waiters.delete(w)
288
+ const which = outbound.bytes + size + spare(limits.outboundBytes) > limits.outboundBytes ? "bytes" : "messages"
289
+ reject(new NativeSessionError(503, `native outbound ${which} limit reached: the queue did not drain for ${Math.round(limits.writeWait / 1000)}s`))
290
+ }, limits.writeWait)
291
+ w.timer.unref?.()
292
+ waiters.add(w)
293
+ })
294
+ },
295
+ close() {
296
+ if (closed) return
297
+ closed = true
298
+ queue.length = 0
299
+ outbound.bytes = 0
300
+ outbound.messages = 0
301
+ wake()
302
+ rejectWrite?.(new NativeSessionError(410, "native transport was cancelled"))
303
+ close()
304
+ },
305
+ }
306
+ }
307
+
308
+ async function runNative({ tok, base, id, tools, conv, convID, signal, maxMode, params, native, connect, onResponse, onPayload, headers, headerWaitMs }: RunArgs & { native: NativeOwner }): Promise<RunResult> {
309
+ const cid = convID || randomUUID()
310
+ const since = Date.now()
311
+ const accounting = new AbortController()
312
+ const book = ledger(tok, cid, since, accounting.signal, !!convID, { before: since })
313
+ const debtKey = usageKey(tok, cid)
314
+ let started = false, settled = false
315
+ let deferred: Awaited<ReturnType<typeof book.owed>> = null
316
+ native.accounting = {
317
+ started() { started = true },
318
+ async settle() {
319
+ const more = await book.owed(true)
320
+ if (settled) {
321
+ if (more) owe(debtKey, { carry: more })
322
+ return null
323
+ }
324
+ deferred = more
325
+ return more
326
+ },
327
+ delivered() {
328
+ if (settled) return
329
+ settled = true
330
+ deferred = null
331
+ book.done()
332
+ accounting.abort()
333
+ },
334
+ abandon() {
335
+ if (settled) return
336
+ settled = true
337
+ book.done()
338
+ accounting.abort()
339
+ if (deferred) owe(debtKey, { carry: deferred })
340
+ deferred = null
341
+ if (started && native.segments > 0 && !native.finalUsage && convID && canRead(tok)) {
342
+ owe(debtKey, { since, n: 1, ready: Date.now() + STEP_WAIT.owedAt })
343
+ }
344
+ },
345
+ }
346
+ let modelId = id
347
+ if (onPayload) {
348
+ const replaced = await onPayload({ model: modelId, maxMode: !!maxMode, params, conversationId: cid, tools: tools.map((t) => t.name) })
349
+ if (replaced && typeof replaced === "object" && !Buffer.isBuffer(replaced) && "model" in replaced && typeof replaced.model === "string" && replaced.model) {
350
+ modelId = replaced.model
351
+ }
352
+ }
353
+ const { first, blobs } = buildRun(conv.msgs, conv.last, tools, modelId, cid, { maxMode, params })
354
+ native.chatTools = tools
355
+ native.attach(signal)
356
+ if (native.error) {
357
+ nativeSessions.forget(native)
358
+ return { error: native.error }
359
+ }
360
+ const version = await clientVersion()
361
+ const o = await open({ base, tok, headers, version, signal: native.ac.signal, connect, headerWaitMs })
362
+ if (o.error) {
363
+ native.fail(o.error)
364
+ nativeSessions.forget(native)
365
+ return { ...o, h1: !!o.h1 }
366
+ }
367
+ if (onResponse) await onResponse({ status: o.status, headers: o.headers ?? {} })
368
+ const { session, req } = o
369
+ const close = () => {
370
+ try { req.close(http2.constants.NGHTTP2_CANCEL) } catch {}
371
+ try { session.close() } catch {}
372
+ try { session.destroy() } catch {}
373
+ }
374
+ const transport = nativeTransport(req, close, (caught) => {
375
+ const e = caught as Thrown
376
+ native.fail({ status: e.status ?? 502, message: e.message })
377
+ }, native.limits)
378
+ try {
379
+ native.bind(transport, blobs, conv.estimate)
380
+ if (native.error) {
381
+ nativeSessions.forget(native)
382
+ return { error: native.error, h1: !!o.h1 }
383
+ }
384
+ native.send(first)
385
+ native.accounting.started()
386
+ if (o.status < 200 || o.status > 299) {
387
+ const chunks: Buffer[] = []
388
+ for await (const c of req) chunks.push(c)
389
+ native.fail(failure(o.status, Buffer.concat(chunks).toString("utf8").slice(0, 1 << 20)))
390
+ nativeSessions.forget(native)
391
+ return { error: native.error!, h1: !!o.h1 }
392
+ }
393
+ native.pumpTask = (async () => {
394
+ await native.pump(frames(req))
395
+ })()
396
+ const response = native.response()
397
+ const it = response.events
398
+ const head = await it.next()
399
+ if (head.done || head.value.error) {
400
+ const error = head.value?.error ?? { status: 502, message: "an empty reply" }
401
+ await native.cancel(error.message)
402
+ nativeSessions.forget(native)
403
+ return { error, h1: !!o.h1 }
404
+ }
405
+ let firstEvent: IteratorResult<RunEvent> | null = head
406
+ const events: AsyncIterableIterator<RunEvent> = {
407
+ next() {
408
+ if (firstEvent) {
409
+ const r = firstEvent
410
+ firstEvent = null
411
+ if (r.value?.stop) native.delivered()
412
+ return Promise.resolve(r)
413
+ }
414
+ return it.next().then((r) => {
415
+ if (r.value?.stop) native.delivered()
416
+ return r
417
+ })
418
+ },
419
+ return: () => it.return(),
420
+ [Symbol.asyncIterator]() { return this },
421
+ }
422
+ return { conversationId: cid, events, h1: !!o.h1 }
423
+ } catch (caught) {
424
+ const e = caught as Thrown
425
+ native.fail({ status: e.status ?? 502, message: e.message })
426
+ await native.pumpTask
427
+ nativeSessions.forget(native)
428
+ return { error: native.error!, h1: !!o.h1 }
429
+ }
430
+ }
package/src/auth.ts CHANGED
@@ -5,6 +5,8 @@
5
5
  * https://github.com/Rahularya01/pi-cursor
6
6
  * cursor-agent's auth.json is read the way magpie reads it, and never written.
7
7
  * Browser sign-in is the deep-control PKCE flow, polled at api2.cursor.sh.
8
+ * A stored login is renewed the way Cursor's IDE renews it, as oh-my-pi (MIT)
9
+ * documents: a refresh_token grant at api2.cursor.sh/oauth/token.
8
10
  * Tokens are never written to logs.
9
11
  */
10
12
  import { execFile, spawn } from "node:child_process"
@@ -21,7 +23,9 @@ export { sleep }
21
23
 
22
24
  const LOGIN_URL = "https://cursor.com/loginDeepControl"
23
25
  const POLL_URL = `${API}/auth/poll`
24
- const EXCHANGE_URL = `${API}/auth/exchange_user_api_key`
26
+ const REFRESH_URL = `${API}/oauth/token`
27
+ /** The OAuth client Cursor's IDE renews its login session with. */
28
+ const CLIENT_ID = "KbZUR41cY7W6zRSdpSUJ7I7mLYBKOCmB"
25
29
 
26
30
  export type AuthSource = "environment" | "pi-oauth" | "cursor-agent" | "keychain" | "ide-state"
27
31
 
@@ -236,22 +240,30 @@ export async function login(callbacks: OAuthLoginCallbacks): Promise<OAuthCreden
236
240
  throw new Error("Cursor sign-in timed out")
237
241
  }
238
242
 
243
+ /**
244
+ * Renew a stored login with the grant Cursor's IDE uses.
245
+ *
246
+ * The refresh token is the session credential, so renewal works even after the
247
+ * access token expired. The host passes its own timeout signal; a rotated
248
+ * refresh token is returned so the host can persist it.
249
+ */
239
250
  export async function refresh(credentials: OAuthCredentials, signal?: AbortSignal): Promise<OAuthCredentials> {
240
- const res = await fetch(EXCHANGE_URL, {
251
+ const refreshToken = trimmed(credentials.refresh)
252
+ if (!refreshToken) throw new Error("Cursor has no refresh token. Run /login cursor again.")
253
+ const res = await fetch(REFRESH_URL, {
241
254
  method: "POST",
242
- headers: {
243
- Authorization: `Bearer ${credentials.access}`,
244
- "Content-Type": "application/json",
245
- "connect-protocol-version": "1",
246
- "x-cursor-client-type": "cli",
247
- "x-cursor-client-version": await clientVersion(),
248
- },
249
- body: "{}",
255
+ headers: { "Content-Type": "application/json" },
256
+ body: JSON.stringify({ grant_type: "refresh_token", client_id: CLIENT_ID, refresh_token: refreshToken }),
250
257
  signal,
251
258
  })
259
+ // Never echo the body: it can quote the credential back.
252
260
  if (!res.ok) throw new Error(`Cursor sign-in could not be refreshed (HTTP ${res.status})`)
253
- const body = (await res.json().catch(() => null)) as { accessToken?: unknown; refreshToken?: unknown; access?: unknown; refresh?: unknown } | null
254
- const access = trimmed(body?.accessToken) || trimmed(body?.access) || credentials.access
255
- const nextRefresh = trimmed(body?.refreshToken) || trimmed(body?.refresh) || credentials.refresh
256
- return { access, refresh: nextRefresh, expires: expiresAt(access) }
261
+ const body = (await res.json().catch(() => null)) as
262
+ | { access_token?: unknown; refresh_token?: unknown; shouldLogout?: unknown }
263
+ | null
264
+ // Cursor answers a session it will not renew with 200, no token, and shouldLogout.
265
+ if (body?.shouldLogout === true) throw new Error("Cursor ended this sign-in. Run /login cursor again.")
266
+ const access = trimmed(body?.access_token)
267
+ if (!access) throw new Error("Cursor sent back no access token while refreshing the sign-in")
268
+ return { access, refresh: trimmed(body?.refresh_token) || refreshToken, expires: expiresAt(access) }
257
269
  }
package/src/cache.ts ADDED
@@ -0,0 +1,38 @@
1
+ import { createHash } from "node:crypto"
2
+
3
+ export const CACHE_CAP = 100
4
+
5
+ export function tokenKey(token: string): string {
6
+ return createHash("sha256").update(token).digest("hex")
7
+ }
8
+
9
+ type Stamped = { expires: number }
10
+
11
+ export function recall<T extends Stamped>(map: Map<string, T>, key: string, now = Date.now()): T | undefined {
12
+ const hit = map.get(key)
13
+ if (!hit) return undefined
14
+ if (now >= hit.expires) {
15
+ map.delete(key)
16
+ return undefined
17
+ }
18
+ return hit
19
+ }
20
+
21
+ export function store<T extends Stamped>(
22
+ map: Map<string, T>,
23
+ key: string,
24
+ value: T,
25
+ ttl: number,
26
+ now = Date.now(),
27
+ ): void {
28
+ for (const [stored, entry] of map) {
29
+ if (now >= entry.expires) map.delete(stored)
30
+ }
31
+ map.delete(key)
32
+ map.set(key, { ...value, expires: now + ttl })
33
+ while (map.size > CACHE_CAP) {
34
+ const oldest = map.keys().next().value
35
+ if (oldest === undefined) break
36
+ map.delete(oldest)
37
+ }
38
+ }