@caph42/pi-cursor-provider 0.5.3 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/README.md +34 -2
- package/package.json +1 -1
- package/src/config.ts +20 -6
- package/src/index.ts +78 -16
- package/src/limits.ts +199 -0
- package/src/models.ts +36 -3
- package/src/usage.ts +42 -56
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.6.0
|
|
4
|
+
|
|
5
|
+
- A merged (unified) subscription now offers only the models its included weekly allowance covers. `GetPlanInfo`'s `isMerged` decides whether the filter runs; the current period's `autoBucketModels` names the ids that allowance pays for, and an entry is offered when the id a Run at its default parameters resolves to is one of them. The filter is applied when the catalogue is read, not to the catalogue itself: the stored list stays complete, request resolution keeps every variant, and `{ "showAllModels": true }` in `cursor.json` offers everything again without a refresh and without the plan lookups. Cursor's own plans filter nothing, and a plan or period report that cannot be read filters nothing either. Checked against a live X unified account: 6 of 65 entries stayed (auto, Grok 4.7 at two context sizes, Grok 4.6, Grok 4.5, Composer 2.5); two of the excluded ones were sampled and both were refused with `429 … is not included in your weekly usage`, and the rest were not each exercised. A refresh makes one more request (`GetPlanInfo`), and a second one (`GetCurrentPeriodUsage`) only on a merged plan.
|
|
6
|
+
- A model's `maxTokens` is no longer a flat 32k guess: it comes from [models.dev](https://models.dev/api.json), matched by model id, taken as the limit most providers report with one vote per provider, and clamped to the entry's context window both when the limit is reported and when it is not. The index is stored in `cursor-limits.json` beside `cursor.json`: the first catalogue refresh after an install or update writes it (the file records the package version that wrote it, so a version change refreshes it once), every other session reads the file without a request, and concurrent refreshes share one download. A failure backs off ten minutes and leaves the stored index in use. A model it does not list — Cursor's own Composer, and `auto`, whose picker name is the API keyword `default` — keeps the fallback. Checked live: Grok 4.7 at 256k reports 256k (clamped from models.dev's 500k), Grok 4.7 at 500k reports 500k, Grok 4.6 and 4.5 report 256k, Composer 2.5 reports 32k, and a session refresh makes no models.dev request at all.
|
|
7
|
+
- `/cursor-provider-update` refetches the models.dev index and the Cursor catalogue on demand, and reports how many models and limits it ended up with. Nothing else in this package reads models.dev during a session.
|
|
8
|
+
- Image input stays declared for every model: Cursor's `supportsImages` under-reports it for the models sampled. The flag is `false` for Grok 4.7 and Composer 2.5, yet Grok 4.7, Grok 4.6, Grok 4.5, and Composer 2.5 each described a real 512×396 photograph in detail — a black-and-white panda meme with a photoshopped human face — rather than echoing colours, and a smaller synthetic test image had only been refused for being too small. The samples cover those entries, not the whole catalogue.
|
|
9
|
+
- `/cursor.usage` no longer adds a Grok Bot window, and the cursor.com dashboard request that read it is gone. The report covers the allowance a Pi turn can spend; another product's allowance is not spendable here.
|
|
10
|
+
|
|
3
11
|
## 0.5.3
|
|
4
12
|
|
|
5
13
|
- The Cursor catalogue refresh on `session_start` no longer blocks the session in the TUI. Pi paints before it binds extensions and awaits `session_start` handlers one at a time, so the network round trip left the built-in footer on screen for as long as it took — measured 1.9 s with a healthy connection, up to the 15 s timeout without one — and every extension registered after this one waited with it. The TUI path now starts the refresh in the background and publishes when it lands; a new session, a reload, or a shutdown cancels the request it replaced, so `refreshModels` cannot publish a catalogue for a session that ended, and no status or warning from it is applied. Headless modes still await it: an RPC host reads the catalogue right after startup and has no other signal that it changed.
|
package/README.md
CHANGED
|
@@ -63,6 +63,39 @@ Pi keeps a separate scoped model list (`/scoped-models`, `enabledModels`, or `--
|
|
|
63
63
|
|
|
64
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.
|
|
65
65
|
|
|
66
|
+
## Unified subscription
|
|
67
|
+
|
|
68
|
+
An account on Cursor's merged (unified) subscription — one weekly allowance billed through xAI's own commerce — is still served the whole picker, but the plan's included usage covers only part of it. This package offers the ids that allowance reports as covered and leaves the rest out of `/model`. Sampled against a live X unified account: a Run on two of the excluded models was refused with `429 … is not included in your weekly usage: Buy credits or switch to a Grok model`; the other excluded ones were not each exercised.
|
|
69
|
+
|
|
70
|
+
`GetPlanInfo`'s `isMerged` decides whether the filter runs at all; the current period's `autoBucketModels` names the ids the included usage pays for. An entry is offered when the id a Run at its default parameters resolves to is one of them, which is why an included effort can carry its family and an excluded default does not. Cursor's own plans filter nothing, and neither does a plan or period report that cannot be read.
|
|
71
|
+
|
|
72
|
+
Measured on that account: 6 of 65 entries stayed (auto, Grok 4.7 at two context sizes, Grok 4.6, Grok 4.5, Composer 2.5). Whether buying credits makes an excluded model run is not established here — the reports above name covered ids only, so this package cannot tell an account's credits apart from its plan, and does not try.
|
|
73
|
+
|
|
74
|
+
To offer every model Cursor lists, write `{ "showAllModels": true }` to `cursor.json` (see [Hide models](#hide-models)). The setting is applied when the catalogue is read, so it needs no refresh, and it skips the plan lookups altogether. The stored catalogue always stays complete: only what this provider offers is narrowed.
|
|
75
|
+
|
|
76
|
+
Plan facts are cached for an hour per credential. The catalogue keeps the covered ids with it, so a plan change reaches `/model` on the next refresh or `/reload`.
|
|
77
|
+
|
|
78
|
+
## Model metadata
|
|
79
|
+
|
|
80
|
+
Each model entry carries what Pi needs to route a turn correctly:
|
|
81
|
+
|
|
82
|
+
- `contextWindow` comes from Cursor's own picker: one entry per context size a model offers (`@256k`, `@500k`), else the model's token limit. Models the picker gives no size for fall back to 200k.
|
|
83
|
+
- Thinking levels come from the model's `effort` parameter, mapped onto Pi's `off`…`max` levels; a model with only a `thinking` switch becomes `off`/`high`.
|
|
84
|
+
- `maxTokens` comes from [models.dev](https://models.dev/api.json), matched by model id and taken as the limit most providers report, one vote per provider. It is never larger than the entry's context window, so a small-context entry also gets a small answer budget; a model models.dev does not list, such as Cursor's own Composer, keeps a 32k fallback. Pi clamps the value to the room left in the context before a request, so a generous limit only costs accuracy when it is too small.
|
|
85
|
+
- `input` is `text` and `image` for every model. Cursor's `supportsImages` flag under-reports image support for the models sampled: it says `false` for Grok 4.7 and Composer 2.5, yet both described a real 512×396 photograph in detail (a black-and-white panda meme with a photoshopped human face), as did Grok 4.6 and Grok 4.5. The samples cover those entries, not the whole catalogue, and declaring `image` also stops Pi from replacing images with a placeholder before they reach Cursor.
|
|
86
|
+
|
|
87
|
+
### The models.dev index
|
|
88
|
+
|
|
89
|
+
The document is 5.5 MB of JSON, about 600 KB gzipped, so a session does not read it. `/cursor-provider-update` and the first catalogue refresh after an install or update write `cursor-limits.json` beside `cursor.json` (`$PI_CODING_AGENT_DIR`, else `~/.pi/agent`); every other refresh reads that file only. The file records the package version that wrote it, so updating this package refreshes the index once and leaves it alone afterwards, and concurrent refreshes share one download. A failed read is retried no sooner than ten minutes later and leaves the stored index in use; if the file cannot be written, the index still serves this session and the next one reads again.
|
|
90
|
+
|
|
91
|
+
```text
|
|
92
|
+
/cursor-provider-update
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
The command refetches the index and then the Cursor catalogue, and reports how many models and limits it ended up with. It takes no arguments.
|
|
96
|
+
|
|
97
|
+
Cost stays zero for every model: a subscription bill is not a token price.
|
|
98
|
+
|
|
66
99
|
## Fast mode
|
|
67
100
|
|
|
68
101
|
Select a Cursor model, then use:
|
|
@@ -108,10 +141,9 @@ Windows follow magpie, in this order.
|
|
|
108
141
|
- Cursor Models
|
|
109
142
|
- Other Models
|
|
110
143
|
- On-demand, when the account has a dollar limit or an open on-demand spend
|
|
111
|
-
- Grok Bot, or Grok Bot (trial), when the dashboard reports that allowance
|
|
112
144
|
- Total
|
|
113
145
|
|
|
114
|
-
|
|
146
|
+
Total stays last. Only what a Pi turn can spend is reported: a plan's allowance for another product, such as Cursor's Grok bot, is left out even when the dashboard reports it.
|
|
115
147
|
|
|
116
148
|
```text
|
|
117
149
|
Plan: Pro
|
package/package.json
CHANGED
package/src/config.ts
CHANGED
|
@@ -13,6 +13,11 @@
|
|
|
13
13
|
* Hiding removes models from the live directory too: sessions already using a
|
|
14
14
|
* hidden model keep it, but resuming one may require selecting another model.
|
|
15
15
|
* A missing, unreadable or malformed file hides nothing.
|
|
16
|
+
*
|
|
17
|
+
* `showAllModels` switches off the plan filter that a merged (unified)
|
|
18
|
+
* subscription applies to the catalogue:
|
|
19
|
+
*
|
|
20
|
+
* { "showAllModels": true }
|
|
16
21
|
*/
|
|
17
22
|
import { readFileSync } from "node:fs"
|
|
18
23
|
import { homedir } from "node:os"
|
|
@@ -32,22 +37,31 @@ function patternsOf(value: unknown): string[] {
|
|
|
32
37
|
return value.flatMap((v) => (typeof v === "string" && v.trim() ? [v.trim()] : []))
|
|
33
38
|
}
|
|
34
39
|
|
|
35
|
-
/**
|
|
36
|
-
|
|
40
|
+
/** `cursor.json` as parsed JSON, or undefined when it is absent or not JSON. */
|
|
41
|
+
function jsonAt(path: string): unknown {
|
|
37
42
|
let text: string
|
|
38
43
|
try {
|
|
39
44
|
text = readFileSync(path, "utf8")
|
|
40
45
|
} catch {
|
|
41
|
-
return
|
|
46
|
+
return undefined
|
|
42
47
|
}
|
|
43
48
|
try {
|
|
44
|
-
|
|
45
|
-
return patternsOf((json as { hiddenModels?: unknown } | null)?.hiddenModels)
|
|
49
|
+
return JSON.parse(text)
|
|
46
50
|
} catch {
|
|
47
|
-
return
|
|
51
|
+
return undefined
|
|
48
52
|
}
|
|
49
53
|
}
|
|
50
54
|
|
|
55
|
+
/** The patterns in `cursor.json`. A file that is absent or not JSON hides nothing. */
|
|
56
|
+
export function hiddenPatterns(path: string = configPath()): string[] {
|
|
57
|
+
return patternsOf((jsonAt(path) as { hiddenModels?: unknown } | null)?.hiddenModels)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Whether `cursor.json` asks for every model Cursor lists, plan filter aside. */
|
|
61
|
+
export function showAllModels(path: string = configPath()): boolean {
|
|
62
|
+
return (jsonAt(path) as { showAllModels?: unknown } | null)?.showAllModels === true
|
|
63
|
+
}
|
|
64
|
+
|
|
51
65
|
/** A pattern as a regex: `*` any run, the rest literal (a `?` is a question mark, not a wildcard),
|
|
52
66
|
* the whole id, ignoring case. */
|
|
53
67
|
function globRe(pattern: string): RegExp {
|
package/src/index.ts
CHANGED
|
@@ -11,17 +11,19 @@ import type { Model, Provider } from "@earendil-works/pi-ai"
|
|
|
11
11
|
import type { ExtensionAPI, ExtensionContext } 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 { hiddenPatterns, visible } from "./config.ts"
|
|
14
|
+
import { hiddenPatterns, showAllModels, visible } from "./config.ts"
|
|
15
15
|
import { registerCursorDoctor } from "./doctor.ts"
|
|
16
|
-
import {
|
|
16
|
+
import { limitsForCatalogue, refreshLimits } from "./limits.ts"
|
|
17
|
+
import { piModelConfigs, planCovered, usable } from "./models.ts"
|
|
17
18
|
import { registerCursorFast } from "./fast.ts"
|
|
18
|
-
import { fetchUsage, formatUsage } from "./usage.ts"
|
|
19
|
+
import { fetchUsage, formatUsage, planCoverage } from "./usage.ts"
|
|
19
20
|
|
|
20
21
|
export { fetchUsage, formatUsage, onDemandOf } from "./usage.ts"
|
|
21
22
|
|
|
22
23
|
// One catalogue per credential: a refresh for one account must never serve
|
|
23
|
-
// its models to another.
|
|
24
|
-
|
|
24
|
+
// its models to another. The catalogue stays complete; `paid` is the subset a
|
|
25
|
+
// merged (unified) plan's included allowance covers, applied when reading.
|
|
26
|
+
const catalogs = new Map<string, { models: Model<"cursor-run">[]; paid?: Set<string> }>()
|
|
25
27
|
|
|
26
28
|
function credentialKey(token: string): string {
|
|
27
29
|
return createHash("sha256").update(token).digest("hex")
|
|
@@ -35,14 +37,24 @@ export default function (pi: ExtensionAPI) {
|
|
|
35
37
|
// Which credential produced `offered`; undefined when it came from Pi's cache
|
|
36
38
|
// alone, whose provenance this provider cannot see.
|
|
37
39
|
let offeredKey: string | undefined
|
|
40
|
+
// The ids the current catalogue may offer on a merged plan; undefined when the
|
|
41
|
+
// account is on Cursor's own plans, nothing is known, or `showAllModels` is
|
|
42
|
+
// set. Applied on every read, so the setting takes effect without a refresh.
|
|
43
|
+
let offeredPaid: Set<string> | undefined
|
|
44
|
+
const planFilter = (models: readonly Model<"cursor-run">[]): Model<"cursor-run">[] => {
|
|
45
|
+
const paid = offeredPaid
|
|
46
|
+
if (!paid || showAllModels()) return [...models]
|
|
47
|
+
const kept = models.filter((model) => paid.has(model.id))
|
|
48
|
+
return kept.length ? [...kept] : [...models]
|
|
49
|
+
}
|
|
38
50
|
const fast = registerCursorFast(pi)
|
|
39
51
|
const provider: Provider<"cursor-run"> = {
|
|
40
52
|
id: "cursor",
|
|
41
53
|
name: "Cursor",
|
|
42
54
|
baseUrl: AGENT,
|
|
43
|
-
getModels: () => visible(offered, hiddenPatterns()),
|
|
55
|
+
getModels: () => visible(planFilter(offered), hiddenPatterns()),
|
|
44
56
|
// Pi applies this after models.json overlays, including user-added models.
|
|
45
|
-
filterModels: (models) => visible(models, hiddenPatterns()),
|
|
57
|
+
filterModels: (models) => visible(planFilter(models), hiddenPatterns()),
|
|
46
58
|
auth: {
|
|
47
59
|
apiKey: {
|
|
48
60
|
name: "Cursor access token",
|
|
@@ -91,33 +103,67 @@ export default function (pi: ExtensionAPI) {
|
|
|
91
103
|
// network, so an offline reload does not look like a signed-out account.
|
|
92
104
|
const kept = token ? catalogs.get(credentialKey(token)) : undefined
|
|
93
105
|
if (!ctx.allowNetwork || !auth) {
|
|
94
|
-
if (kept?.length) {
|
|
95
|
-
await ctx.publish({
|
|
106
|
+
if (kept?.models.length) {
|
|
107
|
+
await ctx.publish({
|
|
108
|
+
update: () => {
|
|
109
|
+
offered = kept.models
|
|
110
|
+
offeredPaid = kept.paid
|
|
111
|
+
offeredKey = token ? credentialKey(token) : undefined
|
|
112
|
+
fast.catalogueChanged()
|
|
113
|
+
},
|
|
114
|
+
})
|
|
96
115
|
}
|
|
97
116
|
return
|
|
98
117
|
}
|
|
99
118
|
const key = credentialKey(auth.token)
|
|
100
119
|
try {
|
|
101
|
-
|
|
120
|
+
// A merged (unified) subscription covers only part of what Cursor lists:
|
|
121
|
+
// ids outside the reported included allowance are not offered, since
|
|
122
|
+
// sampled Runs on them were refused. `showAllModels` skips the lookups
|
|
123
|
+
// entirely, and an account on Cursor's own plans has nothing to look up.
|
|
124
|
+
const override = showAllModels()
|
|
125
|
+
const [raw, coverage, limits] = await Promise.all([
|
|
126
|
+
usable(auth.token, ctx.force === true, ctx.signal),
|
|
127
|
+
override ? Promise.resolve(undefined) : planCoverage(auth.token, ctx.signal),
|
|
128
|
+
// model metadata, never a reason to fail the catalogue
|
|
129
|
+
limitsForCatalogue(ctx.signal),
|
|
130
|
+
])
|
|
131
|
+
// A merged plan keeps its coverage when a period report goes unread, so
|
|
132
|
+
// the picker does not reopen with models the plan does not pay for.
|
|
133
|
+
const known = catalogs.get(key)?.paid
|
|
134
|
+
const covered = coverage?.merged && coverage.ids ? planCovered(raw, coverage.ids) : []
|
|
135
|
+
const paid: Set<string> | undefined = covered.length
|
|
136
|
+
? new Set(covered.map((entry: { id: string }) => entry.id))
|
|
137
|
+
: coverage?.merged
|
|
138
|
+
? known
|
|
139
|
+
: undefined
|
|
140
|
+
const next = piModelConfigs(raw, limits).map((model: Model<"cursor-run">) => ({
|
|
102
141
|
...model,
|
|
103
142
|
provider: "cursor",
|
|
104
143
|
baseUrl: AGENT,
|
|
105
144
|
})) as Model<"cursor-run">[]
|
|
106
145
|
if (ctx.signal.aborted) return
|
|
107
|
-
catalogs.set(key, next)
|
|
146
|
+
catalogs.set(key, { models: next, paid })
|
|
108
147
|
await ctx.publish({
|
|
109
148
|
persist: { models: next, checkedAt: Date.now() },
|
|
110
|
-
update: () => { offered = next; offeredKey = key; fast.catalogueChanged() },
|
|
149
|
+
update: () => { offered = next; offeredPaid = paid; offeredKey = key; fast.catalogueChanged() },
|
|
111
150
|
})
|
|
112
151
|
} catch (error) {
|
|
113
152
|
// Never keep another credential's catalogue after a failed refresh: fall
|
|
114
153
|
// back to what this one discovered, even if that is nothing.
|
|
115
154
|
const unknownSource = offeredKey === undefined
|
|
116
|
-
const previous = catalogs.get(key)
|
|
117
|
-
await ctx.publish({
|
|
155
|
+
const previous = catalogs.get(key)
|
|
156
|
+
await ctx.publish({
|
|
157
|
+
update: () => {
|
|
158
|
+
offered = previous?.models ?? []
|
|
159
|
+
offeredPaid = previous?.paid
|
|
160
|
+
offeredKey = key
|
|
161
|
+
fast.catalogueChanged()
|
|
162
|
+
},
|
|
163
|
+
})
|
|
118
164
|
// Surface a first-load failure instead of reporting an empty provider as
|
|
119
165
|
// a successful refresh.
|
|
120
|
-
if (!previous.length && unknownSource) throw error
|
|
166
|
+
if (!(previous?.models.length ?? 0) && unknownSource) throw error
|
|
121
167
|
}
|
|
122
168
|
},
|
|
123
169
|
stream: fast.stream,
|
|
@@ -194,6 +240,22 @@ export default function (pi: ExtensionAPI) {
|
|
|
194
240
|
|
|
195
241
|
registerCursorDoctor(pi)
|
|
196
242
|
|
|
243
|
+
pi.registerCommand("cursor-provider-update", {
|
|
244
|
+
description: "Refetch the models.dev output limits and the Cursor model catalogue",
|
|
245
|
+
handler: async (args, ctx) => {
|
|
246
|
+
const extra = args.trim() ? " This command does not take arguments." : ""
|
|
247
|
+
const signal = ctx.signal ?? new AbortController().signal
|
|
248
|
+
const limits = await refreshLimits(signal, { force: true })
|
|
249
|
+
const kept = limits ? `${limits.size} model limits` : "no model limits (models.dev could not be read)"
|
|
250
|
+
try {
|
|
251
|
+
await refreshCatalogue(ctx, signal)
|
|
252
|
+
ctx.ui.notify(`Cursor model catalogue: ${offered.length} models, ${kept}.${extra}`, limits ? "info" : "warning")
|
|
253
|
+
} catch (error) {
|
|
254
|
+
ctx.ui.notify(`Cursor model catalogue: ${error instanceof Error ? error.message : String(error)} (${kept}).${extra}`, "warning")
|
|
255
|
+
}
|
|
256
|
+
},
|
|
257
|
+
})
|
|
258
|
+
|
|
197
259
|
pi.registerCommand("cursor.usage", {
|
|
198
260
|
description: "Show Cursor plan usage for this billing period",
|
|
199
261
|
handler: async (args, ctx) => {
|
|
@@ -204,7 +266,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
204
266
|
ctx.ui.notify(`Cursor is not signed in (${version}). Run /login cursor or set CURSOR_ACCESS_TOKEN.${extra}`, "warning")
|
|
205
267
|
return
|
|
206
268
|
}
|
|
207
|
-
let ids = (catalogs.get(credentialKey(auth.token)) ?? offered).map((m) => m.id)
|
|
269
|
+
let ids = (catalogs.get(credentialKey(auth.token))?.models ?? offered).map((m) => m.id)
|
|
208
270
|
if (!ids.length) {
|
|
209
271
|
try {
|
|
210
272
|
ids = (await usable(auth.token, false, ctx.signal)).map((m: { id: string }) => m.id)
|
package/src/limits.ts
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Output-token limits from models.dev, kept on disk.
|
|
3
|
+
*
|
|
4
|
+
* Cursor's picker says how much context a model takes but not how many tokens it
|
|
5
|
+
* may answer with, so a Pi model config would have to guess. models.dev
|
|
6
|
+
* (https://models.dev/api.json) publishes both limits for the same model ids
|
|
7
|
+
* across many providers; this module indexes them by model id and answers with
|
|
8
|
+
* the limit most providers report.
|
|
9
|
+
*
|
|
10
|
+
* The document is about 6 MB (600 KB gzipped), so it is not read during a
|
|
11
|
+
* session: `cursor-limits.json` beside `cursor.json` holds the index, and it is
|
|
12
|
+
* written when this package is installed or updated (the file records the
|
|
13
|
+
* version that wrote it, so a version change refreshes it once) and when
|
|
14
|
+
* `/cursor-provider-update` runs. A session start only reads the file.
|
|
15
|
+
* Nothing here is required: a file that is absent or unreadable leaves an empty
|
|
16
|
+
* index and the catalogue keeps its own fallback.
|
|
17
|
+
*/
|
|
18
|
+
import { readFileSync, writeFileSync } from "node:fs"
|
|
19
|
+
import { homedir } from "node:os"
|
|
20
|
+
import { dirname, join } from "node:path"
|
|
21
|
+
import { fileURLToPath } from "node:url"
|
|
22
|
+
|
|
23
|
+
export const LIMITS_FILE = "cursor-limits.json"
|
|
24
|
+
|
|
25
|
+
const SOURCE = "https://models.dev/api.json"
|
|
26
|
+
const TIMEOUT = 15_000
|
|
27
|
+
const RETRY = 10 * 60 * 1000
|
|
28
|
+
|
|
29
|
+
/** Names Cursor's picker uses for its router rather than for a model. */
|
|
30
|
+
export const ALIAS_IDS = new Set(["auto", "default"])
|
|
31
|
+
|
|
32
|
+
/** A model id as both sides spell it: last path segment, lowercase, `.`, `_`, and spaces as `-`. */
|
|
33
|
+
export function limitKey(raw: unknown): string {
|
|
34
|
+
return String(raw ?? "")
|
|
35
|
+
.trim()
|
|
36
|
+
.toLowerCase()
|
|
37
|
+
.split("/")
|
|
38
|
+
.pop()!
|
|
39
|
+
.replace(/@.*$/, "")
|
|
40
|
+
.replace(/[._\s]+/g, "-")
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
type Model = { id?: string; limit?: { output?: number } }
|
|
44
|
+
|
|
45
|
+
/** Index a models.dev document: model id to the output limit most providers report, ties to the larger. */
|
|
46
|
+
export function limitIndexOf(json: unknown): Map<string, number> {
|
|
47
|
+
const votes = new Map<string, Map<number, number>>()
|
|
48
|
+
for (const provider of Object.values((json ?? {}) as Record<string, { models?: Record<string, Model> } | null>)) {
|
|
49
|
+
// one vote per provider: a provider that lists the same model under several
|
|
50
|
+
// ids (aliases) does not outvote the others
|
|
51
|
+
const own = new Map<string, number>()
|
|
52
|
+
for (const [id, model] of Object.entries(provider?.models ?? {})) {
|
|
53
|
+
const output = Number(model?.limit?.output)
|
|
54
|
+
if (!Number.isFinite(output) || output <= 0) continue
|
|
55
|
+
const key = limitKey(model?.id ?? id)
|
|
56
|
+
if (!key) continue
|
|
57
|
+
own.set(key, Math.max(own.get(key) ?? 0, output))
|
|
58
|
+
}
|
|
59
|
+
for (const [key, output] of own) {
|
|
60
|
+
const bucket = votes.get(key) ?? new Map<number, number>()
|
|
61
|
+
bucket.set(output, (bucket.get(output) ?? 0) + 1)
|
|
62
|
+
votes.set(key, bucket)
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
const index = new Map<string, number>()
|
|
66
|
+
for (const [key, bucket] of votes) {
|
|
67
|
+
let tokens = 0
|
|
68
|
+
let count = -1
|
|
69
|
+
for (const [value, seen] of bucket) {
|
|
70
|
+
if (seen > count || (seen === count && value > tokens)) [tokens, count] = [value, seen]
|
|
71
|
+
}
|
|
72
|
+
index.set(key, tokens)
|
|
73
|
+
}
|
|
74
|
+
return index
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** `cursor-limits.json` beside the rest of Pi's config. */
|
|
78
|
+
export function limitsPath(env: NodeJS.ProcessEnv = process.env, file = LIMITS_FILE): string {
|
|
79
|
+
const dir = (env.PI_CODING_AGENT_DIR ?? "").trim()
|
|
80
|
+
return join(dir || join(homedir(), ".pi", "agent"), file)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
let version: string | undefined
|
|
84
|
+
|
|
85
|
+
/** The version of this package, which decides whether a stored index is current. */
|
|
86
|
+
export function packageVersion(): string {
|
|
87
|
+
if (version !== undefined) return version
|
|
88
|
+
try {
|
|
89
|
+
const json = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), "..", "package.json"), "utf8")) as { version?: unknown }
|
|
90
|
+
version = typeof json.version === "string" ? json.version : ""
|
|
91
|
+
} catch {
|
|
92
|
+
version = ""
|
|
93
|
+
}
|
|
94
|
+
return version
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export type StoredLimits = { index: Map<string, number>; version?: string }
|
|
98
|
+
|
|
99
|
+
/** The stored index. A file that is absent, unreadable, or not ours reads as empty. */
|
|
100
|
+
export function readLimits(path: string = limitsPath()): StoredLimits {
|
|
101
|
+
let json: unknown
|
|
102
|
+
try {
|
|
103
|
+
json = JSON.parse(readFileSync(path, "utf8"))
|
|
104
|
+
} catch {
|
|
105
|
+
return { index: new Map() }
|
|
106
|
+
}
|
|
107
|
+
const { version: wrote, limits } = (json ?? {}) as { version?: unknown; limits?: Record<string, unknown> }
|
|
108
|
+
const index = new Map<string, number>()
|
|
109
|
+
for (const [key, value] of Object.entries(limits ?? {})) {
|
|
110
|
+
const tokens = Number(value)
|
|
111
|
+
if (key && Number.isFinite(tokens) && tokens > 0) index.set(key, tokens)
|
|
112
|
+
}
|
|
113
|
+
return { index, ...(typeof wrote === "string" ? { version: wrote } : {}) }
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Write the index, stamped with the version that wrote it. A failed write is not an error worth raising. */
|
|
117
|
+
export function writeLimits(index: Map<string, number>, path: string = limitsPath(), wrote: string = packageVersion()): boolean {
|
|
118
|
+
try {
|
|
119
|
+
writeFileSync(path, JSON.stringify({ version: wrote, limits: Object.fromEntries(index) }) + "\n")
|
|
120
|
+
return true
|
|
121
|
+
} catch {
|
|
122
|
+
return false
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
let retryAfter = 0
|
|
127
|
+
let inflight: Promise<Map<string, number> | undefined> | undefined
|
|
128
|
+
|
|
129
|
+
function abortError(): Error {
|
|
130
|
+
return Object.assign(new Error("The operation was aborted"), { name: "AbortError" })
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Read the document and index it. Undefined when the read fails; it never throws for that. */
|
|
134
|
+
async function download(): Promise<Map<string, number> | undefined> {
|
|
135
|
+
try {
|
|
136
|
+
const res = await fetch(SOURCE, { headers: { Accept: "application/json" }, signal: AbortSignal.timeout(TIMEOUT) })
|
|
137
|
+
if (!res.ok) throw new Error(`models.dev answered ${res.status}`)
|
|
138
|
+
const index = limitIndexOf(await res.json())
|
|
139
|
+
if (!index.size) throw new Error("models.dev listed no limits")
|
|
140
|
+
retryAfter = 0
|
|
141
|
+
return index
|
|
142
|
+
} catch {
|
|
143
|
+
retryAfter = Date.now() + RETRY
|
|
144
|
+
return undefined
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** One download at a time: two callers asking at once share the document. */
|
|
149
|
+
function shared(): Promise<Map<string, number> | undefined> {
|
|
150
|
+
if (!inflight) inflight = download().finally(() => { inflight = undefined })
|
|
151
|
+
return inflight
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Settle with the shared download, or reject as soon as this caller is cancelled. */
|
|
155
|
+
function untilAbort<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {
|
|
156
|
+
if (!signal) return promise
|
|
157
|
+
if (signal.aborted) return Promise.reject(abortError())
|
|
158
|
+
return new Promise<T>((resolve, reject) => {
|
|
159
|
+
const stop = () => reject(abortError())
|
|
160
|
+
signal.addEventListener("abort", stop, { once: true })
|
|
161
|
+
promise.then(
|
|
162
|
+
(value) => {
|
|
163
|
+
signal.removeEventListener("abort", stop)
|
|
164
|
+
resolve(value)
|
|
165
|
+
},
|
|
166
|
+
(error) => {
|
|
167
|
+
signal.removeEventListener("abort", stop)
|
|
168
|
+
reject(error)
|
|
169
|
+
},
|
|
170
|
+
)
|
|
171
|
+
})
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Refetch the document and store it. `force` is a person asking, which ignores
|
|
176
|
+
* the backoff a failure sets. Returns the new index, or undefined on failure.
|
|
177
|
+
*/
|
|
178
|
+
export async function refreshLimits(signal?: AbortSignal, options: { force?: boolean; path?: string } = {}): Promise<Map<string, number> | undefined> {
|
|
179
|
+
if (!options.force && Date.now() < retryAfter) return undefined
|
|
180
|
+
const index = await untilAbort(shared(), signal)
|
|
181
|
+
if (index && writeLimits(index, options.path ?? limitsPath())) return index
|
|
182
|
+
return index
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* The index to build a catalogue with: the stored one while it matches this
|
|
187
|
+
* package's version, else a fresh read that is stored for the next session.
|
|
188
|
+
*/
|
|
189
|
+
export async function limitsForCatalogue(signal?: AbortSignal, path: string = limitsPath()): Promise<Map<string, number>> {
|
|
190
|
+
const stored = readLimits(path)
|
|
191
|
+
if (stored.index.size && stored.version === packageVersion()) return stored.index
|
|
192
|
+
const fresh = await refreshLimits(signal, { path })
|
|
193
|
+
return fresh ?? stored.index
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
export function clearLimitsRetry(): void {
|
|
197
|
+
retryAfter = 0
|
|
198
|
+
inflight = undefined
|
|
199
|
+
}
|
package/src/models.ts
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
// @ts-nocheck
|
|
9
9
|
import { API, DEFAULT_CONTEXT, MODELS_KEEP, unary } from "./client.ts"
|
|
10
10
|
import { recall, store, tokenKey } from "./cache.ts"
|
|
11
|
+
import { ALIAS_IDS, limitKey } from "./limits.ts"
|
|
11
12
|
|
|
12
13
|
const LEVEL_RANK = ["none", "minimal", "low", "medium", "high", "xhigh", "max"]
|
|
13
14
|
const EFFORT_PARAMS = ["effort", "reasoning_effort", "reasoning"]
|
|
@@ -244,6 +245,18 @@ const lists = new Map()
|
|
|
244
245
|
export function modelCacheKeys() {
|
|
245
246
|
return [...lists.keys()]
|
|
246
247
|
}
|
|
248
|
+
|
|
249
|
+
// planCovered is the entries a merged (unified) plan's included allowance pays
|
|
250
|
+
// for: the id a Run at the entry's default parameters resolves to (the default
|
|
251
|
+
// effort, fast off) is one the period report counts. The report says nothing
|
|
252
|
+
// about what an id outside it would cost; sampled Runs on such ids were refused
|
|
253
|
+
// with 429 "not included in your weekly usage". Entries left out stay in
|
|
254
|
+
// usable(), so an id passed explicitly still resolves to its variants; only
|
|
255
|
+
// what the picker offers is narrowed.
|
|
256
|
+
export function planCovered(raw, ids) {
|
|
257
|
+
return raw.filter((entry) => ids.has(pick(entry, "off", false).id))
|
|
258
|
+
}
|
|
259
|
+
|
|
247
260
|
export async function usable(tok, force = false, signal?: AbortSignal) {
|
|
248
261
|
const h = tokenKey(tok)
|
|
249
262
|
const had = recall(lists, h)
|
|
@@ -342,8 +355,28 @@ export function supportsFast(raw, id, effort = "off") {
|
|
|
342
355
|
})
|
|
343
356
|
}
|
|
344
357
|
|
|
345
|
-
|
|
346
|
-
|
|
358
|
+
// outputOf is how many tokens a model may answer with, as models.dev reports it
|
|
359
|
+
// for the picker's name or the model's server name, never more than the context
|
|
360
|
+
// window the catalogue has for the entry.
|
|
361
|
+
const OUTPUT_FALLBACK = 32_000
|
|
362
|
+
function outputOf(m, limits) {
|
|
363
|
+
// Never more than the entry can take in: a small context makes a small answer
|
|
364
|
+
// budget, whether the limit is reported or guessed.
|
|
365
|
+
const room = m.context || DEFAULT_CONTEXT
|
|
366
|
+
if (!limits) return Math.min(OUTPUT_FALLBACK, room)
|
|
367
|
+
// `default` (Cursor's auto) and `auto` name the router, not a model, and would
|
|
368
|
+
// match an unrelated models.dev id.
|
|
369
|
+
const keys = [m.run, m.model?.serverModelName, m.id].map(limitKey).filter((key) => key && !ALIAS_IDS.has(key))
|
|
370
|
+
const reported = keys.map((key) => limits.get(key)).find((value) => value !== undefined)
|
|
371
|
+
return Math.min(reported ?? OUTPUT_FALLBACK, room)
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* Pi chat-model configs. Cost stays zero: a subscription bill is not a token
|
|
376
|
+
* price. `limits` is models.dev's output limits (see limits.ts); without it the
|
|
377
|
+
* catalogue falls back to 32k.
|
|
378
|
+
*/
|
|
379
|
+
export function piModelConfigs(raw: any, limits?: Map<string, number>) {
|
|
347
380
|
return raw.map((m) => {
|
|
348
381
|
const thinking = thinkingLevelMap(m.levels)
|
|
349
382
|
return {
|
|
@@ -355,7 +388,7 @@ export function piModelConfigs(raw) {
|
|
|
355
388
|
input: ["text", "image"],
|
|
356
389
|
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
357
390
|
contextWindow: m.context || DEFAULT_CONTEXT,
|
|
358
|
-
maxTokens:
|
|
391
|
+
maxTokens: outputOf(m, limits),
|
|
359
392
|
cursorFastLevels: PI_LEVELS.filter(([level]) => supportsFast(raw, m.id, level)).map(([level]) => level),
|
|
360
393
|
}
|
|
361
394
|
})
|
package/src/usage.ts
CHANGED
|
@@ -3,18 +3,18 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Ported from magpie's Cursor provider (MIT):
|
|
5
5
|
* https://github.com/magpie-community/plugins/tree/main/packages/cursor
|
|
6
|
-
* Plan lookup uses the shared Connect client.
|
|
7
|
-
*
|
|
8
|
-
*
|
|
6
|
+
* Plan lookup uses the shared Connect client. The period and the hard limit
|
|
7
|
+
* stay on their own fetches so a refused dashboard call is a report, not a
|
|
8
|
+
* thrown request. Only the subscription this package spends is reported:
|
|
9
|
+
* a plan's allowance for another product (Cursor's Grok bot) is not usage a
|
|
10
|
+
* Pi turn can draw on, so it is left out.
|
|
9
11
|
*/
|
|
10
12
|
import { STATUS_CODES } from "node:http"
|
|
11
13
|
import { API, unary } from "./client.ts"
|
|
12
14
|
import { tokenKey, recall, store } from "./cache.ts"
|
|
13
15
|
|
|
14
|
-
export const WEBSITE = "https://cursor.com"
|
|
15
|
-
|
|
16
16
|
const PLAN_TTL = 3600_000
|
|
17
|
-
const plans = new Map<string, { plan: string; expires: number }>()
|
|
17
|
+
const plans = new Map<string, { plan: string; merged: boolean; expires: number }>()
|
|
18
18
|
|
|
19
19
|
function until(ms: number, signal?: AbortSignal): AbortSignal {
|
|
20
20
|
const deadline = AbortSignal.timeout(ms)
|
|
@@ -179,81 +179,67 @@ async function periodUsage(tok: string, ids: string[], signal?: AbortSignal): Pr
|
|
|
179
179
|
}
|
|
180
180
|
}
|
|
181
181
|
|
|
182
|
-
async function
|
|
182
|
+
async function planFacts(tok: string, signal?: AbortSignal): Promise<{ plan: string; merged: boolean }> {
|
|
183
183
|
const key = tokenKey(tok)
|
|
184
184
|
const had = recall(plans, key)
|
|
185
|
-
if (had) return had.plan
|
|
185
|
+
if (had) return { plan: had.plan, merged: had.merged }
|
|
186
186
|
try {
|
|
187
187
|
const body = await unary(API, "aiserver.v1.DashboardService/GetPlanInfo", tok, {}, 15_000, signal)
|
|
188
188
|
if (signal?.aborted) throw Object.assign(new Error("The operation was aborted"), { name: "AbortError" })
|
|
189
189
|
const plan = String(body?.planInfo?.planName ?? "").trim()
|
|
190
|
-
|
|
191
|
-
|
|
190
|
+
// A merged account bills through Cursor's unified subscription: one weekly
|
|
191
|
+
// allowance, whose report names the models it covers. `nextUpgrade` names a
|
|
192
|
+
// plan the account could move to, not the one it has, so it is not a signal.
|
|
193
|
+
const merged = body?.isMerged === true
|
|
194
|
+
if (plan) store(plans, key, { plan, merged, expires: 0 }, PLAN_TTL)
|
|
195
|
+
return { plan, merged }
|
|
192
196
|
} catch (err) {
|
|
193
197
|
if (cancelled(signal, err)) throw err
|
|
194
|
-
return ""
|
|
198
|
+
return { plan: "", merged: false }
|
|
195
199
|
}
|
|
196
200
|
}
|
|
197
201
|
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
202
|
+
/**
|
|
203
|
+
* What a plan's included allowance covers. `merged: false` is a Cursor plan and
|
|
204
|
+
* nothing to filter. `merged: true` with `ids` is the merged (unified) billing
|
|
205
|
+
* whose period report names the models its included usage pays for; merged with
|
|
206
|
+
* no `ids` is that plan with a report that could not be read. The period report
|
|
207
|
+
* says nothing about the rest of the picker; sampled Runs on ids outside it were
|
|
208
|
+
* refused with 429 "not included in your weekly usage".
|
|
209
|
+
*/
|
|
210
|
+
export type PlanCoverage = { merged: boolean; ids?: Set<string> }
|
|
201
211
|
|
|
202
|
-
async function
|
|
212
|
+
export async function planCoverage(tok: string, signal?: AbortSignal): Promise<PlanCoverage> {
|
|
213
|
+
const { merged } = await planFacts(tok, signal)
|
|
214
|
+
if (!merged) return { merged: false }
|
|
203
215
|
try {
|
|
204
|
-
const
|
|
205
|
-
if (typeof subject !== "string") return []
|
|
206
|
-
const user = subject.split("|").filter(Boolean).at(-1)
|
|
207
|
-
if (!user || !/^[a-zA-Z0-9._-]+$/.test(user)) return []
|
|
208
|
-
const res = await fetch(WEBSITE + "/api/dashboard/get-sand-usage-status", {
|
|
216
|
+
const res = await fetch(API + "/aiserver.v1.DashboardService/GetCurrentPeriodUsage", {
|
|
209
217
|
method: "POST",
|
|
210
|
-
headers: {
|
|
211
|
-
"Content-Type": "application/json",
|
|
212
|
-
Accept: "application/json",
|
|
213
|
-
Origin: WEBSITE,
|
|
214
|
-
Cookie: "WorkosCursorSessionToken=" + encodeURIComponent(user + "::" + tok),
|
|
215
|
-
},
|
|
218
|
+
headers: { Authorization: `Bearer ${tok}`, "Content-Type": "application/json", "Connect-Protocol-Version": "1" },
|
|
216
219
|
body: "{}",
|
|
217
|
-
|
|
218
|
-
signal: until(5_000, signal),
|
|
220
|
+
signal: until(15_000, signal),
|
|
219
221
|
})
|
|
220
222
|
if (signal?.aborted) throw Object.assign(new Error("The operation was aborted"), { name: "AbortError" })
|
|
221
|
-
if (!res.ok) return
|
|
222
|
-
const data = (await res.json()) as {
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
sandTrialExpiresAt?: string
|
|
226
|
-
usagePercent?: number
|
|
227
|
-
nextResetTimestampUtc?: string
|
|
228
|
-
}
|
|
229
|
-
const paid = typeof data?.includedLimitZero === "boolean" ? !data.includedLimitZero : data?.hasNonZeroIncludedLimit === true
|
|
230
|
-
const trial = !paid && typeof data?.sandTrialExpiresAt === "string" && Date.parse(data.sandTrialExpiresAt) > Date.now()
|
|
231
|
-
if ((!paid && !trial) || typeof data?.usagePercent !== "number" || !Number.isFinite(data.usagePercent)) return []
|
|
232
|
-
const reset = paid && typeof data.nextResetTimestampUtc === "string" ? Date.parse(data.nextResetTimestampUtc) : NaN
|
|
233
|
-
return [
|
|
234
|
-
{
|
|
235
|
-
name: trial ? "Grok Bot (trial)" : "Grok Bot",
|
|
236
|
-
used: Math.max(0, Math.min(100, data.usagePercent)),
|
|
237
|
-
aside: true,
|
|
238
|
-
...(Number.isFinite(reset) ? { resetsAt: new Date(reset).toISOString(), span: 604800 } : {}),
|
|
239
|
-
},
|
|
240
|
-
]
|
|
223
|
+
if (!res.ok) return { merged: true }
|
|
224
|
+
const data = (await res.json()) as { autoBucketModels?: unknown }
|
|
225
|
+
const ids = Array.isArray(data?.autoBucketModels) ? data.autoBucketModels.filter((id): id is string => typeof id === "string" && id !== "") : []
|
|
226
|
+
return ids.length ? { merged: true, ids: new Set(ids) } : { merged: true }
|
|
241
227
|
} catch (err) {
|
|
242
228
|
if (cancelled(signal, err)) throw err
|
|
243
|
-
return
|
|
229
|
+
return { merged: true }
|
|
244
230
|
}
|
|
245
231
|
}
|
|
246
232
|
|
|
233
|
+
export function planCacheKeys(): string[] {
|
|
234
|
+
return [...plans.keys()]
|
|
235
|
+
}
|
|
236
|
+
|
|
247
237
|
/** Plan name plus the billing-period windows. GetPlanInfo is cached for about an hour per token. */
|
|
248
238
|
export async function fetchUsage(tok: string, modelIds: string[], signal?: AbortSignal): Promise<UsageReport> {
|
|
249
|
-
const [u,
|
|
250
|
-
periodUsage(tok, modelIds, signal),
|
|
251
|
-
planOf(tok, signal),
|
|
252
|
-
botUsage(tok, signal),
|
|
253
|
-
])
|
|
239
|
+
const [u, facts] = await Promise.all([periodUsage(tok, modelIds, signal), planFacts(tok, signal)])
|
|
254
240
|
const last = (w: UsageWindow) => w.name === "Total" || (w.name === "On-demand" && w.aside)
|
|
255
|
-
const windows = [...u.windows.filter((w) => !last(w)), ...
|
|
256
|
-
return { ...u, windows, ...(plan ? { plan } : {}) }
|
|
241
|
+
const windows = [...u.windows.filter((w) => !last(w)), ...u.windows.filter(last)]
|
|
242
|
+
return { ...u, windows, ...(facts.plan ? { plan: facts.plan } : {}) }
|
|
257
243
|
}
|
|
258
244
|
|
|
259
245
|
function percent(n: number) {
|