@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 +19 -0
- package/README.md +50 -4
- package/package.json +16 -4
- package/src/auth.ts +29 -32
- package/src/cache.ts +38 -0
- package/src/client.ts +13 -14
- package/src/config.ts +5 -4
- package/src/doctor.ts +149 -0
- package/src/fast-autocomplete.ts +21 -0
- package/src/fast-footer.ts +83 -0
- package/src/fast.ts +156 -0
- package/src/index.ts +118 -54
- package/src/ledger.ts +65 -9
- package/src/models.ts +35 -9
- package/src/native-session.ts +43 -5
- package/src/pi-stream.ts +12 -2
- package/src/run.ts +127 -47
- package/src/sleep.ts +29 -0
- package/src/trace.ts +218 -0
- package/src/usage.ts +44 -20
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,21 @@
|
|
|
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 }>()
|
|
18
|
+
|
|
19
|
+
function until(ms: number, signal?: AbortSignal): AbortSignal {
|
|
20
|
+
const deadline = AbortSignal.timeout(ms)
|
|
21
|
+
return signal ? AbortSignal.any([deadline, signal]) : deadline
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function cancelled(signal: AbortSignal | undefined, err: unknown): boolean {
|
|
25
|
+
return signal?.aborted === true || (err instanceof Error && err.name === "AbortError")
|
|
26
|
+
}
|
|
17
27
|
|
|
18
28
|
export type UsageWindow = {
|
|
19
29
|
name: string
|
|
@@ -102,31 +112,32 @@ export function onDemandOf(data: { spendLimitUsage?: Spend } | undefined, hard:
|
|
|
102
112
|
return limit > 0 ? { kind: "fixed", usedDollars, limitDollars: limit } : { kind: "disabled", usedDollars }
|
|
103
113
|
}
|
|
104
114
|
|
|
105
|
-
async function hardLimit(tok: string): Promise<HardLimit | undefined> {
|
|
115
|
+
async function hardLimit(tok: string, signal?: AbortSignal): Promise<HardLimit | undefined> {
|
|
106
116
|
try {
|
|
107
117
|
const res = await fetch(API + "/aiserver.v1.DashboardService/GetHardLimit", {
|
|
108
118
|
method: "POST",
|
|
109
119
|
headers: { Authorization: `Bearer ${tok}`, "Content-Type": "application/json", "Connect-Protocol-Version": "1" },
|
|
110
120
|
body: "{}",
|
|
111
|
-
signal:
|
|
121
|
+
signal: until(15_000, signal),
|
|
112
122
|
})
|
|
113
123
|
return res.ok ? ((await res.json()) ?? undefined) : undefined
|
|
114
|
-
} catch {
|
|
124
|
+
} catch (err) {
|
|
125
|
+
if (cancelled(signal, err)) throw err
|
|
115
126
|
return undefined
|
|
116
127
|
}
|
|
117
128
|
}
|
|
118
129
|
|
|
119
130
|
const dollars = (n: number) => "$" + n.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })
|
|
120
131
|
|
|
121
|
-
async function periodUsage(tok: string, ids: string[]): Promise<UsageReport> {
|
|
132
|
+
async function periodUsage(tok: string, ids: string[], signal?: AbortSignal): Promise<UsageReport> {
|
|
122
133
|
const [res, hard] = await Promise.all([
|
|
123
134
|
fetch(API + "/aiserver.v1.DashboardService/GetCurrentPeriodUsage", {
|
|
124
135
|
method: "POST",
|
|
125
136
|
headers: { Authorization: `Bearer ${tok}`, "Content-Type": "application/json", "Connect-Protocol-Version": "1" },
|
|
126
137
|
body: "{}",
|
|
127
|
-
signal:
|
|
138
|
+
signal: until(15_000, signal),
|
|
128
139
|
}),
|
|
129
|
-
hardLimit(tok),
|
|
140
|
+
hardLimit(tok, signal),
|
|
130
141
|
])
|
|
131
142
|
if (!res.ok) return { error: statusText(res.status), windows: [] }
|
|
132
143
|
const data = (await res.json()) as Period
|
|
@@ -168,20 +179,27 @@ async function periodUsage(tok: string, ids: string[]): Promise<UsageReport> {
|
|
|
168
179
|
}
|
|
169
180
|
}
|
|
170
181
|
|
|
171
|
-
async function planOf(tok: string): Promise<string> {
|
|
172
|
-
const
|
|
173
|
-
|
|
182
|
+
async function planOf(tok: string, signal?: AbortSignal): Promise<string> {
|
|
183
|
+
const key = tokenKey(tok)
|
|
184
|
+
const had = recall(plans, key)
|
|
185
|
+
if (had) return had.plan
|
|
174
186
|
try {
|
|
175
|
-
const body = await unary(API, "aiserver.v1.DashboardService/GetPlanInfo", tok)
|
|
187
|
+
const body = await unary(API, "aiserver.v1.DashboardService/GetPlanInfo", tok, {}, 15_000, signal)
|
|
188
|
+
if (signal?.aborted) throw Object.assign(new Error("The operation was aborted"), { name: "AbortError" })
|
|
176
189
|
const plan = String(body?.planInfo?.planName ?? "").trim()
|
|
177
|
-
if (plan) plans
|
|
178
|
-
return plan
|
|
179
|
-
} catch {
|
|
180
|
-
|
|
190
|
+
if (plan) store(plans, key, { plan, expires: 0 }, PLAN_TTL)
|
|
191
|
+
return plan
|
|
192
|
+
} catch (err) {
|
|
193
|
+
if (cancelled(signal, err)) throw err
|
|
194
|
+
return ""
|
|
181
195
|
}
|
|
182
196
|
}
|
|
183
197
|
|
|
184
|
-
|
|
198
|
+
export function planCacheKeys(): string[] {
|
|
199
|
+
return [...plans.keys()]
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
async function botUsage(tok: string, signal?: AbortSignal): Promise<UsageWindow[]> {
|
|
185
203
|
try {
|
|
186
204
|
const subject = JSON.parse(Buffer.from(tok.split(".")[1] ?? "", "base64url").toString()).sub
|
|
187
205
|
if (typeof subject !== "string") return []
|
|
@@ -197,8 +215,9 @@ async function botUsage(tok: string): Promise<UsageWindow[]> {
|
|
|
197
215
|
},
|
|
198
216
|
body: "{}",
|
|
199
217
|
redirect: "error",
|
|
200
|
-
signal:
|
|
218
|
+
signal: until(5_000, signal),
|
|
201
219
|
})
|
|
220
|
+
if (signal?.aborted) throw Object.assign(new Error("The operation was aborted"), { name: "AbortError" })
|
|
202
221
|
if (!res.ok) return []
|
|
203
222
|
const data = (await res.json()) as {
|
|
204
223
|
includedLimitZero?: boolean
|
|
@@ -219,14 +238,19 @@ async function botUsage(tok: string): Promise<UsageWindow[]> {
|
|
|
219
238
|
...(Number.isFinite(reset) ? { resetsAt: new Date(reset).toISOString(), span: 604800 } : {}),
|
|
220
239
|
},
|
|
221
240
|
]
|
|
222
|
-
} catch {
|
|
241
|
+
} catch (err) {
|
|
242
|
+
if (cancelled(signal, err)) throw err
|
|
223
243
|
return []
|
|
224
244
|
}
|
|
225
245
|
}
|
|
226
246
|
|
|
227
247
|
/** Plan name plus the billing-period windows. GetPlanInfo is cached for about an hour per token. */
|
|
228
|
-
export async function fetchUsage(tok: string, modelIds: string[]): Promise<UsageReport> {
|
|
229
|
-
const [u, plan, bot] = await Promise.all([
|
|
248
|
+
export async function fetchUsage(tok: string, modelIds: string[], signal?: AbortSignal): Promise<UsageReport> {
|
|
249
|
+
const [u, plan, bot] = await Promise.all([
|
|
250
|
+
periodUsage(tok, modelIds, signal),
|
|
251
|
+
planOf(tok, signal),
|
|
252
|
+
botUsage(tok, signal),
|
|
253
|
+
])
|
|
230
254
|
const last = (w: UsageWindow) => w.name === "Total" || (w.name === "On-demand" && w.aside)
|
|
231
255
|
const windows = [...u.windows.filter((w) => !last(w)), ...bot, ...u.windows.filter(last)]
|
|
232
256
|
return { ...u, windows, ...(plan ? { plan } : {}) }
|