@caph42/pi-cursor-provider 0.4.0 → 0.5.1

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,19 @@
1
+ # Changelog
2
+
3
+ ## 0.5.1
4
+
5
+ - 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.
6
+ - `/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.
7
+ - `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.
8
+ - A native Run that cannot be created names its reason instead of returning `null`. A history mismatch keeps the specific error as `detail`.
9
+ - A finished login wait removes its abort listener.
10
+ - `headerWaitMs` is the HTTP/2 header timer. Callers who omit it still wait 15 seconds.
11
+ - Cancelling a request aborts the Connect call. A late model catalog is not cached.
12
+ - A failed model refresh returns that credential's last catalog, or an empty list when it has none.
13
+ - Tool names, descriptions, and schemas cannot close the catalog tags.
14
+ - Offline tests cover assistant events, Run retries, and HTTP/2 stickiness.
15
+
16
+ ## 0.3.0
17
+
18
+ - 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.
19
+ - 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
@@ -49,12 +51,36 @@ Then select a model:
49
51
  { "hiddenModels": ["claude-*", "gpt-5", "cursor/gpt-5-mini"] }
50
52
  ```
51
53
 
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.
54
+ The extension registers a native Pi provider. Its synchronous model directory and availability filter read `cursor.json`, so local rules apply even when Cursor cannot refresh its remote catalogue. The availability filter also covers models added through `models.json`.
55
+
56
+ Successful discovery saves the complete catalogue in Pi's `models-store.json`. Startup and `/reload` restore that catalogue before applying the current hide rules; a session-start refresh discovers models when no cache exists. Offline mode restores the cache without fetching. A failed remote refresh keeps the previous catalogue, and a first-load failure is reported instead of silently returning an empty list.
57
+
58
+ 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` and let its catalogue refresh finish to see the new list. After updating the extension itself, run `/reload` once. When developing from a checkout, configure that local path as the package source; `/reload` reloads configured sources and does not copy checkout changes into an npm installation.
53
59
 
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.
60
+ Hidden models are removed from the live provider directory, so normal directory lookups no longer resolve their ids. A session already running on a hidden model keeps it; resuming one may require selecting another model. `/cursor.usage` still classifies usage by every model the account has.
61
+
62
+ Pi keeps a separate scoped model list (`/scoped-models`, `enabledModels`, or `--models`). Its picker can retain previously scoped model objects independently of the provider directory. If a hidden model still appears under **scoped**, remove it with `/scoped-models` and update any matching scope patterns. Provider filtering cannot remove those saved references through the public extension API.
55
63
 
56
64
  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
65
 
66
+ ## Fast mode
67
+
68
+ Select a Cursor model, then use:
69
+
70
+ ```text
71
+ /cursor.fast on
72
+ /cursor.fast status
73
+ /cursor.fast off
74
+ ```
75
+
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. 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.
77
+
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.
79
+
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`.
81
+
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.
83
+
58
84
  ## How this relates to other Cursor packages
59
85
 
60
86
  | Package | Role |
@@ -73,6 +99,8 @@ The same report is exported from the package.
73
99
  import { fetchUsage, formatUsage, onDemandOf } from "@caph42/pi-cursor-provider"
74
100
  ```
75
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
+
76
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`.
77
105
 
78
106
  Windows follow magpie, in this order.
@@ -121,6 +149,22 @@ The stateless path still cancels the stream after tools. The native path does no
121
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.
122
150
  - "Max Mode Required" retries once with Max Mode and remembers that model id for the process.
123
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
+
124
168
  ## Known gaps
125
169
 
126
170
  Compared with magpie [`packages/cursor`](https://github.com/magpie-community/plugins/tree/main/packages/cursor), this package still does not include:
@@ -141,8 +185,10 @@ npm test
141
185
  CURSOR_E2E=1 npm run test:e2e
142
186
  ```
