@caph42/pi-cursor-provider 0.5.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 +19 -0
- package/README.md +24 -2
- package/package.json +13 -3
- package/src/auth.ts +26 -14
- package/src/cache.ts +38 -0
- package/src/client.ts +10 -12
- package/src/doctor.ts +149 -0
- package/src/index.ts +3 -16
- package/src/ledger.ts +63 -5
- package/src/models.ts +8 -5
- package/src/native-session.ts +43 -5
- package/src/run.ts +106 -35
- package/src/trace.ts +218 -0
- package/src/usage.ts +12 -6
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
|
|
@@ -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. `
|
|
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.
|
|
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.
|
|
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,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": "*",
|
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
|
|
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
|
|
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
|
-
|
|
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
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
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
|
+
}
|
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 =
|
|
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
|
-
|
|
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 (
|
|
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
|
-
|
|
60
|
-
return
|
|
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",
|
|
@@ -72,7 +72,7 @@ export async function headersFor(tok) {
|
|
|
72
72
|
}
|
|
73
73
|
|
|
74
74
|
/** Connect unary call in JSON. `signal` aborts the request. `timeout` still does. */
|
|
75
|
-
export async function unary(base, path, tok, body = {}, timeout = 15_000, signal?: AbortSignal) {
|
|
75
|
+
export async function unary(base: string, path: string, tok: string, body: unknown = {}, timeout = 15_000, signal?: AbortSignal) {
|
|
76
76
|
const deadline = AbortSignal.timeout(timeout)
|
|
77
77
|
const res = await fetch(base + "/" + path, {
|
|
78
78
|
method: "POST",
|
|
@@ -83,9 +83,7 @@ export async function unary(base, path, tok, body = {}, timeout = 15_000, signal
|
|
|
83
83
|
const text = await res.text()
|
|
84
84
|
if (!res.ok) {
|
|
85
85
|
const f = failure(res.status, text)
|
|
86
|
-
|
|
87
|
-
e.status = f.status
|
|
88
|
-
throw e
|
|
86
|
+
throw Object.assign(new Error(f.message), { status: f.status })
|
|
89
87
|
}
|
|
90
88
|
return JSON.parse(text || "{}")
|
|
91
89
|
}
|
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
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -11,7 +11,8 @@ import type { Model, Provider } from "@earendil-works/pi-ai"
|
|
|
11
11
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"
|
|
12
12
|
import { login, refresh, resolveAccessToken } from "./auth.ts"
|
|
13
13
|
import { AGENT, clientVersion } from "./client.ts"
|
|
14
|
-
import {
|
|
14
|
+
import { hiddenPatterns, visible } from "./config.ts"
|
|
15
|
+
import { registerCursorDoctor } from "./doctor.ts"
|
|
15
16
|
import { piModelConfigs, usable } from "./models.ts"
|
|
16
17
|
import { registerCursorFast } from "./fast.ts"
|
|
17
18
|
import { fetchUsage, formatUsage } from "./usage.ts"
|
|
@@ -137,21 +138,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
137
138
|
if (error && ctx.hasUI) ctx.ui.notify(`Cursor model catalogue: ${error.message}`, "warning")
|
|
138
139
|
})
|
|
139
140
|
|
|
140
|
-
pi
|
|
141
|
-
description: "Show which Cursor credential would be used, without printing the token",
|
|
142
|
-
handler: async (args, ctx) => {
|
|
143
|
-
const extra = args.trim() ? " This command does not take arguments." : ""
|
|
144
|
-
const auth = await resolveAccessToken()
|
|
145
|
-
const version = await clientVersion()
|
|
146
|
-
const patterns = hiddenPatterns()
|
|
147
|
-
const hiddenText = patterns.length ? `Hidden from /model: ${patterns.join(", ")} (${configPath()}).` : `No models hidden (${configPath()}).`
|
|
148
|
-
if (!auth) {
|
|
149
|
-
ctx.ui.notify(`Cursor is not signed in (${version}). Run /login cursor or set CURSOR_ACCESS_TOKEN. ${hiddenText}${extra}`, "warning")
|
|
150
|
-
return
|
|
151
|
-
}
|
|
152
|
-
ctx.ui.notify(`Cursor auth source: ${auth.source}. Client ${version}. ${hiddenText} Token not shown.${extra}`, "info")
|
|
153
|
-
},
|
|
154
|
-
})
|
|
141
|
+
registerCursorDoctor(pi)
|
|
155
142
|
|
|
156
143
|
pi.registerCommand("cursor.usage", {
|
|
157
144
|
description: "Show Cursor plan usage for this billing period",
|
package/src/ledger.ts
CHANGED
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
import { createHash } from "node:crypto"
|
|
14
14
|
import { API, headersFor } from "./client.ts"
|
|
15
15
|
import { sleep } from "./sleep.ts"
|
|
16
|
+
import { trace, type Account } from "./trace.ts"
|
|
16
17
|
|
|
17
18
|
// STEP_WAIT is how long a step's event is looked for: first after that long,
|
|
18
19
|
// then every so often until the end (each ask given `ask` to answer).
|
|
@@ -56,14 +57,59 @@ export const misses = new Map()
|
|
|
56
57
|
const tokKey = (tok) => createHash("sha256").update(tok).digest("hex")
|
|
57
58
|
export const usageKey = (tok, conv) => tokKey(tok) + "\0" + conv
|
|
58
59
|
|
|
60
|
+
const stepsWait = (missed) => missed < STEP_WAIT.skipAfter || missed % STEP_WAIT.retryEvery === 0
|
|
61
|
+
const refusedUntil = (at) => at + STEP_WAIT.owedFor
|
|
62
|
+
|
|
59
63
|
export function canRead(tok) {
|
|
60
64
|
const at = unreadable.get(tokKey(tok))
|
|
61
65
|
if (at === undefined) return true
|
|
62
|
-
if (Date.now()
|
|
66
|
+
if (Date.now() < refusedUntil(at)) return false
|
|
63
67
|
unreadable.delete(tokKey(tok))
|
|
64
68
|
return true
|
|
65
69
|
}
|
|
66
70
|
|
|
71
|
+
/** The usage ledger in a form the doctor may print. */
|
|
72
|
+
export type LedgerState = {
|
|
73
|
+
/** Every account. */
|
|
74
|
+
owed: { runs: number; conversations: number; collecting: number }
|
|
75
|
+
/** The account the reader asked about. null without one. */
|
|
76
|
+
current: { runsOwed: number; misses: number; stepsWait: boolean; unreadableUntil: number | null } | null
|
|
77
|
+
/** Other accounts whose usage events Cursor still refuses. */
|
|
78
|
+
unreadableOthers: number
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Unlike canRead and owe, this deletes no expired entry.
|
|
82
|
+
export function ledgerState(account: Account | undefined, now = Date.now()): LedgerState {
|
|
83
|
+
const live = (since) => now - since <= STEP_WAIT.owedFor
|
|
84
|
+
const runsOf = (d) => (d.groups ? d.groups.filter((g) => live(g.since)).reduce((n, g) => n + g.n, 0) : live(d.since) ? d.n : 0)
|
|
85
|
+
let runs = 0
|
|
86
|
+
let conversations = 0
|
|
87
|
+
let runsOwed = 0
|
|
88
|
+
for (const [key, d] of owed) {
|
|
89
|
+
const n = runsOf(d)
|
|
90
|
+
if (!n) continue
|
|
91
|
+
runs += n
|
|
92
|
+
conversations++
|
|
93
|
+
if (account?.is(key.slice(0, key.indexOf("\0")))) runsOwed += n
|
|
94
|
+
}
|
|
95
|
+
let collecting = 0
|
|
96
|
+
for (const set of flights.values()) collecting += set.size
|
|
97
|
+
let unreadableUntil = null
|
|
98
|
+
let unreadableOthers = 0
|
|
99
|
+
for (const [key, at] of unreadable) {
|
|
100
|
+
if (now >= refusedUntil(at)) continue
|
|
101
|
+
if (account?.is(key)) unreadableUntil = refusedUntil(at)
|
|
102
|
+
else unreadableOthers++
|
|
103
|
+
}
|
|
104
|
+
let missed = 0
|
|
105
|
+
for (const [key, n] of misses) if (account?.is(key)) missed = n
|
|
106
|
+
return {
|
|
107
|
+
owed: { runs, conversations, collecting },
|
|
108
|
+
current: account ? { runsOwed, misses: missed, stepsWait: stepsWait(missed), unreadableUntil } : null,
|
|
109
|
+
unreadableOthers,
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
67
113
|
const ZERO = () => ({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0, reasoning: 0 })
|
|
68
114
|
function addUsage(a, b) {
|
|
69
115
|
if (!b) return a
|
|
@@ -136,8 +182,10 @@ export async function usageEvents(tok, conv, since, want, { poll = false, first
|
|
|
136
182
|
})
|
|
137
183
|
if (res.status >= 400 && res.status < 500 && res.status !== 429) {
|
|
138
184
|
unreadable.set(tokKey(tok), Date.now())
|
|
185
|
+
trace?.note("usage", { status: res.status, refused: true })
|
|
139
186
|
return { usage, events, got, counts, refused: true }
|
|
140
187
|
}
|
|
188
|
+
if (!res.ok) trace?.note("usage", { status: res.status })
|
|
141
189
|
const evs = res.ok ? ((await res.json())?.usageEventsDisplay ?? []) : []
|
|
142
190
|
const found = evs
|
|
143
191
|
.filter((e) => e?.conversationId === conv && e.tokenUsage && num(e.timestamp) >= since - 1000 && !claimed.has(key + "\0" + e.timestamp))
|
|
@@ -157,7 +205,9 @@ export async function usageEvents(tok, conv, since, want, { poll = false, first
|
|
|
157
205
|
got++
|
|
158
206
|
}
|
|
159
207
|
if (got >= want) break
|
|
160
|
-
} catch {
|
|
208
|
+
} catch (e) {
|
|
209
|
+
if (!signal?.aborted) trace?.note("usage", { error: e })
|
|
210
|
+
}
|
|
161
211
|
if (!poll || Date.now() + STEP_WAIT.every > end) break
|
|
162
212
|
await wait(STEP_WAIT.every)
|
|
163
213
|
}
|
|
@@ -180,7 +230,10 @@ function collect(tok, conv, { poll = false, first, signal, over = () => false, a
|
|
|
180
230
|
let r = { usage: null, events: [], got: 0 }
|
|
181
231
|
if (want > 0 && canRead(tok)) r = await usageEvents(tok, conv, Math.min(...groups.map((g) => g.since)), want, {
|
|
182
232
|
poll, first, signal, abortFetch, before: () => d.before ?? Infinity, ...(d.groups ? { groups } : {}),
|
|
183
|
-
}).catch(() =>
|
|
233
|
+
}).catch((e) => {
|
|
234
|
+
trace?.note("usage", { error: e })
|
|
235
|
+
return r
|
|
236
|
+
})
|
|
184
237
|
let short = false
|
|
185
238
|
for (const [i, g] of groups.entries()) {
|
|
186
239
|
const remaining = g.n - (d.groups ? r.counts?.[i] ?? 0 : r.got)
|
|
@@ -246,9 +299,14 @@ export function ledger(tok, conv, since, signal, kept, { before } = {}) {
|
|
|
246
299
|
async own() {
|
|
247
300
|
if (!canRead(tok)) return null
|
|
248
301
|
const m = misses.get(key) ?? 0
|
|
249
|
-
const waits = m
|
|
302
|
+
const waits = stepsWait(m)
|
|
250
303
|
if (!kept) {
|
|
251
|
-
const r = waits
|
|
304
|
+
const r = waits
|
|
305
|
+
? await usageEvents(tok, conv, since, 1, { poll: true, signal }).catch((e) => {
|
|
306
|
+
trace?.note("usage", { error: e })
|
|
307
|
+
return {}
|
|
308
|
+
})
|
|
309
|
+
: {}
|
|
252
310
|
if (r.usage) misses.delete(key)
|
|
253
311
|
else if (!r.refused) misses.set(key, m + 1)
|
|
254
312
|
return r.usage ?? null
|
package/src/models.ts
CHANGED
|
@@ -6,8 +6,8 @@
|
|
|
6
6
|
* Billing-period windows live in usage.ts; per-step deferred usage in ledger.ts.
|
|
7
7
|
*/
|
|
8
8
|
// @ts-nocheck
|
|
9
|
-
import { createHash } from "node:crypto"
|
|
10
9
|
import { API, DEFAULT_CONTEXT, MODELS_KEEP, unary } from "./client.ts"
|
|
10
|
+
import { recall, store, tokenKey } from "./cache.ts"
|
|
11
11
|
|
|
12
12
|
const LEVEL_RANK = ["none", "minimal", "low", "medium", "high", "xhigh", "max"]
|
|
13
13
|
const EFFORT_PARAMS = ["effort", "reasoning_effort", "reasoning"]
|
|
@@ -241,11 +241,14 @@ function fitEffort(want, levels) {
|
|
|
241
241
|
// can't give is a failure: magpie keeps the list it had. A usable list it
|
|
242
242
|
// can't give leaves the picker as it is.
|
|
243
243
|
const lists = new Map()
|
|
244
|
+
export function modelCacheKeys() {
|
|
245
|
+
return [...lists.keys()]
|
|
246
|
+
}
|
|
244
247
|
export async function usable(tok, force = false, signal?: AbortSignal) {
|
|
248
|
+
const h = tokenKey(tok)
|
|
249
|
+
const had = recall(lists, h)
|
|
245
250
|
if (signal?.aborted) throw Object.assign(new Error("The operation was aborted"), { name: "AbortError" })
|
|
246
|
-
|
|
247
|
-
const had = lists.get(h)
|
|
248
|
-
if (!force && had && Date.now() - had.at < MODELS_KEEP) return had.raw
|
|
251
|
+
if (!force && had) return had.raw
|
|
249
252
|
const [j, ids] = await Promise.all([
|
|
250
253
|
unary(API, "aiserver.v1.AiService/AvailableModels", tok, { useModelParameters: true, doNotUseMarkdown: true }, 30_000, signal),
|
|
251
254
|
unary(API, "agent.v1.AgentService/GetUsableModels", tok, {}, 8_000, signal).then(
|
|
@@ -262,7 +265,7 @@ export async function usable(tok, force = false, signal?: AbortSignal) {
|
|
|
262
265
|
if (signal?.aborted) throw Object.assign(new Error("The operation was aborted"), { name: "AbortError" })
|
|
263
266
|
const raw = modelsOf(Array.isArray(j?.models) ? j.models : [], ids)
|
|
264
267
|
if (!raw.length) throw new Error("Cursor listed no models")
|
|
265
|
-
lists
|
|
268
|
+
store(lists, h, { raw, expires: 0 }, MODELS_KEEP)
|
|
266
269
|
return raw
|
|
267
270
|
}
|
|
268
271
|
|
package/src/native-session.ts
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* Ported from magpie's native-session.mjs (MIT):
|
|
6
6
|
* https://github.com/magpie-community/plugins/tree/main/packages/cursor
|
|
7
7
|
* Self-contained. The only import is node:crypto. Run wiring passes pb, exec,
|
|
8
|
-
* usageOf, and
|
|
8
|
+
* usageOf, failure, and trace in. This file does not import the rest of the package.
|
|
9
9
|
*/
|
|
10
10
|
import { createHash, randomBytes } from "node:crypto"
|
|
11
11
|
|
|
@@ -352,6 +352,27 @@ class Segment {
|
|
|
352
352
|
}
|
|
353
353
|
}
|
|
354
354
|
|
|
355
|
+
/** States an owner in entries can be in. fail() removes an owner as it sets failed, cancelled, or expired. */
|
|
356
|
+
export type OwnerPhase = "opening" | "running" | "submitting" | "awaiting-results" | "finalizing" | "complete"
|
|
357
|
+
|
|
358
|
+
export type OwnerView = {
|
|
359
|
+
phase: OwnerPhase
|
|
360
|
+
model: string
|
|
361
|
+
maxMode: boolean
|
|
362
|
+
/** Tool batches handed back to the caller. */
|
|
363
|
+
rounds: number
|
|
364
|
+
/** The Run's absolute lifetime deadline. */
|
|
365
|
+
lifetimeEnds: number
|
|
366
|
+
/** Whether the owner belongs to the account the reader asked about. */
|
|
367
|
+
current: boolean
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/** The pool in a form the doctor may print. */
|
|
371
|
+
export type NativeState = {
|
|
372
|
+
owners: readonly OwnerView[]
|
|
373
|
+
limits: { perAccount: number; perProcess: number }
|
|
374
|
+
}
|
|
375
|
+
|
|
355
376
|
export class NativeSessionPool {
|
|
356
377
|
constructor(limits = NATIVE_LIMITS) {
|
|
357
378
|
this.limits = limits
|
|
@@ -359,6 +380,21 @@ export class NativeSessionPool {
|
|
|
359
380
|
this.handles = new Map()
|
|
360
381
|
this.selectors = new Map()
|
|
361
382
|
}
|
|
383
|
+
// Takes anything with Account's is(), so this file imports nothing. Unlike
|
|
384
|
+
// prepare, create, and response(), it changes no owner.
|
|
385
|
+
state(account?: { is(fingerprint: string): boolean }): NativeState {
|
|
386
|
+
return {
|
|
387
|
+
owners: [...this.entries].sort((a, b) => a.expiresAt - b.expiresAt).map((owner) => ({
|
|
388
|
+
phase: owner.state,
|
|
389
|
+
model: owner.resolution?.id ?? "",
|
|
390
|
+
maxMode: !!owner.resolution?.maxMode,
|
|
391
|
+
rounds: owner.segments,
|
|
392
|
+
lifetimeEnds: owner.expiresAt,
|
|
393
|
+
current: !!account?.is(owner.account),
|
|
394
|
+
})),
|
|
395
|
+
limits: { perAccount: this.limits.perAccount, perProcess: this.limits.perProcess },
|
|
396
|
+
}
|
|
397
|
+
}
|
|
362
398
|
// selector is conversationID(chat, session): session/cache key AND first
|
|
363
399
|
// user identity. Task subagents sharing a session must not own its parent.
|
|
364
400
|
prepare(tok, chat, selector, tools) {
|
|
@@ -401,7 +437,7 @@ export class NativeSessionPool {
|
|
|
401
437
|
return { owner, batch, results, encoded, digest, chat }
|
|
402
438
|
} catch (e) {
|
|
403
439
|
if (!(e instanceof NativeSessionError)) throw e
|
|
404
|
-
return fallback
|
|
440
|
+
return { fallback: "history incompatible with retained owner", detail: e.message }
|
|
405
441
|
}
|
|
406
442
|
}
|
|
407
443
|
// Pending ancestors, new input, and terminal old handles are ordinary
|
|
@@ -411,19 +447,20 @@ export class NativeSessionPool {
|
|
|
411
447
|
return { account, selector, controls, selected: !!selector, chat }
|
|
412
448
|
}
|
|
413
449
|
create(prepared, resolution, wire) {
|
|
414
|
-
if (prepared.fallback
|
|
450
|
+
if (prepared.fallback) return prepared
|
|
451
|
+
if (prepared.selected && this.selectors.has(prepared.account + ":" + prepared.selector)) return { fallback: "owner busy" }
|
|
415
452
|
const crowded = () => this.entries.size >= this.limits.perProcess || [...this.entries].filter((e) => e.account === prepared.account).length >= this.limits.perAccount
|
|
416
453
|
while (crowded()) {
|
|
417
454
|
const accountFull = [...this.entries].filter((e) => e.account === prepared.account).length >= this.limits.perAccount
|
|
418
455
|
const finished = [...this.entries].find((e) => ["complete", "failed", "cancelled", "expired"].includes(e.state) && (!accountFull || e.account === prepared.account))
|
|
419
|
-
if (!finished) return
|
|
456
|
+
if (!finished) return { fallback: accountFull ? "account owner limit" : "process owner limit" }
|
|
420
457
|
this.forget(finished)
|
|
421
458
|
}
|
|
422
459
|
let owner
|
|
423
460
|
try { owner = new NativeSession(this, prepared, resolution, wire) }
|
|
424
461
|
catch (e) {
|
|
425
462
|
if (!(e instanceof NativeSessionError)) throw e
|
|
426
|
-
return
|
|
463
|
+
return { fallback: "opening history not retainable", detail: e.message }
|
|
427
464
|
}
|
|
428
465
|
this.entries.add(owner)
|
|
429
466
|
if (prepared.selected) this.selectors.set(owner.account + ":" + owner.selector, owner)
|
|
@@ -524,6 +561,7 @@ class NativeSession {
|
|
|
524
561
|
if (this.error || this.state === "complete") return
|
|
525
562
|
this.error = error
|
|
526
563
|
this.state = state
|
|
564
|
+
this.wire.trace?.note("owner-ended", { state, model: this.resolution?.id, error })
|
|
527
565
|
this.segment.fail(error)
|
|
528
566
|
for (const segment of this.batches ?? []) segment.detach?.()
|
|
529
567
|
this.segment.detach?.()
|
package/src/run.ts
CHANGED
|
@@ -24,8 +24,10 @@ import { isDeepStrictEqual } from "node:util"
|
|
|
24
24
|
import { EMPTY, failure, field, fields, frame, frames, pb, pbAny, pbNum, pbStr, pbValue, regional } from "./codec.ts"
|
|
25
25
|
import { AGENT, API, CALL, GOOS, NAMESPACE, clientVersion, tempDir, unary } from "./client.ts"
|
|
26
26
|
import { canRead, ledger, owe, STEP_WAIT, usageKey } from "./ledger.ts"
|
|
27
|
+
import { recall, store, tokenKey } from "./cache.ts"
|
|
27
28
|
import { request as resolveModel, usable } from "./models.ts"
|
|
28
29
|
import { NATIVE_LIMITS, NativeSessionError, nativeFields, nativeMcpArgs, nativeSessions } from "./native-session.ts"
|
|
30
|
+
import { hostOf, trace, type Account, type Host } from "./trace.ts"
|
|
29
31
|
|
|
30
32
|
const NO_RESULT = "Tool use was interrupted and did not produce a result."
|
|
31
33
|
|
|
@@ -297,12 +299,18 @@ function buildRun(msgs, lastUser, tools, model, conv = "", { maxMode = false, pa
|
|
|
297
299
|
// while it can't be had.
|
|
298
300
|
|
|
299
301
|
const endpoints = new Map()
|
|
302
|
+
const ENDPOINT_TTL = 10 * 60 * 1000
|
|
303
|
+
const ENDPOINT_MISS_TTL = 60_000
|
|
304
|
+
export function endpointCacheKeys() {
|
|
305
|
+
return [...endpoints.keys()]
|
|
306
|
+
}
|
|
300
307
|
export async function agentURL(tok, fresh, signal?: AbortSignal) {
|
|
301
|
-
const key =
|
|
302
|
-
const had = endpoints
|
|
303
|
-
if (!fresh && had
|
|
308
|
+
const key = tokenKey(tok)
|
|
309
|
+
const had = recall(endpoints, key)
|
|
310
|
+
if (!fresh && had) return had.url
|
|
304
311
|
let url = AGENT
|
|
305
312
|
let listed = false
|
|
313
|
+
let error
|
|
306
314
|
try {
|
|
307
315
|
const cfg = await unary(API, "aiserver.v1.ServerConfigService/GetServerConfig", tok, {}, 10_000, signal)
|
|
308
316
|
for (const raw of [cfg?.agentUrlConfig?.agentUrl, cfg?.agentUrlConfig?.agentnUrl]) {
|
|
@@ -317,11 +325,14 @@ export async function agentURL(tok, fresh, signal?: AbortSignal) {
|
|
|
317
325
|
}
|
|
318
326
|
} catch (e) {
|
|
319
327
|
if (signal?.aborted) throw e
|
|
328
|
+
error = e
|
|
320
329
|
}
|
|
321
330
|
if (signal?.aborted) throw Object.assign(new Error("The operation was aborted"), { name: "AbortError" })
|
|
322
331
|
// A refresh that learns nothing must not replace a regional URL with the global one.
|
|
323
|
-
|
|
324
|
-
|
|
332
|
+
const kept = !listed && fresh && !!had?.url
|
|
333
|
+
trace?.note("endpoint", { url: kept ? had.url : url, listed, kept, error })
|
|
334
|
+
if (kept) return had.url
|
|
335
|
+
store(endpoints, key, { url, listed, expires: 0 }, listed ? ENDPOINT_TTL : ENDPOINT_MISS_TTL)
|
|
325
336
|
return url
|
|
326
337
|
}
|
|
327
338
|
|
|
@@ -519,7 +530,9 @@ async function open(base, headers, signal, connect = defaultConnect, headerWaitM
|
|
|
519
530
|
if (signal?.aborted) return cancelledOpen()
|
|
520
531
|
// Injected connect (tests): HTTP/2 only, keep the caller's header wait.
|
|
521
532
|
if (connect !== defaultConnect) {
|
|
522
|
-
|
|
533
|
+
const o = await openH2(base, headers, signal, connect, headerWaitMs)
|
|
534
|
+
if (!o.error) trace?.note("transport", { url: base, h1: false })
|
|
535
|
+
return o
|
|
523
536
|
}
|
|
524
537
|
if (Date.now() >= h1Until) {
|
|
525
538
|
const o = await openH2(base, headers, signal, defaultConnect, headerWaitMs)
|
|
@@ -528,15 +541,46 @@ async function open(base, headers, signal, connect = defaultConnect, headerWaitM
|
|
|
528
541
|
try { o.session?.destroy?.() } catch {}
|
|
529
542
|
return cancelledOpen()
|
|
530
543
|
}
|
|
531
|
-
if (!o.h2Failed)
|
|
544
|
+
if (!o.h2Failed) {
|
|
545
|
+
trace?.note("transport", { url: base, h1: false })
|
|
546
|
+
return o
|
|
547
|
+
}
|
|
532
548
|
if (o.blocked) h1Until = Date.now() + H2.retryAfter
|
|
533
|
-
|
|
549
|
+
trace?.note("transport", { url: API, h1: true, h2: { url: base, error: o.error }, until: o.blocked ? h1Until : undefined })
|
|
550
|
+
} else trace?.note("transport", { url: API, h1: true, until: h1Until })
|
|
534
551
|
if (signal?.aborted) return cancelledOpen()
|
|
535
552
|
return openH1(headers, signal)
|
|
536
553
|
}
|
|
537
554
|
|
|
538
555
|
export function resetH1() { h1Until = 0 }
|
|
539
|
-
|
|
556
|
+
|
|
557
|
+
/** What run.ts keeps between turns, in a form the doctor may print. */
|
|
558
|
+
export type RunState = {
|
|
559
|
+
transport: { via: "h2" } | { via: "h1"; until: number }
|
|
560
|
+
/** This account's agent host. null before a turn asked, after the entry expired, or without an account. */
|
|
561
|
+
agent: { host: Host; source: "server-config" | "global-fallback"; until: number } | null
|
|
562
|
+
/** Live agent hosts cached for other accounts. */
|
|
563
|
+
otherAgents: number
|
|
564
|
+
/** Models Cursor said need max mode. Later turns ask for it. */
|
|
565
|
+
maxModeForced: readonly string[]
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
// Walks endpoints without recall(), which deletes the expired entries this skips.
|
|
569
|
+
export function runState(account: Account | undefined, now = Date.now()): RunState {
|
|
570
|
+
let agent = null
|
|
571
|
+
let otherAgents = 0
|
|
572
|
+
for (const [key, entry] of endpoints) {
|
|
573
|
+
if (now >= entry.expires) continue
|
|
574
|
+
if (account?.is(key)) agent = { host: hostOf(entry.url), source: entry.listed ? "server-config" : "global-fallback", until: entry.expires }
|
|
575
|
+
else otherAgents++
|
|
576
|
+
}
|
|
577
|
+
return {
|
|
578
|
+
transport: now < h1Until ? { via: "h1", until: h1Until } : { via: "h2" },
|
|
579
|
+
agent,
|
|
580
|
+
otherAgents,
|
|
581
|
+
maxModeForced: [...maxOnly].sort(),
|
|
582
|
+
}
|
|
583
|
+
}
|
|
540
584
|
|
|
541
585
|
// decode follows the server's messages into the answer's pieces until the
|
|
542
586
|
// turn ends, or the model has made its tool calls. stepUsage / owedUsage are
|
|
@@ -873,12 +917,16 @@ async function runOnce({ tok, base, id, tools, conv, convID, signal, maxMode, pa
|
|
|
873
917
|
send(first)
|
|
874
918
|
if (o.status < 200 || o.status > 299) {
|
|
875
919
|
const chunks = []
|
|
920
|
+
let bodyCut = false
|
|
876
921
|
try {
|
|
877
922
|
for await (const c of req) chunks.push(c)
|
|
878
|
-
} catch {
|
|
923
|
+
} catch {
|
|
924
|
+
bodyCut = true
|
|
925
|
+
}
|
|
879
926
|
close()
|
|
880
927
|
book.done()
|
|
881
|
-
|
|
928
|
+
const error = failure(o.status, Buffer.concat(chunks).toString("utf8").slice(0, 1 << 20))
|
|
929
|
+
return { error: bodyCut ? { ...error, bodyCut } : error, h1: !!o.h1 }
|
|
882
930
|
}
|
|
883
931
|
const it = decode(frames(req), {
|
|
884
932
|
send,
|
|
@@ -1157,25 +1205,7 @@ export function clearMaxOnly() {
|
|
|
1157
1205
|
export { nativeSessions } from "./native-session.ts"
|
|
1158
1206
|
export { STEP_WAIT, ledger, owed, misses, unreadable, clearLedger, usageKey } from "./ledger.ts"
|
|
1159
1207
|
|
|
1160
|
-
|
|
1161
|
-
export async function runAnswer({
|
|
1162
|
-
tok,
|
|
1163
|
-
model,
|
|
1164
|
-
effort = "",
|
|
1165
|
-
fast,
|
|
1166
|
-
messages,
|
|
1167
|
-
tools = [],
|
|
1168
|
-
session = "",
|
|
1169
|
-
signal,
|
|
1170
|
-
connect,
|
|
1171
|
-
resolveAgentURL = agentURL,
|
|
1172
|
-
rawModels,
|
|
1173
|
-
onResponse,
|
|
1174
|
-
onPayload,
|
|
1175
|
-
headers,
|
|
1176
|
-
headerWaitMs = H2.wait,
|
|
1177
|
-
toolIdleMs = TOOL_IDLE_MS,
|
|
1178
|
-
}: {
|
|
1208
|
+
export type RunAnswerOptions = {
|
|
1179
1209
|
tok: string
|
|
1180
1210
|
model?: string
|
|
1181
1211
|
effort?: string
|
|
@@ -1192,7 +1222,9 @@ export async function runAnswer({
|
|
|
1192
1222
|
headers?: Record<string, string | null | undefined>
|
|
1193
1223
|
headerWaitMs?: number
|
|
1194
1224
|
toolIdleMs?: number
|
|
1195
|
-
}
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
export type RunAnswerResult = {
|
|
1196
1228
|
error?: { status?: number; message?: string }
|
|
1197
1229
|
conversationId?: string
|
|
1198
1230
|
events?: AsyncIterable<{
|
|
@@ -1208,7 +1240,37 @@ export async function runAnswer({
|
|
|
1208
1240
|
}
|
|
1209
1241
|
error?: { status?: number; message?: string }
|
|
1210
1242
|
}>
|
|
1211
|
-
}
|
|
1243
|
+
}
|
|
1244
|
+
|
|
1245
|
+
/** One user-visible turn. A regional miss retries once, and only when the agent URL changed. */
|
|
1246
|
+
export async function runAnswer(opts: RunAnswerOptions): Promise<RunAnswerResult> {
|
|
1247
|
+
const t = trace
|
|
1248
|
+
if (!t) return answer(opts)
|
|
1249
|
+
return t.within({ token: opts.tok, model: opts.model }, async () => {
|
|
1250
|
+
const ran = await answer(opts)
|
|
1251
|
+
if (ran.error && !opts.signal?.aborted) t.note("failed", { error: ran.error })
|
|
1252
|
+
return ran.events ? { ...ran, events: t.carry(ran.events) } : ran
|
|
1253
|
+
})
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
async function answer({
|
|
1257
|
+
tok,
|
|
1258
|
+
model,
|
|
1259
|
+
effort = "",
|
|
1260
|
+
fast,
|
|
1261
|
+
messages,
|
|
1262
|
+
tools = [],
|
|
1263
|
+
session = "",
|
|
1264
|
+
signal,
|
|
1265
|
+
connect,
|
|
1266
|
+
resolveAgentURL = agentURL,
|
|
1267
|
+
rawModels,
|
|
1268
|
+
onResponse,
|
|
1269
|
+
onPayload,
|
|
1270
|
+
headers,
|
|
1271
|
+
headerWaitMs = H2.wait,
|
|
1272
|
+
toolIdleMs = TOOL_IDLE_MS,
|
|
1273
|
+
}: RunAnswerOptions): Promise<RunAnswerResult> {
|
|
1212
1274
|
const chat = {
|
|
1213
1275
|
model,
|
|
1214
1276
|
messages,
|
|
@@ -1230,6 +1292,7 @@ export async function runAnswer({
|
|
|
1230
1292
|
try {
|
|
1231
1293
|
const conv = conversation(chat, listed)
|
|
1232
1294
|
const resumed = prepared.owner.resume({ ...prepared, estimate: conv.estimate }, signal)
|
|
1295
|
+
trace?.note("native", { path: "resumed" })
|
|
1233
1296
|
return { conversationId: convID, events: withDelivery(prepared.owner, resumed.events) }
|
|
1234
1297
|
} catch (e) {
|
|
1235
1298
|
return { error: { status: e?.status ?? 502, message: e?.message ?? String(e) } }
|
|
@@ -1250,10 +1313,15 @@ export async function runAnswer({
|
|
|
1250
1313
|
const conv = conversation(chat, listed)
|
|
1251
1314
|
let base = await resolveAgentURL(tok, false, signal)
|
|
1252
1315
|
const once = async () => {
|
|
1253
|
-
const
|
|
1316
|
+
const made = nativeSessions.create(prepared, { id, maxMode, params }, { pb, exec, usageOf, failure, trace })
|
|
1317
|
+
const native = made.fallback ? null : made
|
|
1318
|
+
trace?.note("native", native ? { path: "created" } : { path: "declined", fallback: made.fallback, detail: made.detail })
|
|
1254
1319
|
const args = { tok, base, id, tools: listed, conv, convID, signal, maxMode, params, connect, onResponse, onPayload, headers, headerWaitMs, toolIdleMs }
|
|
1255
1320
|
let response = native ? await runNative({ ...args, native }) : await runOnce(args)
|
|
1256
|
-
if (response.error?.retentionIneligible && !signal?.aborted)
|
|
1321
|
+
if (response.error?.retentionIneligible && !signal?.aborted) {
|
|
1322
|
+
trace?.note("native", { path: "abandoned", error: response.error })
|
|
1323
|
+
response = await runOnce(args)
|
|
1324
|
+
}
|
|
1257
1325
|
return response
|
|
1258
1326
|
}
|
|
1259
1327
|
let ran = await once()
|
|
@@ -1262,13 +1330,16 @@ export async function runAnswer({
|
|
|
1262
1330
|
resetH1()
|
|
1263
1331
|
const fresh = await resolveAgentURL(tok, true, signal)
|
|
1264
1332
|
const viaH1 = !!ran.h1
|
|
1265
|
-
|
|
1333
|
+
const again = (fresh !== base || viaH1) && !signal?.aborted
|
|
1334
|
+
trace?.note("retry", { rule: "region", error: ran.error, to: again ? fresh : undefined, cancelled: !!signal?.aborted })
|
|
1335
|
+
if (again) {
|
|
1266
1336
|
base = fresh
|
|
1267
1337
|
ran = await once()
|
|
1268
1338
|
}
|
|
1269
1339
|
}
|
|
1270
1340
|
if (signal?.aborted) return ran
|
|
1271
1341
|
if (ran.error && !maxMode && maxRequired(ran.error.message)) {
|
|
1342
|
+
trace?.note("retry", { rule: "max-mode", error: ran.error, model: id })
|
|
1272
1343
|
maxMode = true
|
|
1273
1344
|
maxOnly.add(id)
|
|
1274
1345
|
ran = await once()
|
package/src/trace.ts
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a diagnostic may print, and the decision journal that CURSOR_DEBUG turns on.
|
|
3
|
+
* A Decision holds only hosts, reasons scrubbed by reasonOf, statuses, model ids,
|
|
4
|
+
* and clock times. An Account compares fingerprints and prints as "[account]".
|
|
5
|
+
*/
|
|
6
|
+
import { AsyncLocalStorage } from "node:async_hooks"
|
|
7
|
+
import { inspect, isDeepStrictEqual } from "node:util"
|
|
8
|
+
import { tokenKey } from "./cache.ts"
|
|
9
|
+
|
|
10
|
+
/** The host and port of a URL. An endpoint is printed only in this form. */
|
|
11
|
+
export type Host = string & { readonly __brand: "Host" }
|
|
12
|
+
|
|
13
|
+
/** Error or refusal text after reasonOf scrubbed and clipped it. */
|
|
14
|
+
export type Reason = string & { readonly __brand: "Reason" }
|
|
15
|
+
|
|
16
|
+
export function hostOf(url: string): Host {
|
|
17
|
+
try {
|
|
18
|
+
return new URL(url).host as Host
|
|
19
|
+
} catch {
|
|
20
|
+
return "(unparseable URL)" as Host
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const REASON_MAX = 200
|
|
25
|
+
|
|
26
|
+
function reasonOf(cause: unknown): Reason {
|
|
27
|
+
const error = cause as { message?: unknown; code?: unknown } | null | undefined
|
|
28
|
+
let text = typeof cause === "string" ? cause : String(error?.message ?? cause ?? "")
|
|
29
|
+
const code = typeof error?.code === "string" ? error.code : ""
|
|
30
|
+
if (code && !text.includes(code)) text += ` (${code})`
|
|
31
|
+
text = text
|
|
32
|
+
.replace(/\bBearer\s+\S+/gi, "Bearer [token]")
|
|
33
|
+
.replace(/\bhttps?:\/\/[^\s"'<>()]*[^\s"'<>().,;:!?]/gi, (url) => hostOf(url))
|
|
34
|
+
.replace(/eyJ[\w-]*\.[\w-]*\.[\w-]*/g, "[token]")
|
|
35
|
+
.replace(/[0-9a-f]{32,}/gi, "[hex]")
|
|
36
|
+
.replace(/[\w-]{40,}/g, "[token]")
|
|
37
|
+
.replace(/\s+/g, " ")
|
|
38
|
+
.trim()
|
|
39
|
+
return (text.length > REASON_MAX ? text.slice(0, REASON_MAX - 1) + "…" : text) as Reason
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** One access token as this process knows it. It compares and never prints. */
|
|
43
|
+
export class Account {
|
|
44
|
+
#fingerprint: string
|
|
45
|
+
private constructor(fingerprint: string) {
|
|
46
|
+
this.#fingerprint = fingerprint
|
|
47
|
+
}
|
|
48
|
+
static of(token: string): Account {
|
|
49
|
+
return new Account(tokenKey(token))
|
|
50
|
+
}
|
|
51
|
+
/** Whether a store key, or an owner's account, is this account's fingerprint. */
|
|
52
|
+
is(fingerprint: string): boolean {
|
|
53
|
+
return fingerprint === this.#fingerprint
|
|
54
|
+
}
|
|
55
|
+
same(other: Account): boolean {
|
|
56
|
+
return other.#fingerprint === this.#fingerprint
|
|
57
|
+
}
|
|
58
|
+
toString(): string {
|
|
59
|
+
return "[account]"
|
|
60
|
+
}
|
|
61
|
+
toJSON(): string {
|
|
62
|
+
return "[account]"
|
|
63
|
+
}
|
|
64
|
+
[inspect.custom](): string {
|
|
65
|
+
return "[account]"
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export type Decision =
|
|
70
|
+
| { kind: "endpoint"; source: "server-config"; host: Host }
|
|
71
|
+
| { kind: "endpoint"; source: "global-fallback" | "kept-regional"; host: Host; why: Reason }
|
|
72
|
+
| { kind: "transport"; via: "h2"; host: Host }
|
|
73
|
+
| { kind: "transport"; via: "h1"; host: Host; cause: "sticky"; until: number }
|
|
74
|
+
| { kind: "transport"; via: "h1"; host: Host; cause: "h2-failed"; h2Host: Host; why: Reason; until: number | null }
|
|
75
|
+
| { kind: "native"; path: "resumed" | "created" }
|
|
76
|
+
| { kind: "native"; path: "declined" | "abandoned"; why: Reason }
|
|
77
|
+
| { kind: "owner-ended"; phase: "failed" | "cancelled" | "expired"; model: string; why: Reason }
|
|
78
|
+
| ({ kind: "retry"; rule: "region"; status: number; why: Reason } & ({ retriedOn: Host } | { notRetried: "same-host-over-h2" | "cancelled" }))
|
|
79
|
+
| { kind: "retry"; rule: "max-mode"; status: number; why: Reason; model: string }
|
|
80
|
+
| { kind: "failed"; status: number; why: Reason; bodyCut: boolean }
|
|
81
|
+
| { kind: "usage"; outcome: "refused" | "unavailable"; status: number }
|
|
82
|
+
| { kind: "usage"; outcome: "failed"; why: Reason }
|
|
83
|
+
|
|
84
|
+
/** A journaled decision. An identical neighbour in the same turn folds into count. */
|
|
85
|
+
export type Entry = Decision & { at: number; count: number }
|
|
86
|
+
|
|
87
|
+
/** One runAnswer call. Turn 0 holds decisions noted outside any turn, with no account. */
|
|
88
|
+
export type TurnLog = {
|
|
89
|
+
readonly turn: number
|
|
90
|
+
readonly started: number
|
|
91
|
+
readonly model: string
|
|
92
|
+
readonly account: Account | null
|
|
93
|
+
readonly entries: readonly Entry[]
|
|
94
|
+
/** Decisions refused after the turn kept ENTRIES of them. */
|
|
95
|
+
readonly dropped: number
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export type Trace = {
|
|
99
|
+
note<K extends Decision["kind"]>(kind: K, raw: RawFact<K>): void
|
|
100
|
+
within<T>(turn: { token: string; model?: string }, run: () => Promise<T>): Promise<T>
|
|
101
|
+
/** Keeps a stream that the turn returns inside its log. Call it inside within(). */
|
|
102
|
+
carry<E>(events: AsyncIterable<E>): AsyncIterable<E>
|
|
103
|
+
/** The last TURNS logs, oldest first, then turn 0 when it holds entries. */
|
|
104
|
+
turns(): readonly TurnLog[]
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const TURNS = 16
|
|
108
|
+
const ENTRIES = 32
|
|
109
|
+
const NO_AGENT = "GetServerConfig named no agent host"
|
|
110
|
+
|
|
111
|
+
type Failure = { status?: number; message?: string } | undefined
|
|
112
|
+
type Fields<D> = D extends unknown ? Omit<D, "kind"> : never
|
|
113
|
+
type Of<K extends Decision["kind"]> = Fields<Extract<Decision, { kind: K }>>
|
|
114
|
+
type RawFact<K extends Decision["kind"]> = Parameters<(typeof parse)[K]>[0]
|
|
115
|
+
|
|
116
|
+
const statusIn = (error: Failure) => (typeof error?.status === "number" ? error.status : 502)
|
|
117
|
+
|
|
118
|
+
// The checker does not read the files that note decisions. Each parser picks
|
|
119
|
+
// named fields and never spreads its input, so a stray token or header cannot
|
|
120
|
+
// reach a log.
|
|
121
|
+
const parse = {
|
|
122
|
+
endpoint: (raw: { url: string; listed: boolean; kept: boolean; error?: unknown }): Of<"endpoint"> =>
|
|
123
|
+
raw.listed
|
|
124
|
+
? { source: "server-config", host: hostOf(raw.url) }
|
|
125
|
+
: { source: raw.kept ? "kept-regional" : "global-fallback", host: hostOf(raw.url), why: reasonOf(raw.error ?? NO_AGENT) },
|
|
126
|
+
transport: (raw: { url: string; h1: boolean; h2?: { url: string; error: unknown }; until?: number }): Of<"transport"> => {
|
|
127
|
+
if (!raw.h1) return { via: "h2", host: hostOf(raw.url) }
|
|
128
|
+
if (!raw.h2) return { via: "h1", host: hostOf(raw.url), cause: "sticky", until: raw.until ?? 0 }
|
|
129
|
+
return { via: "h1", host: hostOf(raw.url), cause: "h2-failed", h2Host: hostOf(raw.h2.url), why: reasonOf(raw.h2.error), until: raw.until ?? null }
|
|
130
|
+
},
|
|
131
|
+
native: (raw: { path: "resumed" | "created" | "declined" | "abandoned"; fallback?: string; detail?: string; error?: unknown }): Of<"native"> => {
|
|
132
|
+
if (raw.path === "resumed" || raw.path === "created") return { path: raw.path }
|
|
133
|
+
if (raw.path === "abandoned") return { path: raw.path, why: reasonOf(raw.error) }
|
|
134
|
+
return { path: raw.path, why: reasonOf(raw.detail ? `${raw.fallback} (${raw.detail})` : raw.fallback) }
|
|
135
|
+
},
|
|
136
|
+
"owner-ended": (raw: { state: "failed" | "cancelled" | "expired"; model?: string; error: unknown }): Of<"owner-ended"> => ({
|
|
137
|
+
phase: raw.state,
|
|
138
|
+
model: String(raw.model ?? ""),
|
|
139
|
+
why: reasonOf(raw.error),
|
|
140
|
+
}),
|
|
141
|
+
retry: (raw: { rule: "region"; error: Failure; to?: string; cancelled: boolean } | { rule: "max-mode"; error: Failure; model: string }): Of<"retry"> => {
|
|
142
|
+
const status = statusIn(raw.error)
|
|
143
|
+
const why = reasonOf(raw.error)
|
|
144
|
+
if (raw.rule === "max-mode") return { rule: "max-mode", status, why, model: String(raw.model ?? "") }
|
|
145
|
+
if (raw.to) return { rule: "region", status, why, retriedOn: hostOf(raw.to) }
|
|
146
|
+
return { rule: "region", status, why, notRetried: raw.cancelled ? "cancelled" : "same-host-over-h2" }
|
|
147
|
+
},
|
|
148
|
+
failed: (raw: { error: Failure & { bodyCut?: boolean } }): Of<"failed"> => ({
|
|
149
|
+
status: statusIn(raw.error),
|
|
150
|
+
why: reasonOf(raw.error),
|
|
151
|
+
bodyCut: raw.error?.bodyCut === true,
|
|
152
|
+
}),
|
|
153
|
+
usage: (raw: { status?: number; refused?: boolean; error?: unknown }): Of<"usage"> =>
|
|
154
|
+
raw.status === undefined ? { outcome: "failed", why: reasonOf(raw.error) } : { outcome: raw.refused ? "refused" : "unavailable", status: raw.status },
|
|
155
|
+
} satisfies { [K in Decision["kind"]]: (raw: never) => Of<K> }
|
|
156
|
+
|
|
157
|
+
type Log = { turn: number; started: number; model: string; account: Account | null; entries: Entry[]; dropped: number }
|
|
158
|
+
|
|
159
|
+
function sameDecision(entry: Entry, decision: Decision): boolean {
|
|
160
|
+
const { at: _at, count: _count, ...rest } = entry
|
|
161
|
+
return isDeepStrictEqual(rest, decision)
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function enabled(value: string | undefined): boolean {
|
|
165
|
+
const v = (value ?? "").trim().toLowerCase()
|
|
166
|
+
return v !== "" && !["0", "false", "off", "no"].includes(v)
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function createTrace(): Trace {
|
|
170
|
+
const scope = new AsyncLocalStorage<Log>()
|
|
171
|
+
const logs: Log[] = []
|
|
172
|
+
const outside: Log = { turn: 0, started: Date.now(), model: "", account: null, entries: [], dropped: 0 }
|
|
173
|
+
let next = 1
|
|
174
|
+
return {
|
|
175
|
+
note(kind, raw) {
|
|
176
|
+
if (!Object.hasOwn(parse, kind)) return
|
|
177
|
+
const decision = { kind, ...(parse[kind] as (raw: unknown) => object)(raw) } as Decision
|
|
178
|
+
const log = scope.getStore() ?? outside
|
|
179
|
+
const last = log.entries.at(-1)
|
|
180
|
+
const now = Date.now()
|
|
181
|
+
if (last && sameDecision(last, decision)) {
|
|
182
|
+
last.count += 1
|
|
183
|
+
last.at = now
|
|
184
|
+
} else if (log.entries.length >= ENTRIES) log.dropped += 1
|
|
185
|
+
else log.entries.push({ ...decision, at: now, count: 1 })
|
|
186
|
+
},
|
|
187
|
+
within(turn, run) {
|
|
188
|
+
const log: Log = { turn: next++, started: Date.now(), model: turn.model ?? "", account: Account.of(turn.token), entries: [], dropped: 0 }
|
|
189
|
+
logs.push(log)
|
|
190
|
+
while (logs.length > TURNS) logs.shift()
|
|
191
|
+
return scope.run(log, run)
|
|
192
|
+
},
|
|
193
|
+
// The consumer reads events after runAnswer has returned, and
|
|
194
|
+
// AsyncLocalStorage does not follow a generator into a later next().
|
|
195
|
+
carry<E>(events: AsyncIterable<E>): AsyncIterable<E> {
|
|
196
|
+
const log = scope.getStore()
|
|
197
|
+
if (!log) return events
|
|
198
|
+
const it = events[Symbol.asyncIterator]()
|
|
199
|
+
const carried: AsyncIterableIterator<E> = {
|
|
200
|
+
next: () => scope.run(log, () => it.next()),
|
|
201
|
+
return: (value?: unknown) => scope.run(log, () => it.return?.(value) ?? Promise.resolve({ done: true as const, value: undefined })),
|
|
202
|
+
[Symbol.asyncIterator]: () => carried,
|
|
203
|
+
}
|
|
204
|
+
return carried
|
|
205
|
+
},
|
|
206
|
+
turns() {
|
|
207
|
+
return outside.entries.length ? [...logs, outside] : [...logs]
|
|
208
|
+
},
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// Declared after everything createTrace reads at module load.
|
|
213
|
+
export let trace: Trace | undefined = enabled(process.env.CURSOR_DEBUG) ? createTrace() : undefined
|
|
214
|
+
|
|
215
|
+
/** For tests. Swaps in a fresh, empty journal, or none. */
|
|
216
|
+
export function traceForTests(on: boolean): void {
|
|
217
|
+
trace = on ? createTrace() : undefined
|
|
218
|
+
}
|
package/src/usage.ts
CHANGED
|
@@ -9,11 +9,12 @@
|
|
|
9
9
|
*/
|
|
10
10
|
import { STATUS_CODES } from "node:http"
|
|
11
11
|
import { API, unary } from "./client.ts"
|
|
12
|
+
import { tokenKey, recall, store } from "./cache.ts"
|
|
12
13
|
|
|
13
14
|
export const WEBSITE = "https://cursor.com"
|
|
14
15
|
|
|
15
16
|
const PLAN_TTL = 3600_000
|
|
16
|
-
const plans = new Map<string, { plan: string;
|
|
17
|
+
const plans = new Map<string, { plan: string; expires: number }>()
|
|
17
18
|
|
|
18
19
|
function until(ms: number, signal?: AbortSignal): AbortSignal {
|
|
19
20
|
const deadline = AbortSignal.timeout(ms)
|
|
@@ -179,20 +180,25 @@ async function periodUsage(tok: string, ids: string[], signal?: AbortSignal): Pr
|
|
|
179
180
|
}
|
|
180
181
|
|
|
181
182
|
async function planOf(tok: string, signal?: AbortSignal): Promise<string> {
|
|
182
|
-
const
|
|
183
|
-
|
|
183
|
+
const key = tokenKey(tok)
|
|
184
|
+
const had = recall(plans, key)
|
|
185
|
+
if (had) return had.plan
|
|
184
186
|
try {
|
|
185
187
|
const body = await unary(API, "aiserver.v1.DashboardService/GetPlanInfo", tok, {}, 15_000, signal)
|
|
186
188
|
if (signal?.aborted) throw Object.assign(new Error("The operation was aborted"), { name: "AbortError" })
|
|
187
189
|
const plan = String(body?.planInfo?.planName ?? "").trim()
|
|
188
|
-
if (plan) plans
|
|
189
|
-
return plan
|
|
190
|
+
if (plan) store(plans, key, { plan, expires: 0 }, PLAN_TTL)
|
|
191
|
+
return plan
|
|
190
192
|
} catch (err) {
|
|
191
193
|
if (cancelled(signal, err)) throw err
|
|
192
|
-
return
|
|
194
|
+
return ""
|
|
193
195
|
}
|
|
194
196
|
}
|
|
195
197
|
|
|
198
|
+
export function planCacheKeys(): string[] {
|
|
199
|
+
return [...plans.keys()]
|
|
200
|
+
}
|
|
201
|
+
|
|
196
202
|
async function botUsage(tok: string, signal?: AbortSignal): Promise<UsageWindow[]> {
|
|
197
203
|
try {
|
|
198
204
|
const subject = JSON.parse(Buffer.from(tok.split(".")[1] ?? "", "base64url").toString()).sub
|