@caph42/pi-cursor-provider 0.5.3 → 0.7.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 +16 -0
- package/README.md +38 -5
- package/package.json +1 -1
- package/src/config.ts +20 -6
- package/src/fast-footer.ts +2 -2
- package/src/fast.ts +9 -6
- package/src/index.ts +78 -16
- package/src/limits.ts +199 -0
- package/src/models.ts +36 -3
- package/src/native-session.ts +5 -2
- package/src/pi-stream.ts +60 -1
- package/src/protocol.ts +12 -2
- package/src/usage.ts +42 -56
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## Unreleased
|
|
4
|
+
|
|
5
|
+
## 0.7.0
|
|
6
|
+
|
|
7
|
+
- `/cursor.fast` with no argument toggles the current model between off and on. `/cursor.fast on`, `/cursor.fast off`, and `/cursor.fast status` are unchanged.
|
|
8
|
+
- Fast stays off the footer while it is off or unavailable. Enabling it publishes `Fast`; an enabled preference that the current thinking level no longer supports publishes `Fast unavailable`. Non-Cursor models still publish nothing.
|
|
9
|
+
- Each assistant stream event carries `cursorOutputTiming`, copied when the event is queued. The shared partial stays the one live message, so a consumer that reads the queue later still sees the reading from that moment: estimated output tokens, elapsed time, and a receive-side tokens-per-second once a measured interval exists. Bytes that open a burst, including the first delta after a tool call, are not in the rate. Cursor's own output count arrives with the stop and replaces the estimate only when it is measured. Replayed native events are marked and do not move the clock.
|
|
10
|
+
|
|
11
|
+
## 0.6.0
|
|
12
|
+
|
|
13
|
+
- 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.
|
|
14
|
+
- 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.
|
|
15
|
+
- `/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.
|
|
16
|
+
- 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.
|
|
17
|
+
- `/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.
|
|
18
|
+
|
|
3
19
|
## 0.5.3
|
|
4
20
|
|
|
5
21
|
- 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,21 +63,55 @@ 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:
|
|
69
102
|
|
|
70
103
|
```text
|
|
104
|
+
/cursor.fast
|
|
71
105
|
/cursor.fast on
|
|
72
|
-
/cursor.fast status
|
|
73
106
|
/cursor.fast off
|
|
107
|
+
/cursor.fast status
|
|
74
108
|
```
|
|
75
109
|
|
|
76
|
-
With no argument, `/cursor.fast`
|
|
110
|
+
With no argument, `/cursor.fast` toggles the current model: off becomes on, and on becomes off. `/cursor.fast on` and `/cursor.fast off` set it explicitly. In the TUI, type `/cursor.fast ` and press Tab to choose `on` or `off`; a unique prefix such as `of` completes to `off` without executing the command. `/cursor.fast status` only reports the current state. In the TUI, enabled fast shows `Fast` on the second footer row beside the model/thinking information. Off shows nothing there. Other extension statuses retain their own row. The same text is also published through `ctx.ui.setStatus`, so a footer that renders extension statuses — Pi's own footer, or pi-ccline's — still shows it when another extension owns the footer slot; Cursor's footer filters that key out, so it never appears twice. RPC clients continue receiving the `cursor-fast` status text. Enabling fast preserves the selected model ID, context size, and thinking level. It requires an account-available fast variant at the same context and effective thinking parameters; unsupported combinations are rejected.
|
|
77
111
|
|
|
78
112
|
The setting defaults to off and belongs to the current model in the current session. Other models keep their own settings. Reloading or resuming that session restores the setting from its current branch; a new session starts with fast off. Changes apply to the next request and require the current response to finish first.
|
|
79
113
|
|
|
80
|
-
If fast is enabled and a later thinking change or catalogue update removes support, the footer shows `
|
|
114
|
+
If fast is enabled and a later thinking change or catalogue update removes support, the footer shows `Fast unavailable` and requests report an error until you select a supported thinking level or run `/cursor.fast off`. The command does not add duplicate fast models to `/model`.
|
|
81
115
|
|
|
82
116
|
The second-row display uses Pi 1.4's custom-footer slot and its default renderer. On other Pi versions it falls back to the standard status row until the footer adapter is verified. Extensions that replace the same footer slot can replace this layout; Cursor yields if another extension takes ownership. The `cursor-fast` status row is still set in that case, so a footer that renders extension statuses keeps showing the fast state; otherwise `/cursor.fast status` remains the source of truth.
|
|
83
117
|
|
|
@@ -108,10 +142,9 @@ Windows follow magpie, in this order.
|
|
|
108
142
|
- Cursor Models
|
|
109
143
|
- Other Models
|
|
110
144
|
- 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
145
|
- Total
|
|
113
146
|
|
|
114
|
-
|
|
147
|
+
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
148
|
|
|
116
149
|
```text
|
|
117
150
|
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/fast-footer.ts
CHANGED
|
@@ -70,8 +70,8 @@ export function createFastFooter(
|
|
|
70
70
|
render(width: number): string[] {
|
|
71
71
|
footer.setAutoCompactEnabled(pi.getSettings().compaction?.enabled ?? true)
|
|
72
72
|
const lines = footer.render(width)
|
|
73
|
-
const text = badge()
|
|
74
|
-
const label = theme.fg(text === "
|
|
73
|
+
const text = badge()
|
|
74
|
+
const label = theme.fg(text === "Fast" ? "accent" : "warning", text)
|
|
75
75
|
const suffix = ` • ${label}`
|
|
76
76
|
const reserved = visibleWidth(suffix)
|
|
77
77
|
lines[1] = width <= reserved
|
package/src/fast.ts
CHANGED
|
@@ -70,8 +70,10 @@ export function registerCursorFast(pi: ExtensionAPI) {
|
|
|
70
70
|
return
|
|
71
71
|
}
|
|
72
72
|
const on = enabled.has(model.id)
|
|
73
|
-
|
|
74
|
-
|
|
73
|
+
// Off is the default, so it stays off the footer. Only an enabled preference
|
|
74
|
+
// earns the row; an unsupported thinking level keeps it visible as a warning.
|
|
75
|
+
if (!on) { display(ctx, undefined); return }
|
|
76
|
+
display(ctx, supported(model, pi.getThinkingLevel()) ? "Fast" : "Fast unavailable")
|
|
75
77
|
}
|
|
76
78
|
|
|
77
79
|
function restore(ctx: ExtensionContext) {
|
|
@@ -108,12 +110,12 @@ export function registerCursorFast(pi: ExtensionAPI) {
|
|
|
108
110
|
pi.on("before_agent_start", (_event, ctx) => updateStatus(ctx))
|
|
109
111
|
|
|
110
112
|
pi.registerCommand("cursor.fast", {
|
|
111
|
-
description: "
|
|
113
|
+
description: "Toggle Cursor fast for the current model, or set on, off, or status",
|
|
112
114
|
getArgumentCompletions: (prefix) => ["on", "off"].filter((value) => value.startsWith(prefix.trimStart().toLowerCase())).map((value) => ({ value, label: value })),
|
|
113
115
|
handler: async (args, ctx) => {
|
|
114
|
-
const
|
|
115
|
-
if (!["on", "off", "status"].includes(
|
|
116
|
-
ctx.ui.notify("Usage: /cursor.fast on|off|status", "warning")
|
|
116
|
+
const requested = args.trim().toLowerCase()
|
|
117
|
+
if (requested && !["on", "off", "status"].includes(requested)) {
|
|
118
|
+
ctx.ui.notify("Usage: /cursor.fast [on|off|status]", "warning")
|
|
117
119
|
return
|
|
118
120
|
}
|
|
119
121
|
const model = modelOf(ctx)
|
|
@@ -121,6 +123,7 @@ export function registerCursorFast(pi: ExtensionAPI) {
|
|
|
121
123
|
ctx.ui.notify("Select a Cursor model with /model before using /cursor.fast.", "warning")
|
|
122
124
|
return
|
|
123
125
|
}
|
|
126
|
+
const action = requested || (enabled.has(model.id) ? "off" : "on")
|
|
124
127
|
if (action !== "status" && !ctx.isIdle()) {
|
|
125
128
|
ctx.ui.notify("Wait for the current response to finish before changing Cursor fast mode.", "warning")
|
|
126
129
|
return
|
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/native-session.ts
CHANGED
|
@@ -334,12 +334,13 @@ class Segment {
|
|
|
334
334
|
}
|
|
335
335
|
if (at < segment.events.length) {
|
|
336
336
|
const event = segment.events[at++]
|
|
337
|
-
if (replay && event.stop) return { value: { ...event, usage: {
|
|
337
|
+
if (replay && event.stop) return { value: { ...event, replay: true, usage: {
|
|
338
338
|
prompt_tokens: 0, completion_tokens: 0, total_tokens: 0,
|
|
339
|
+
cursor_output_source: "replayed",
|
|
339
340
|
prompt_tokens_details: { cached_tokens: 0, cache_write_tokens: 0 },
|
|
340
341
|
magpie_native: { accounting: "replayed" },
|
|
341
342
|
} }, done: false }
|
|
342
|
-
return { value: event, done: false }
|
|
343
|
+
return { value: replay ? { ...event, replay: true } : event, done: false }
|
|
343
344
|
}
|
|
344
345
|
return { done: true }
|
|
345
346
|
},
|
|
@@ -758,6 +759,7 @@ class NativeSession {
|
|
|
758
759
|
for (const c of segment.calls) this.pool.handles.set(c.id, { owner: this, batch: segment })
|
|
759
760
|
segment.finish({ stop: "tool_calls", usage: {
|
|
760
761
|
prompt_tokens: 0, completion_tokens: 0, total_tokens: 0,
|
|
762
|
+
cursor_output_source: "pending",
|
|
761
763
|
prompt_tokens_details: { cached_tokens: 0, cache_write_tokens: 0 },
|
|
762
764
|
magpie_native: { accounting: "pending" },
|
|
763
765
|
} })
|
|
@@ -872,6 +874,7 @@ class NativeSession {
|
|
|
872
874
|
const prompt = u.input + u.cacheRead + u.cacheWrite
|
|
873
875
|
this.finalUsage = {
|
|
874
876
|
prompt_tokens: prompt, completion_tokens: u.output, total_tokens: prompt + u.output,
|
|
877
|
+
cursor_output_source: !measuredOutput ? "estimated" : this.steps > 1 ? "allocated" : "measured",
|
|
875
878
|
prompt_tokens_details: { cached_tokens: u.cacheRead, cache_write_tokens: u.cacheWrite },
|
|
876
879
|
...(this.usageFields?.some((f) => f.num === 5) ? { completion_tokens_details: { reasoning_tokens: u.reasoning } } : {}),
|
|
877
880
|
...(!measuredInput || !measuredOutput ? { magpie_native: { accounting: "estimated" } } : {}),
|
package/src/pi-stream.ts
CHANGED
|
@@ -38,10 +38,25 @@ export interface CursorStreamOptions extends SimpleStreamOptions {
|
|
|
38
38
|
/** Shown when no Cursor credential is available. */
|
|
39
39
|
export const CURSOR_NOT_SIGNED_IN = "Cursor isn't signed in. Run /login cursor or set CURSOR_ACCESS_TOKEN."
|
|
40
40
|
|
|
41
|
+
export type CursorOutputTiming = {
|
|
42
|
+
outputTokens: number
|
|
43
|
+
source: "estimated" | "measured"
|
|
44
|
+
accountingSource?: "measured" | "estimated" | "allocated" | "pending" | "replayed" | "unavailable"
|
|
45
|
+
elapsedMs: number
|
|
46
|
+
/** Receive-side estimate after the first delta; absent without a measurable interval. */
|
|
47
|
+
tokensPerSecond?: number
|
|
48
|
+
tokensPerSecondSource?: "estimated"
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
type CursorMessage = AssistantMessage & { cursorOutputTiming?: CursorOutputTiming }
|
|
52
|
+
|
|
53
|
+
type Timed<T> = T & { cursorOutputTiming?: CursorOutputTiming }
|
|
54
|
+
|
|
41
55
|
type RunTool = { id: string; name: string; args: string }
|
|
42
56
|
type RunUsage = {
|
|
43
57
|
prompt_tokens?: number
|
|
44
58
|
completion_tokens?: number
|
|
59
|
+
cursor_output_source?: CursorOutputTiming["accountingSource"]
|
|
45
60
|
prompt_tokens_details?: { cached_tokens?: number; cache_write_tokens?: number }
|
|
46
61
|
completion_tokens_details?: { reasoning_tokens?: number }
|
|
47
62
|
/** Earlier steps' usage collected with this step; not applied to Pi context size. */
|
|
@@ -53,6 +68,7 @@ type RunUsage = {
|
|
|
53
68
|
}
|
|
54
69
|
}
|
|
55
70
|
type RunEvent = {
|
|
71
|
+
replay?: boolean
|
|
56
72
|
text?: string
|
|
57
73
|
reasoning?: string
|
|
58
74
|
tool?: RunTool
|
|
@@ -175,14 +191,45 @@ export async function emitCursorEvents(
|
|
|
175
191
|
events: AsyncIterable<RunEvent>,
|
|
176
192
|
options?: SimpleStreamOptions,
|
|
177
193
|
): Promise<void> {
|
|
178
|
-
const message = blank(model)
|
|
194
|
+
const message: CursorMessage = blank(model)
|
|
179
195
|
if (options?.reasoning) message.thinkingLevel = options.reasoning
|
|
196
|
+
let streamingAt: number | undefined
|
|
197
|
+
let elapsedMs = 0
|
|
198
|
+
let outputBytes = 0
|
|
199
|
+
// Bytes that opened a burst have no interval of their own, so the rate counts only what arrived after one.
|
|
200
|
+
let rateBytes = 0
|
|
201
|
+
const updateTiming = (text: string) => {
|
|
202
|
+
const now = performance.now()
|
|
203
|
+
const size = Buffer.byteLength(text, "utf8")
|
|
204
|
+
if (streamingAt === undefined) {
|
|
205
|
+
streamingAt = now
|
|
206
|
+
} else {
|
|
207
|
+
elapsedMs += Math.max(0, now - streamingAt)
|
|
208
|
+
streamingAt = now
|
|
209
|
+
rateBytes += size
|
|
210
|
+
}
|
|
211
|
+
outputBytes += size
|
|
212
|
+
const rateTokens = rateBytes / 4
|
|
213
|
+
// A fresh object each time: the previous event still points at the last one.
|
|
214
|
+
message.cursorOutputTiming = {
|
|
215
|
+
outputTokens: Math.ceil(outputBytes / 4),
|
|
216
|
+
source: "estimated",
|
|
217
|
+
elapsedMs,
|
|
218
|
+
...(elapsedMs > 0 && rateTokens > 0 ? { tokensPerSecond: rateTokens * 1000 / elapsedMs, tokensPerSecondSource: "estimated" as const } : {}),
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
const pauseTiming = () => {
|
|
222
|
+
streamingAt = undefined
|
|
223
|
+
}
|
|
180
224
|
let finished = false
|
|
181
225
|
let open: { kind: "text" | "thinking"; index: number } | null = null
|
|
182
226
|
|
|
183
227
|
const push = (event: AssistantMessageEvent) => {
|
|
184
228
|
if (finished) return
|
|
185
229
|
if (event.type === "done" || event.type === "error") finished = true
|
|
230
|
+
// partial stays the one shared message. Its timing object is replaced as deltas arrive and the queue
|
|
231
|
+
// holds events until the consumer reads, so the reading for this event is copied onto the event itself.
|
|
232
|
+
if (message.cursorOutputTiming) (event as Timed<typeof event>).cursorOutputTiming = { ...message.cursorOutputTiming }
|
|
186
233
|
stream.push(event)
|
|
187
234
|
}
|
|
188
235
|
const endOpen = () => {
|
|
@@ -217,6 +264,7 @@ export async function emitCursorEvents(
|
|
|
217
264
|
return
|
|
218
265
|
}
|
|
219
266
|
if (event.text) {
|
|
267
|
+
if (!event.replay) updateTiming(event.text)
|
|
220
268
|
if (open?.kind === "thinking") endOpen()
|
|
221
269
|
if (!open) {
|
|
222
270
|
message.content.push({ type: "text", text: "" })
|
|
@@ -228,6 +276,7 @@ export async function emitCursorEvents(
|
|
|
228
276
|
push({ type: "text_delta", contentIndex: open.index, delta: event.text, partial: message })
|
|
229
277
|
}
|
|
230
278
|
if (event.reasoning) {
|
|
279
|
+
if (!event.replay) updateTiming(event.reasoning)
|
|
231
280
|
if (open?.kind === "text") endOpen()
|
|
232
281
|
if (!open) {
|
|
233
282
|
message.content.push({ type: "thinking", thinking: "" })
|
|
@@ -239,6 +288,7 @@ export async function emitCursorEvents(
|
|
|
239
288
|
push({ type: "thinking_delta", contentIndex: open.index, delta: event.reasoning, partial: message })
|
|
240
289
|
}
|
|
241
290
|
if (event.tool) {
|
|
291
|
+
pauseTiming()
|
|
242
292
|
endOpen()
|
|
243
293
|
sawTool = true
|
|
244
294
|
const call: ToolCall = {
|
|
@@ -256,6 +306,15 @@ export async function emitCursorEvents(
|
|
|
256
306
|
if (event.stop) {
|
|
257
307
|
endOpen()
|
|
258
308
|
applyUsage(message, model, event.usage)
|
|
309
|
+
if (message.cursorOutputTiming && event.usage?.cursor_output_source) {
|
|
310
|
+
const source = event.usage.cursor_output_source
|
|
311
|
+
const measured = source === "measured" && typeof event.usage.completion_tokens === "number"
|
|
312
|
+
message.cursorOutputTiming = {
|
|
313
|
+
...message.cursorOutputTiming,
|
|
314
|
+
accountingSource: source,
|
|
315
|
+
...(measured ? { source: "measured", outputTokens: event.usage.completion_tokens } : {}),
|
|
316
|
+
}
|
|
317
|
+
}
|
|
259
318
|
const reason: Extract<StopReason, "stop" | "toolUse"> = sawTool || event.stop === "tool_calls" ? "toolUse" : "stop"
|
|
260
319
|
message.stopReason = reason
|
|
261
320
|
push({ type: "done", reason, message })
|
package/src/protocol.ts
CHANGED
|
@@ -37,6 +37,7 @@ export type RunUsage = {
|
|
|
37
37
|
/** Earlier steps' usage collected with this one. It is not this step's context size. */
|
|
38
38
|
magpie_deferred?: { prompt_tokens: number; completion_tokens: number; cached_tokens: number; cache_write_tokens: number }
|
|
39
39
|
magpie_native?: { accounting: "pending" | "estimated" | "replayed" }
|
|
40
|
+
cursor_output_source?: "measured" | "estimated" | "allocated" | "pending" | "replayed" | "unavailable"
|
|
40
41
|
}
|
|
41
42
|
|
|
42
43
|
/** What a Run streams to the caller. Each event sets one of text, reasoning, tool, stop, or error. */
|
|
@@ -355,8 +356,12 @@ export async function* decode(
|
|
|
355
356
|
let wrote = 0
|
|
356
357
|
let usage: UsageCounts = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, reasoning: 0 }
|
|
357
358
|
let counted = false
|
|
359
|
+
let outputSource: RunUsage["cursor_output_source"] = "unavailable"
|
|
358
360
|
const finish = (more: UsageCounts | null) => {
|
|
359
|
-
if (!counted && !usage.output)
|
|
361
|
+
if (!counted && !usage.output) {
|
|
362
|
+
usage.output = Math.floor((said + 3) / 4)
|
|
363
|
+
outputSource = "estimated"
|
|
364
|
+
}
|
|
360
365
|
if (!counted && !usage.input && !usage.cacheRead && !usage.cacheWrite) usage.input = estimate
|
|
361
366
|
const prompt = usage.input + usage.cacheRead + usage.cacheWrite
|
|
362
367
|
const deferred = more && more.input + more.output + more.cacheRead + more.cacheWrite > 0
|
|
@@ -365,6 +370,7 @@ export async function* decode(
|
|
|
365
370
|
usage: {
|
|
366
371
|
prompt_tokens: prompt,
|
|
367
372
|
completion_tokens: usage.output,
|
|
373
|
+
cursor_output_source: outputSource,
|
|
368
374
|
total_tokens: prompt + usage.output,
|
|
369
375
|
prompt_tokens_details: { cached_tokens: usage.cacheRead, cache_write_tokens: usage.cacheWrite },
|
|
370
376
|
...(usage.reasoning ? { completion_tokens_details: { reasoning_tokens: usage.reasoning } } : {}),
|
|
@@ -385,7 +391,10 @@ export async function* decode(
|
|
|
385
391
|
if (calls > 0 && !ended && stepUsage) {
|
|
386
392
|
close?.()
|
|
387
393
|
const u = await stepUsage().catch(() => null)
|
|
388
|
-
if (u)
|
|
394
|
+
if (u) {
|
|
395
|
+
usage = u
|
|
396
|
+
outputSource = "measured"
|
|
397
|
+
}
|
|
389
398
|
counted = u === false || !!u
|
|
390
399
|
} else if (calls > 0) {
|
|
391
400
|
close?.()
|
|
@@ -455,6 +464,7 @@ export async function* decode(
|
|
|
455
464
|
}
|
|
456
465
|
case 14: // turn ended, with what it used
|
|
457
466
|
usage = usageOf(uf)
|
|
467
|
+
outputSource = uf.some((field) => field.num === 2) ? "measured" : "unavailable"
|
|
458
468
|
ended = true
|
|
459
469
|
counted = true
|
|
460
470
|
if (calls === 0) {
|
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) {
|