143
187
 
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.
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`. `codec.ts`, `ledger.ts`, `models.ts`, `native-session.ts`, and `run.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` answers with a new access token, and that token lists models, reads usage, and completes a Run. `npm test` keeps that coverage offline, so a protocol change fails a test before a release.
145
191
 
146
192
  ## License
147
193
 
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).
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.4.0",
3
+ "version": "0.5.1",
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,15 +36,18 @@
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": "*",
34
- "@earendil-works/pi-coding-agent": "*"
44
+ "@earendil-works/pi-coding-agent": "*",
45
+ "@earendil-works/pi-tui": "*"
35
46
  },
36
47
  "devDependencies": {
37
48
  "@earendil-works/pi-ai": "1.4.0",
38
49
  "@earendil-works/pi-coding-agent": "1.4.0",
50
+ "@earendil-works/pi-tui": "1.4.0",
39
51
  "@types/node": "^22.20.5",
40
52
  "typescript": "5.9"
41
53
  },
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"
@@ -15,10 +17,15 @@ import { join } from "node:path"
15
17
  import type { OAuthCredentials, OAuthLoginCallbacks } from "@earendil-works/pi-ai"
16
18
  import { readStoredCredential } from "@earendil-works/pi-coding-agent"
17
19
  import { API, clientVersion } from "./client.ts"
20
+ import { sleep } from "./sleep.ts"
21
+
22
+ export { sleep }
18
23
 
19
24
  const LOGIN_URL = "https://cursor.com/loginDeepControl"
20
25
  const POLL_URL = `${API}/auth/poll`
21
- 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"
22
29
 
23
30
  export type AuthSource = "environment" | "pi-oauth" | "cursor-agent" | "keychain" | "ide-state"
24
31
 
@@ -60,24 +67,6 @@ export function expiresAt(token: string): number {
60
67
  return Math.max(exp - 5 * 60 * 1000, Date.now() + 60 * 1000)
61
68
  }
62
69
 
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
70
  function openBrowser(url: string) {
82
71
  try {
83
72
  const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open"
@@ -251,22 +240,30 @@ export async function login(callbacks: OAuthLoginCallbacks): Promise<OAuthCreden
251
240
  throw new Error("Cursor sign-in timed out")
252
241
  }
253
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
+ */
254
250
  export async function refresh(credentials: OAuthCredentials, signal?: AbortSignal): Promise<OAuthCredentials> {
255
- 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, {
256
254
  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: "{}",
255
+ headers: { "Content-Type": "application/json" },
256
+ body: JSON.stringify({ grant_type: "refresh_token", client_id: CLIENT_ID, refresh_token: refreshToken }),
265
257
  signal,
266
258
  })
259
+ // Never echo the body: it can quote the credential back.
267
260
  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) }
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) }
272
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
+ }
package/src/client.ts CHANGED
@@ -4,7 +4,6 @@
4
4
  * Ported from magpie's Cursor provider (MIT):
5
5
  * https://github.com/magpie-community/plugins/tree/main/packages/cursor
6
6
  */
7
- // @ts-nocheck
8
7
  import { basename, dirname, join } from "node:path"
9
8
  import { homedir, platform, tmpdir } from "node:os"
10
9
  import { readdir, realpath, stat } from "node:fs/promises"
@@ -17,10 +16,10 @@ export const CALL = "CallDynamicTool"
17
16
  export const NAMESPACE = "pi"
18
17
  export const DEFAULT_CONTEXT = 200_000
19
18
  export const MODELS_KEEP = 10 * 60 * 1000
20
- export const GOOS = { win32: "windows" }[platform()] ?? platform()
19
+ export const GOOS = platform() === "win32" ? "windows" : platform()
21
20
  export const tempDir = tmpdir
22
21
 
23
- const exists = (p) => stat(p).then((s) => !s.isDirectory(), () => false)
22
+ const exists = (p: string) => stat(p).then((s) => !s.isDirectory(), () => false)
24
23
 
25
24
  async function cursorExecutable() {
26
25
  const dirs = (process.env.PATH ?? "").split(GOOS === "windows" ? ";" : ":").filter(Boolean)
@@ -39,11 +38,12 @@ async function cursorExecutable() {
39
38
  }
40
39
 
41
40
  const VERSION_RE = /^\d{4}\.\d{2}\.\d{2}-[0-9a-f]+$/
42
- let versionSaid = ""
41
+ const VERSION_TTL = 10 * 60 * 1000
42
+ let versionCache = { value: "", expires: 0 }
43
43
 
44
44
  /** "cli-<installed cursor-agent version>", or the fallback the API still accepts. */
45
45
  export async function clientVersion() {
46
- if (versionSaid) return versionSaid
46
+ if (versionCache.value && Date.now() < versionCache.expires) return versionCache.value
47
47
  let v = ""
48
48
  const exe = await cursorExecutable()
49
49
  if (exe) {
@@ -56,11 +56,11 @@ export async function clientVersion() {
56
56
  for (const dir of dirs)
57
57
  for (const n of await readdir(dir).catch(() => [])) if (VERSION_RE.test(n) && n > v) v = n
58
58
  }
59
- versionSaid = "cli-" + (v || VERSION_FALLBACK)
60
- return versionSaid
59
+ versionCache = { value: "cli-" + (v || VERSION_FALLBACK), expires: Date.now() + VERSION_TTL }
60
+ return versionCache.value
61
61
  }
62
62
 
63
- export async function headersFor(tok) {
63
+ export async function headersFor(tok: string) {
64
64
  return {
65
65
  "Content-Type": "application/json",
66
66
  "Connect-Protocol-Version": "1",
@@ -71,20 +71,19 @@ export async function headersFor(tok) {
71
71
  }
72
72
  }
73
73
 
74
- /** Connect unary call in JSON. */
75
- export async function unary(base, path, tok, body = {}, timeout = 15_000) {
74
+ /** Connect unary call in JSON. `signal` aborts the request. `timeout` still does. */
75
+ export async function unary(base: string, path: string, tok: string, body: unknown = {}, timeout = 15_000, signal?: AbortSignal) {
76
+ const deadline = AbortSignal.timeout(timeout)
76
77
  const res = await fetch(base + "/" + path, {
77
78
  method: "POST",
78
79
  headers: await headersFor(tok),
79
80
  body: JSON.stringify(body),
80
- signal: AbortSignal.timeout(timeout),
81
+ signal: signal ? AbortSignal.any([deadline, signal]) : deadline,
81
82
  })
82
83
  const text = await res.text()
83
84
  if (!res.ok) {
84
85
  const f = failure(res.status, text)
85
- const e = new Error(f.message)
86
- e.status = f.status
87
- throw e
86
+ throw Object.assign(new Error(f.message), { status: f.status })
88
87
  }
89
88
  return JSON.parse(text || "{}")
90
89
  }
package/src/config.ts CHANGED
@@ -10,8 +10,9 @@
10
10
  *
11
11
  * A pattern globs the id `/model` shows (the part after `cursor/`): `*` is any
12
12
  * run of characters, everything else is literal, and the match ignores case.
13
- * Hiding is a picker filter only: a session already on that model keeps it. A
14
- * missing, unreadable or malformed file hides nothing.
13
+ * Hiding removes models from the live directory too: sessions already using a
14
+ * hidden model keep it, but resuming one may require selecting another model.
15
+ * A missing, unreadable or malformed file hides nothing.
15
16
  */
16
17
  import { readFileSync } from "node:fs"
17
18
  import { homedir } from "node:os"
@@ -70,7 +71,7 @@ export function hidden(patterns: string[], id: string): boolean {
70
71
  }
71
72
 
72
73
  /** The models a pattern list keeps, in order. No patterns keeps all of them. */
73
- export function visible<T extends { id: string }>(models: T[], patterns: string[]): T[] {
74
- if (!patterns.length) return models
74
+ export function visible<T extends { id: string }>(models: readonly T[], patterns: string[]): T[] {
75
+ if (!patterns.length) return [...models]
75
76
  return models.filter((m) => !hidden(patterns, m.id))
76
77
  }
package/src/doctor.ts ADDED
@@ -0,0 +1,149 @@
1
+ /**
2
+ * /cursor.doctor. Reads each store through its owner's view and the journal
3
+ * through trace.turns(). It changes no state and prints nothing derived from
4
+ * a token. Every clock it prints is UTC.
5
+ */
6
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"
7
+ import { resolveAccessToken, type AuthSource } from "./auth.ts"
8
+ import { API, clientVersion } from "./client.ts"
9
+ import { configPath, hiddenPatterns } from "./config.ts"
10
+ import { ledgerState, type LedgerState } from "./ledger.ts"
11
+ import { nativeSessions, type NativeState } from "./native-session.ts"
12
+ import { runState, type RunState } from "./run.ts"
13
+ import { Account, hostOf, trace, type Decision, type TurnLog } from "./trace.ts"
14
+
15
+ type Report = {
16
+ now: number
17
+ /** null when nothing is signed in. */
18
+ auth: { source: AuthSource; account: Account } | null
19
+ version: string
20
+ hidden: { patterns: readonly string[]; path: string }
21
+ run: RunState
22
+ native: NativeState
23
+ ledger: LedgerState
24
+ /** null while CURSOR_DEBUG is off. */
25
+ journal: readonly TurnLog[] | null
26
+ }
27
+
28
+ type Notice = { text: string; level: "info" | "warning" }
29
+
30
+ export function registerCursorDoctor(pi: ExtensionAPI): void {
31
+ pi.registerCommand("cursor.doctor", {
32
+ description: "Show Cursor's credential, transport, agent host, native owners, and usage ledger, without printing the token",
33
+ handler: async (args, ctx) => {
34
+ const { text, level } = render(await gather())
35
+ ctx.ui.notify(args.trim() ? `${text}\nThis command does not take arguments.` : text, level)
36
+ },
37
+ })
38
+ }
39
+
40
+ // Pi's own credential lookup can refresh OAuth over the network, so the doctor
41
+ // reads the local credential, as /cursor.usage does.
42
+ async function gather(): Promise<Report> {
43
+ const auth = await resolveAccessToken()
44
+ const version = await clientVersion()
45
+ const account = auth ? Account.of(auth.token) : undefined
46
+ const now = Date.now()
47
+ return {
48
+ now,
49
+ auth: auth && account ? { source: auth.source, account } : null,
50
+ version,
51
+ hidden: { patterns: hiddenPatterns(), path: configPath() },
52
+ run: runState(account, now),
53
+ native: nativeSessions.state(account),
54
+ ledger: ledgerState(account, now),
55
+ journal: trace?.turns() ?? null,
56
+ }
57
+ }
58
+
59
+ const clock = (ms: number) => `${new Date(ms).toISOString().slice(11, 19)}Z`
60
+ const count = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`
61
+
62
+ function render(report: Report): Notice {
63
+ const { auth, run, native, ledger, journal } = report
64
+ const lines = [`Cursor doctor at ${clock(report.now)}`]
65
+ lines.push(
66
+ auth
67
+ ? `Credential: ${auth.source}. Token not shown. Client ${report.version}.`
68
+ : `Cursor is not signed in. Run /login cursor or set CURSOR_ACCESS_TOKEN. Client ${report.version}.`,
69
+ )
70
+ const { patterns, path } = report.hidden
71
+ lines.push(patterns.length ? `Hidden from /model: ${patterns.join(", ")} (${path}).` : `No models hidden (${path}).`)
72
+ lines.push(
73
+ run.transport.via === "h2"
74
+ ? "Transport: h2."
75
+ : `Transport: h1, sticky until ${clock(run.transport.until)}. HTTP/2 failed on this network, so Runs use HTTP/1.1 at ${hostOf(API)} until then.`,
76
+ )
77
+ lines.push(agentLine(report))
78
+ if (run.maxModeForced.length) lines.push(`Max mode forced for: ${run.maxModeForced.join(", ")}.`)
79
+
80
+ const active = native.owners.filter((owner) => owner.phase !== "complete").length
81
+ lines.push(
82
+ `Native owners: ${active} active, ${native.owners.length - active} kept for replay (limits ${native.limits.perAccount} per account, ${native.limits.perProcess} per process).`,
83
+ )
84
+ for (const owner of native.owners) {
85
+ const ends = owner.phase === "complete" ? "kept for replay" : `lifetime ends ${clock(owner.lifetimeEnds)}`
86
+ const mode = owner.maxMode ? " in max mode" : ""
87
+ lines.push(` ${owner.phase}, ${owner.model || "unknown model"}${mode}, ${count(owner.rounds, "tool round")}, ${ends}, ${owner.current ? "this account" : "another account"}`)
88
+ }
89
+
90
+ const refused = ledger.unreadableOthers + (ledger.current?.unreadableUntil != null ? 1 : 0)
91
+ const { runs, conversations, collecting } = ledger.owed
92
+ lines.push(
93
+ `Ledger: ${count(runs, "Run")} owed over ${count(conversations, "conversation")}, ${count(collecting, "collection")} running, ${count(refused, "account")} unreadable.`,
94
+ )
95
+ if (ledger.current) {
96
+ const { runsOwed, misses, stepsWait, unreadableUntil } = ledger.current
97
+ const skip = stepsWait ? "" : ", so steps skip the usage wait"
98
+ const read = unreadableUntil === null ? "Usage events readable." : `Cursor refuses its usage events until ${clock(unreadableUntil)}.`
99
+ lines.push(` This account: ${count(runsOwed, "Run")} owed, ${count(misses, "usage miss", "usage misses")} in a row${skip}. ${read}`)
100
+ }
101
+
102
+ if (!journal) lines.push("Decision journal off. Start Pi with CURSOR_DEBUG=1 to record retry and fallback reasons.")
103
+ else if (!journal.length) lines.push("Decision journal on (CURSOR_DEBUG). No turn has run yet.")
104
+ else {
105
+ lines.push("Recent decisions (CURSOR_DEBUG), oldest turn first:")
106
+ for (const log of journal) {
107
+ const whose = log.account && auth?.account.same(log.account) ? "this account" : "another account"
108
+ lines.push(log.account ? ` Turn ${log.turn} at ${clock(log.started)}, ${log.model || "no model"}, ${whose}` : " Outside any turn")
109
+ for (const entry of log.entries) lines.push(` ${say(entry)}${entry.count > 1 ? ` ×${entry.count}` : ""}`)
110
+ if (log.dropped) lines.push(` ${count(log.dropped, "later decision")} not kept`)
111
+ }
112
+ }
113
+
114
+ const degraded = !auth || ledger.current?.unreadableUntil != null || run.transport.via === "h1"
115
+ return { text: lines.join("\n"), level: degraded ? "warning" : "info" }
116
+ }
117
+
118
+ function agentLine({ auth, run }: Report): string {
119
+ const n = run.otherAgents
120
+ const others = n ? ` ${count(n, "other account")} ${n === 1 ? "has" : "have"} a cached host.` : ""
121
+ if (!auth) return `Agent host: unknown while signed out.${others}`
122
+ if (!run.agent) return `Agent host: none cached for this account. The next turn asks GetServerConfig.${others}`
123
+ const named = run.agent.source === "server-config" ? "named by GetServerConfig" : "the global default because GetServerConfig named none"
124
+ return `Agent host: ${run.agent.host}, ${named}, asked again after ${clock(run.agent.until)}.${others}`
125
+ }
126
+
127
+ function say(d: Decision): string {
128
+ switch (d.kind) {
129
+ case "endpoint":
130
+ if (d.source === "server-config") return `endpoint: ${d.host}, named by GetServerConfig`
131
+ return d.source === "kept-regional" ? `endpoint: kept ${d.host} (${d.why})` : `endpoint: ${d.host}, the global default (${d.why})`
132
+ case "transport":
133
+ if (d.via === "h2") return `run: h2 to ${d.host}`
134
+ if (d.cause === "sticky") return `run: h1 to ${d.host}, sticky until ${clock(d.until)}`
135
+ return `run: h1 to ${d.host}. HTTP/2 to ${d.h2Host} failed (${d.why})${d.until === null ? "" : `, sticky until ${clock(d.until)}`}.`
136
+ case "native":
137
+ return "why" in d ? `native: ${d.path}, ${d.why}` : `native: ${d.path}`
138
+ case "owner-ended":
139
+ return `owner ended: ${d.phase}, ${d.model || "unknown model"} (${d.why})`
140
+ case "retry":
141
+ if (d.rule === "max-mode") return `max mode required for ${d.model} (${d.status}, ${d.why}). Retried with max mode.`
142
+ if ("retriedOn" in d) return `region error (${d.status}, ${d.why}). Retried on ${d.retriedOn}.`
143
+ return `region error (${d.status}, ${d.why}). Not retried because ${d.notRetried === "cancelled" ? "the turn was cancelled" : "the agent host did not change and the Run used HTTP/2"}.`
144
+ case "failed":
145
+ return `failed (${d.status}, ${d.why})${d.bodyCut ? ", error body cut short" : ""}`
146
+ case "usage":
147
+ return d.outcome === "failed" ? `usage read failed (${d.why})` : `usage read ${d.outcome} (${d.status})`
148
+ }
149
+ }
@@ -0,0 +1,21 @@
1
+ import type { AutocompleteProvider } from "@earendil-works/pi-tui"
2
+
3
+ /** Pi 1.4 routes Tab after slash-command arguments through file completion. */
4
+ export function cursorFastAutocomplete(current: AutocompleteProvider): AutocompleteProvider {
5
+ const argumentsAt = (lines: string[], line: number, col: number) =>
6
+ line === 0 && /^[ \t]*\/cursor\.fast +/.test((lines[line] ?? "").slice(0, col))
7
+
8
+ return {
9
+ triggerCharacters: current.triggerCharacters,
10
+ shouldTriggerFileCompletion(lines, line, col) {
11
+ if (argumentsAt(lines, line, col)) return true
12
+ return current.shouldTriggerFileCompletion?.(lines, line, col) ?? true
13
+ },
14
+ getSuggestions(lines, line, col, options) {
15
+ return current.getSuggestions(lines, line, col, argumentsAt(lines, line, col) ? { ...options, force: false } : options)
16
+ },
17
+ applyCompletion(lines, line, col, item, prefix) {
18
+ return current.applyCompletion(lines, line, col, item, prefix)
19
+ },
20
+ }
21
+ }