@caph42/pi-cursor-provider 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,83 @@
1
+ import * as Pi from "@earendil-works/pi-coding-agent"
2
+ import type { ExtensionAPI, ExtensionContext, ReadonlyFooterDataProvider, Theme } from "@earendil-works/pi-coding-agent"
3
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui"
4
+ import type { TUI } from "@earendil-works/pi-tui"
5
+
6
+ const FooterComponent = Pi.FooterComponent
7
+
8
+ // The adapter below follows the inspected 1.4 renderer. Other versions retain
9
+ // the standard status row until their footer contract has been verified.
10
+ export const supportsInlineFastFooter = /^1\.4\./.test(Pi.VERSION) && typeof FooterComponent === "function"
11
+
12
+ /** Keep Pi's standard footer formatting, reserving space in row two for fast. */
13
+ export function createFastFooter(
14
+ context: () => ExtensionContext,
15
+ pi: Pick<ExtensionAPI, "getThinkingLevel" | "getSettings">,
16
+ badge: () => string,
17
+ tui: Pick<TUI, "requestRender">,
18
+ theme: Theme,
19
+ data: ReadonlyFooterDataProvider,
20
+ onDispose: () => void = () => {},
21
+ ) {
22
+ let leaf: string | null | undefined
23
+ let entries: ReturnType<ExtensionContext["sessionManager"]["getEntries"]> | undefined
24
+ const getEntries = () => {
25
+ const manager = context().sessionManager
26
+ if (!entries || leaf !== manager.getLeafId()) {
27
+ leaf = manager.getLeafId()
28
+ entries = manager.getEntries()
29
+ }
30
+ return entries
31
+ }
32
+ // FooterComponent (Pi 1.4) reads only this session surface. Supply it from
33
+ // public extension context APIs; the real model/session are never modified.
34
+ const session = {
35
+ get model() { return context().model },
36
+ get routedModel() { return undefined }, // Installed only for physical Cursor models.
37
+ get state() { return { model: context().model, thinkingLevel: pi.getThinkingLevel() } },
38
+ sessionManager: {
39
+ getCwd: () => context().sessionManager.getCwd(),
40
+ getSessionId: () => context().sessionManager.getSessionId(),
41
+ getLeafId: () => context().sessionManager.getLeafId(),
42
+ getSessionName: () => context().sessionManager.getSessionName(),
43
+ getEntryCount: () => getEntries().length,
44
+ getEntries,
45
+ },
46
+ getContextUsage: () => context().getContextUsage(),
47
+ modelRuntime: {
48
+ isUsingSubscription: (provider: string) => {
49
+ const ctx = context()
50
+ return ctx.model?.provider === provider && ctx.modelRegistry.isUsingOAuth(ctx.model) &&
51
+ ctx.modelRegistry.getProvider(provider)?.auth.oauth?.isSubscription === true
52
+ },
53
+ },
54
+ }
55
+ const footer = new FooterComponent(session as unknown as ConstructorParameters<typeof FooterComponent>[0], {
56
+ getGitBranch: () => data.getGitBranch(),
57
+ getAvailableProviderCount: () => data.getAvailableProviderCount(),
58
+ onBranchChange: (callback) => data.onBranchChange(callback),
59
+ getExtensionStatuses: () => new Map([...data.getExtensionStatuses()].filter(([key]) => key !== "cursor-fast")),
60
+ })
61
+ const unsubscribe = data.onBranchChange(() => tui.requestRender())
62
+ return {
63
+ invalidate: () => footer.invalidate(),
64
+ dispose() {
65
+ unsubscribe()
66
+ footer.dispose()
67
+ entries = undefined
68
+ onDispose()
69
+ },
70
+ render(width: number): string[] {
71
+ footer.setAutoCompactEnabled(pi.getSettings().compaction?.enabled ?? true)
72
+ const lines = footer.render(width)
73
+ const text = badge().replace(/^Cursor /, "")
74
+ const label = theme.fg(text === "fast: on" ? "accent" : "dim", text)
75
+ const suffix = ` • ${label}`
76
+ const reserved = visibleWidth(suffix)
77
+ lines[1] = width <= reserved
78
+ ? truncateToWidth(label, width, "")
79
+ : truncateToWidth((footer.render(width - reserved)[1] ?? "") + suffix, width, "")
80
+ return lines
81
+ },
82
+ }
83
+ }
package/src/fast.ts ADDED
@@ -0,0 +1,156 @@
1
+ import type { Model, SimpleStreamOptions, TranscriptContext } from "@earendil-works/pi-ai"
2
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent"
3
+ import { streamCursor } from "./pi-stream.ts"
4
+ import { createFastFooter, supportsInlineFastFooter } from "./fast-footer.ts"
5
+ import { cursorFastAutocomplete } from "./fast-autocomplete.ts"
6
+
7
+ const ENTRY = "cursor-fast"
8
+ const STATUS = "cursor-fast"
9
+
10
+ type FastModel = Model<any> & { cursorFastLevels?: string[] }
11
+
12
+ export function registerCursorFast(pi: ExtensionAPI) {
13
+ const enabled = new Set<string>()
14
+ let sessionId: string | undefined
15
+ let currentContext: ExtensionContext | undefined
16
+ let badge = ""
17
+ let footerInstalled = false
18
+ let footerYielded = false
19
+ let removingFooter = false
20
+ let footerUI: ExtensionContext["ui"] | undefined
21
+ let requestRender: (() => void) | undefined
22
+ let autocompleteInstalled = false
23
+
24
+ function clearFooter() {
25
+ if (!footerInstalled) return
26
+ removingFooter = true
27
+ try { footerUI?.setFooter(undefined) } finally { removingFooter = false }
28
+ footerInstalled = false
29
+ footerUI = undefined
30
+ requestRender = undefined
31
+ }
32
+
33
+ function display(ctx: ExtensionContext, text: string | undefined) {
34
+ if (ctx.mode !== "tui" || !supportsInlineFastFooter) {
35
+ ctx.ui.setStatus(STATUS, text)
36
+ return
37
+ }
38
+ ctx.ui.setStatus(STATUS, undefined)
39
+ if (!text) { clearFooter(); return }
40
+ badge = text
41
+ if (!footerInstalled && !footerYielded) {
42
+ footerUI = ctx.ui
43
+ footerInstalled = true
44
+ ctx.ui.setFooter((tui, theme, data) => {
45
+ requestRender = () => tui.requestRender()
46
+ return createFastFooter(() => currentContext!, pi, () => badge, tui, theme, data, () => {
47
+ footerInstalled = false
48
+ requestRender = undefined
49
+ // Another extension may replace the shared footer. Yield ownership
50
+ // rather than repeatedly replacing it or clearing its footer later.
51
+ if (!removingFooter) footerYielded = true
52
+ })
53
+ })
54
+ }
55
+ requestRender?.()
56
+ }
57
+
58
+ const modelOf = (ctx: ExtensionContext): FastModel | undefined => {
59
+ if (ctx.model?.provider !== "cursor") return undefined
60
+ return (ctx.modelRegistry.find("cursor", ctx.model.id) ?? ctx.model) as FastModel
61
+ }
62
+ const supported = (model: FastModel, level: string) => Array.isArray(model.cursorFastLevels) && model.cursorFastLevels.includes(level)
63
+
64
+ function updateStatus(ctx: ExtensionContext) {
65
+ currentContext = ctx
66
+ const model = modelOf(ctx)
67
+ if (!model) {
68
+ display(ctx, undefined)
69
+ return
70
+ }
71
+ const on = enabled.has(model.id)
72
+ const available = supported(model, pi.getThinkingLevel())
73
+ display(ctx, available ? `Cursor fast: ${on ? "on" : "off"}` : `Cursor fast: ${on ? "on (unavailable)" : "unavailable"}`)
74
+ }
75
+
76
+ function restore(ctx: ExtensionContext) {
77
+ enabled.clear()
78
+ sessionId = ctx.sessionManager.getSessionId()
79
+ for (const entry of ctx.sessionManager.getBranch()) {
80
+ if (entry.type !== "custom" || entry.customType !== ENTRY) continue
81
+ const data = entry.data as { model?: unknown; enabled?: unknown } | undefined
82
+ if (typeof data?.model !== "string" || typeof data.enabled !== "boolean") continue
83
+ if (data.enabled) enabled.add(data.model)
84
+ else enabled.delete(data.model)
85
+ }
86
+ updateStatus(ctx)
87
+ }
88
+
89
+ pi.on("session_start", (_event, ctx) => {
90
+ restore(ctx)
91
+ if (ctx.mode === "tui" && !autocompleteInstalled && typeof ctx.ui.addAutocompleteProvider === "function") {
92
+ ctx.ui.addAutocompleteProvider(cursorFastAutocomplete)
93
+ autocompleteInstalled = true
94
+ }
95
+ })
96
+ pi.on("session_tree", (_event, ctx) => restore(ctx))
97
+ pi.on("session_shutdown", (_event, ctx) => {
98
+ clearFooter()
99
+ ctx.ui.setStatus(STATUS, undefined)
100
+ currentContext = undefined
101
+ sessionId = undefined
102
+ autocompleteInstalled = false
103
+ enabled.clear()
104
+ })
105
+ pi.on("model_select", (_event, ctx) => updateStatus(ctx))
106
+ pi.on("thinking_level_select", (_event, ctx) => updateStatus(ctx))
107
+ pi.on("before_agent_start", (_event, ctx) => updateStatus(ctx))
108
+
109
+ pi.registerCommand("cursor.fast", {
110
+ description: "Set Cursor fast mode for the current model: on, off, or status",
111
+ getArgumentCompletions: (prefix) => ["on", "off"].filter((value) => value.startsWith(prefix.trimStart().toLowerCase())).map((value) => ({ value, label: value })),
112
+ handler: async (args, ctx) => {
113
+ const action = args.trim().toLowerCase() || "status"
114
+ if (!["on", "off", "status"].includes(action)) {
115
+ ctx.ui.notify("Usage: /cursor.fast on|off|status", "warning")
116
+ return
117
+ }
118
+ const model = modelOf(ctx)
119
+ if (!model) {
120
+ ctx.ui.notify("Select a Cursor model with /model before using /cursor.fast.", "warning")
121
+ return
122
+ }
123
+ if (action !== "status" && !ctx.isIdle()) {
124
+ ctx.ui.notify("Wait for the current response to finish before changing Cursor fast mode.", "warning")
125
+ return
126
+ }
127
+ const level = pi.getThinkingLevel()
128
+ if (action === "on" && !supported(model, level)) {
129
+ ctx.ui.notify(`Cursor fast is unavailable for ${model.id} at thinking ${level}. Refresh /model if the catalogue is outdated.`, "warning")
130
+ updateStatus(ctx)
131
+ return
132
+ }
133
+ if (action !== "status") {
134
+ const on = action === "on"
135
+ pi.appendEntry(ENTRY, { model: model.id, enabled: on })
136
+ if (on) enabled.add(model.id)
137
+ else enabled.delete(model.id)
138
+ }
139
+ updateStatus(ctx)
140
+ const on = enabled.has(model.id)
141
+ const unavailable = supported(model, level) ? "" : " (unavailable at this thinking level)"
142
+ ctx.ui.notify(`Cursor fast: ${on ? "on" : "off"}${unavailable} — ${model.id}; thinking ${level}.`, "info")
143
+ },
144
+ })
145
+
146
+ return {
147
+ updateStatus,
148
+ catalogueChanged() { if (currentContext) updateStatus(currentContext) },
149
+ stream(model: Model<any>, context: TranscriptContext, options?: SimpleStreamOptions) {
150
+ // A provider may also serve nested/background requests. Only apply the
151
+ // preference to requests explicitly belonging to this Pi session.
152
+ const fast = sessionId !== undefined && options?.sessionId === sessionId && enabled.has(model.id)
153
+ return streamCursor(model, context, { ...options, fast })
154
+ },
155
+ }
156
+ }
package/src/index.ts CHANGED
@@ -6,75 +6,140 @@
6
6
  * A native Run in this process stays open and takes call_cursor_ results.
7
7
  * This does not register a parked bridge, a checkpoint, or a run journal.
8
8
  */
9
- import type { RefreshModelsContext } from "@earendil-works/pi-ai"
10
- import type { ExtensionAPI, ProviderModelConfig } from "@earendil-works/pi-coding-agent"
9
+ import { createHash } from "node:crypto"
10
+ import type { Model, Provider } from "@earendil-works/pi-ai"
11
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"
11
12
  import { login, refresh, resolveAccessToken } from "./auth.ts"
12
13
  import { AGENT, clientVersion } from "./client.ts"
13
- import { configPath, hiddenPatterns, visible } from "./config.ts"
14
+ import { hiddenPatterns, visible } from "./config.ts"
15
+ import { registerCursorDoctor } from "./doctor.ts"
14
16
  import { piModelConfigs, usable } from "./models.ts"
15
- import { streamCursor } from "./pi-stream.ts"
17
+ import { registerCursorFast } from "./fast.ts"
16
18
  import { fetchUsage, formatUsage } from "./usage.ts"
17
19
 
18
20
  export { fetchUsage, formatUsage, onDemandOf } from "./usage.ts"
19
21
 
20
- // offered is every model Cursor offers the account; models is what cursor.json keeps
21
- let offered: ProviderModelConfig[] = []
22
- let models: ProviderModelConfig[] = []
22
+ // One catalogue per credential: a refresh for one account must never serve
23
+ // its models to another.
24
+ const catalogs = new Map<string, Model<"cursor-run">[]>()
23
25
 
24
- async function refreshModels(ctx: RefreshModelsContext): Promise<ProviderModelConfig[]> {
25
- if (ctx.signal.aborted) return models
26
- if (ctx.allowNetwork) {
27
- const fromCred =
28
- ctx.credential?.type === "oauth" ? ctx.credential.access : ctx.credential?.type === "api_key" ? ctx.credential.key : undefined
29
- const auth = await resolveAccessToken({ apiKey: fromCred })
30
- if (auth) {
31
- try {
32
- offered = piModelConfigs(await usable(auth.token, ctx.force === true)) as ProviderModelConfig[]
33
- } catch {
34
- // keep the list Cursor gave last; only the hide list below changes
35
- }
36
- }
37
- }
38
- // cursor.json is read on every refresh, network or not, so a hidden model leaves
39
- // the picker on the next list refresh
40
- models = visible(offered, hiddenPatterns())
41
- return models
26
+ function credentialKey(token: string): string {
27
+ return createHash("sha256").update(token).digest("hex")
42
28
  }
43
29
 
30
+
44
31
  export default function (pi: ExtensionAPI) {
45
- pi.registerProvider("cursor", {
32
+ // Keep the complete catalogue per registration. Local visibility rules must
33
+ // also run on synchronous reads, not only when a remote refresh completes.
34
+ let offered: Model<"cursor-run">[] = []
35
+ // Which credential produced `offered`; undefined when it came from Pi's cache
36
+ // alone, whose provenance this provider cannot see.
37
+ let offeredKey: string | undefined
38
+ const fast = registerCursorFast(pi)
39
+ const provider: Provider<"cursor-run"> = {
40
+ id: "cursor",
46
41
  name: "Cursor",
47
42
  baseUrl: AGENT,
48
- apiKey: "$CURSOR_ACCESS_TOKEN",
49
- api: "cursor-run",
50
- models,
51
- oauth: {
52
- name: "Cursor",
53
- isSubscription: true,
54
- login,
55
- refreshToken: (credentials, signal) => refresh(credentials, signal),
56
- getApiKey: (credentials) => credentials.access,
43
+ getModels: () => visible(offered, hiddenPatterns()),
44
+ // Pi applies this after models.json overlays, including user-added models.
45
+ filterModels: (models) => visible(models, hiddenPatterns()),
46
+ auth: {
47
+ apiKey: {
48
+ name: "Cursor access token",
49
+ resolve: async ({ ctx, credential }) => {
50
+ const auth = await resolveAccessToken({
51
+ apiKey: credential?.key,
52
+ env: { CURSOR_ACCESS_TOKEN: await ctx.env("CURSOR_ACCESS_TOKEN") },
53
+ })
54
+ return auth ? { auth: { apiKey: auth.token }, source: auth.source } : undefined
55
+ },
56
+ },
57
+ oauth: {
58
+ name: "Cursor",
59
+ isSubscription: true,
60
+ login: async (interaction) => ({
61
+ ...(await login({
62
+ onAuth: (info) => interaction.notify({ type: "auth_url", ...info }),
63
+ onDeviceCode: (info) => interaction.notify({ type: "device_code", ...info }),
64
+ onSelect: (prompt) => interaction.prompt({ type: "select", ...prompt }),
65
+ onPrompt: (prompt) => interaction.prompt({ type: "text", ...prompt }),
66
+ onProgress: (message) => interaction.notify({ type: "progress", message }),
67
+ signal: interaction.signal,
68
+ })),
69
+ type: "oauth",
70
+ }),
71
+ refresh: async (credential, signal) => ({ ...(await refresh(credential, signal)), type: "oauth" }),
72
+ toAuth: async (credential) => ({ apiKey: credential.access }),
73
+ },
57
74
  },
58
- refreshModels,
59
- streamSimple: streamCursor,
60
- })
61
-
62
- pi.registerCommand("cursor.doctor", {
63
- description: "Show which Cursor credential would be used, without printing the token",
64
- handler: async (args, ctx) => {
65
- const extra = args.trim() ? " This command does not take arguments." : ""
66
- const auth = await resolveAccessToken()
67
- const version = await clientVersion()
68
- const patterns = hiddenPatterns()
69
- const hiddenText = patterns.length ? `Hidden from /model: ${patterns.join(", ")} (${configPath()}).` : `No models hidden (${configPath()}).`
70
- if (!auth) {
71
- ctx.ui.notify(`Cursor is not signed in (${version}). Run /login cursor or set CURSOR_ACCESS_TOKEN. ${hiddenText}${extra}`, "warning")
75
+ refreshModels: async (ctx) => {
76
+ if (ctx.signal.aborted) return
77
+ // Pi initializes and reloads extensions without network access. Restore
78
+ // the unfiltered catalogue before that phase returns, including when a
79
+ // subsequent network refresh fails or is cancelled.
80
+ if (!offered.length && ctx.stored) {
81
+ const cached = ctx.stored.models.filter((model): model is Model<"cursor-run"> =>
82
+ model.provider === "cursor" && model.api === "cursor-run" && (model.type === undefined || model.type === "chat"),
83
+ )
84
+ if (cached.length) await ctx.publish({ update: () => { offered = cached; offeredKey = undefined; fast.catalogueChanged() } })
85
+ }
86
+ const hinted = ctx.credential?.type === "oauth" ? ctx.credential.access : ctx.credential?.type === "api_key" ? ctx.credential.key : undefined
87
+ const auth = ctx.signal.aborted ? undefined : await resolveAccessToken({ apiKey: hinted })
88
+ if (ctx.signal.aborted) return
89
+ const token = auth?.token ?? hinted
90
+ // Serve the catalogue this credential already discovered, without the
91
+ // network, so an offline reload does not look like a signed-out account.
92
+ const kept = token ? catalogs.get(credentialKey(token)) : undefined
93
+ if (!ctx.allowNetwork || !auth) {
94
+ if (kept?.length) {
95
+ await ctx.publish({ update: () => { offered = kept; offeredKey = token ? credentialKey(token) : undefined; fast.catalogueChanged() } })
96
+ }
72
97
  return
73
98
  }
74
- ctx.ui.notify(`Cursor auth source: ${auth.source}. Client ${version}. ${hiddenText} Token not shown.${extra}`, "info")
99
+ const key = credentialKey(auth.token)
100
+ try {
101
+ const next = piModelConfigs(await usable(auth.token, ctx.force === true, ctx.signal)).map((model: Model<"cursor-run">) => ({
102
+ ...model,
103
+ provider: "cursor",
104
+ baseUrl: AGENT,
105
+ })) as Model<"cursor-run">[]
106
+ if (ctx.signal.aborted) return
107
+ catalogs.set(key, next)
108
+ await ctx.publish({
109
+ persist: { models: next, checkedAt: Date.now() },
110
+ update: () => { offered = next; offeredKey = key; fast.catalogueChanged() },
111
+ })
112
+ } catch (error) {
113
+ // Never keep another credential's catalogue after a failed refresh: fall
114
+ // back to what this one discovered, even if that is nothing.
115
+ const unknownSource = offeredKey === undefined
116
+ const previous = catalogs.get(key) ?? []
117
+ await ctx.publish({ update: () => { offered = previous; offeredKey = key; fast.catalogueChanged() } })
118
+ // Surface a first-load failure instead of reporting an empty provider as
119
+ // a successful refresh.
120
+ if (!previous.length && unknownSource) throw error
121
+ }
75
122
  },
123
+ stream: fast.stream,
124
+ streamSimple: fast.stream,
125
+ }
126
+ pi.registerProvider(provider)
127
+
128
+ // Startup and /reload restore cached models first. Discover the catalogue
129
+ // for a first install too, once the host has bound credentials and context.
130
+ pi.on("session_start", async (_event, ctx) => {
131
+ const result = await ctx.modelRegistry.refresh({
132
+ providers: ["cursor"],
133
+ allowNetwork: process.env.PI_OFFLINE === undefined,
134
+ signal: AbortSignal.timeout(15_000),
135
+ })
136
+ fast.updateStatus(ctx)
137
+ const error = result.errors.get("cursor")
138
+ if (error && ctx.hasUI) ctx.ui.notify(`Cursor model catalogue: ${error.message}`, "warning")
76
139
  })
77
140
 
141
+ registerCursorDoctor(pi)
142
+
78
143
  pi.registerCommand("cursor.usage", {
79
144
  description: "Show Cursor plan usage for this billing period",
80
145
  handler: async (args, ctx) => {
@@ -85,17 +150,16 @@ export default function (pi: ExtensionAPI) {
85
150
  ctx.ui.notify(`Cursor is not signed in (${version}). Run /login cursor or set CURSOR_ACCESS_TOKEN.${extra}`, "warning")
86
151
  return
87
152
  }
88
- // every model the account has: usage windows classify events by these, hidden or not
89
- let ids = offered.map((m) => m.id)
153
+ let ids = (catalogs.get(credentialKey(auth.token)) ?? offered).map((m) => m.id)
90
154
  if (!ids.length) {
91
155
  try {
92
- ids = (await usable(auth.token)).map((m: { id: string }) => m.id)
156
+ ids = (await usable(auth.token, false, ctx.signal)).map((m: { id: string }) => m.id)
93
157
  } catch {
94
158
  ids = []
95
159
  }
96
160
  }
97
161
  try {
98
- const report = await fetchUsage(auth.token, ids)
162
+ const report = await fetchUsage(auth.token, ids, ctx.signal)
99
163
  ctx.ui.notify(formatUsage(report) + extra, report.error ? "warning" : "info")
100
164
  } catch (e) {
101
165
  ctx.ui.notify(`Cursor usage could not be read. ${e instanceof Error ? e.message : String(e)}${extra}`, "warning")
package/src/ledger.ts CHANGED
@@ -12,6 +12,8 @@
12
12
  // @ts-nocheck
13
13
  import { createHash } from "node:crypto"
14
14
  import { API, headersFor } from "./client.ts"
15
+ import { sleep } from "./sleep.ts"
16
+ import { trace, type Account } from "./trace.ts"
15
17
 
16
18
  // STEP_WAIT is how long a step's event is looked for: first after that long,
17
19
  // then every so often until the end (each ask given `ask` to answer).
@@ -55,14 +57,59 @@ export const misses = new Map()
55
57
  const tokKey = (tok) => createHash("sha256").update(tok).digest("hex")
56
58
  export const usageKey = (tok, conv) => tokKey(tok) + "\0" + conv
57
59
 
60
+ const stepsWait = (missed) => missed < STEP_WAIT.skipAfter || missed % STEP_WAIT.retryEvery === 0
61
+ const refusedUntil = (at) => at + STEP_WAIT.owedFor
62
+
58
63
  export function canRead(tok) {
59
64
  const at = unreadable.get(tokKey(tok))
60
65
  if (at === undefined) return true
61
- if (Date.now() - at < STEP_WAIT.owedFor) return false
66
+ if (Date.now() < refusedUntil(at)) return false
62
67
  unreadable.delete(tokKey(tok))
63
68
  return true
64
69
  }
65
70
 
71
+ /** The usage ledger in a form the doctor may print. */
72
+ export type LedgerState = {
73
+ /** Every account. */
74
+ owed: { runs: number; conversations: number; collecting: number }
75
+ /** The account the reader asked about. null without one. */
76
+ current: { runsOwed: number; misses: number; stepsWait: boolean; unreadableUntil: number | null } | null
77
+ /** Other accounts whose usage events Cursor still refuses. */
78
+ unreadableOthers: number
79
+ }
80
+
81
+ // Unlike canRead and owe, this deletes no expired entry.
82
+ export function ledgerState(account: Account | undefined, now = Date.now()): LedgerState {
83
+ const live = (since) => now - since <= STEP_WAIT.owedFor
84
+ const runsOf = (d) => (d.groups ? d.groups.filter((g) => live(g.since)).reduce((n, g) => n + g.n, 0) : live(d.since) ? d.n : 0)
85
+ let runs = 0
86
+ let conversations = 0
87
+ let runsOwed = 0
88
+ for (const [key, d] of owed) {
89
+ const n = runsOf(d)
90
+ if (!n) continue
91
+ runs += n
92
+ conversations++
93
+ if (account?.is(key.slice(0, key.indexOf("\0")))) runsOwed += n
94
+ }
95
+ let collecting = 0
96
+ for (const set of flights.values()) collecting += set.size
97
+ let unreadableUntil = null
98
+ let unreadableOthers = 0
99
+ for (const [key, at] of unreadable) {
100
+ if (now >= refusedUntil(at)) continue
101
+ if (account?.is(key)) unreadableUntil = refusedUntil(at)
102
+ else unreadableOthers++
103
+ }
104
+ let missed = 0
105
+ for (const [key, n] of misses) if (account?.is(key)) missed = n
106
+ return {
107
+ owed: { runs, conversations, collecting },
108
+ current: account ? { runsOwed, misses: missed, stepsWait: stepsWait(missed), unreadableUntil } : null,
109
+ unreadableOthers,
110
+ }
111
+ }
112
+
66
113
  const ZERO = () => ({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0, reasoning: 0 })
67
114
  function addUsage(a, b) {
68
115
  if (!b) return a
@@ -117,10 +164,7 @@ export function owe(key, { since = Date.now(), n = 0, ready = Date.now(), carry
117
164
  export async function usageEvents(tok, conv, since, want, { poll = false, first = STEP_WAIT.first, signal, before = () => Infinity, groups, abortFetch = false } = {}) {
118
165
  const key = usageKey(tok, conv)
119
166
  const end = Date.now() + STEP_WAIT.until
120
- const wait = (ms) => new Promise((r) => {
121
- const t = setTimeout(r, ms)
122
- signal?.addEventListener("abort", () => (clearTimeout(t), r()), { once: true })
123
- })
167
+ const wait = (ms) => sleep(ms, signal, "resolve")
124
168
  for (const [k, at] of claimed) if (Date.now() - at > 2 * STEP_WAIT.owedFor) claimed.delete(k)
125
169
  const num = (v) => (Number.isFinite(Number(v)) ? Number(v) : 0)
126
170
  let usage = null
@@ -138,8 +182,10 @@ export async function usageEvents(tok, conv, since, want, { poll = false, first
138
182
  })
139
183
  if (res.status >= 400 && res.status < 500 && res.status !== 429) {
140
184
  unreadable.set(tokKey(tok), Date.now())
185
+ trace?.note("usage", { status: res.status, refused: true })
141
186
  return { usage, events, got, counts, refused: true }
142
187
  }
188
+ if (!res.ok) trace?.note("usage", { status: res.status })
143
189
  const evs = res.ok ? ((await res.json())?.usageEventsDisplay ?? []) : []
144
190
  const found = evs
145
191
  .filter((e) => e?.conversationId === conv && e.tokenUsage && num(e.timestamp) >= since - 1000 && !claimed.has(key + "\0" + e.timestamp))
@@ -159,7 +205,9 @@ export async function usageEvents(tok, conv, since, want, { poll = false, first
159
205
  got++
160
206
  }
161
207
  if (got >= want) break
162
- } catch {}
208
+ } catch (e) {
209
+ if (!signal?.aborted) trace?.note("usage", { error: e })
210
+ }
163
211
  if (!poll || Date.now() + STEP_WAIT.every > end) break
164
212
  await wait(STEP_WAIT.every)
165
213
  }
@@ -182,7 +230,10 @@ function collect(tok, conv, { poll = false, first, signal, over = () => false, a
182
230
  let r = { usage: null, events: [], got: 0 }
183
231
  if (want > 0 && canRead(tok)) r = await usageEvents(tok, conv, Math.min(...groups.map((g) => g.since)), want, {
184
232
  poll, first, signal, abortFetch, before: () => d.before ?? Infinity, ...(d.groups ? { groups } : {}),
185
- }).catch(() => r)
233
+ }).catch((e) => {
234
+ trace?.note("usage", { error: e })
235
+ return r
236
+ })
186
237
  let short = false
187
238
  for (const [i, g] of groups.entries()) {
188
239
  const remaining = g.n - (d.groups ? r.counts?.[i] ?? 0 : r.got)
@@ -248,9 +299,14 @@ export function ledger(tok, conv, since, signal, kept, { before } = {}) {
248
299
  async own() {
249
300
  if (!canRead(tok)) return null
250
301
  const m = misses.get(key) ?? 0
251
- const waits = m < STEP_WAIT.skipAfter || m % STEP_WAIT.retryEvery === 0
302
+ const waits = stepsWait(m)
252
303
  if (!kept) {
253
- const r = waits ? await usageEvents(tok, conv, since, 1, { poll: true, signal }).catch(() => ({})) : {}
304
+ const r = waits
305
+ ? await usageEvents(tok, conv, since, 1, { poll: true, signal }).catch((e) => {
306
+ trace?.note("usage", { error: e })
307
+ return {}
308
+ })
309
+ : {}
254
310
  if (r.usage) misses.delete(key)
255
311
  else if (!r.refused) misses.set(key, m + 1)
256
312
  return r.usage ?? null
package/src/models.ts CHANGED
@@ -6,8 +6,8 @@
6
6
  * Billing-period windows live in usage.ts; per-step deferred usage in ledger.ts.
7
7
  */
8
8
  // @ts-nocheck
9
- import { createHash } from "node:crypto"
10
9
  import { API, DEFAULT_CONTEXT, MODELS_KEEP, unary } from "./client.ts"
10
+ import { recall, store, tokenKey } from "./cache.ts"
11
11
 
12
12
  const LEVEL_RANK = ["none", "minimal", "low", "medium", "high", "xhigh", "max"]
13
13
  const EFFORT_PARAMS = ["effort", "reasoning_effort", "reasoning"]
@@ -241,23 +241,31 @@ function fitEffort(want, levels) {
241
241
  // can't give is a failure: magpie keeps the list it had. A usable list it
242
242
  // can't give leaves the picker as it is.
243
243
  const lists = new Map()
244
- export async function usable(tok, force = false) {
245
- const h = createHash("sha256").update(tok).digest("hex")
246
- const had = lists.get(h)
247
- if (!force && had && Date.now() - had.at < MODELS_KEEP) return had.raw
244
+ export function modelCacheKeys() {
245
+ return [...lists.keys()]
246
+ }
247
+ export async function usable(tok, force = false, signal?: AbortSignal) {
248
+ const h = tokenKey(tok)
249
+ const had = recall(lists, h)
250
+ if (signal?.aborted) throw Object.assign(new Error("The operation was aborted"), { name: "AbortError" })
251
+ if (!force && had) return had.raw
248
252
  const [j, ids] = await Promise.all([
249
- unary(API, "aiserver.v1.AiService/AvailableModels", tok, { useModelParameters: true, doNotUseMarkdown: true }, 30_000),
250
- unary(API, "agent.v1.AgentService/GetUsableModels", tok, {}, 8_000).then(
253
+ unary(API, "aiserver.v1.AiService/AvailableModels", tok, { useModelParameters: true, doNotUseMarkdown: true }, 30_000, signal),
254
+ unary(API, "agent.v1.AgentService/GetUsableModels", tok, {}, 8_000, signal).then(
251
255
  (u) => {
252
256
  const ids = new Set((u?.models ?? []).flatMap((m) => [m.modelId, m.displayModelId]).filter(Boolean))
253
257
  return ids.size ? ids : null
254
258
  },
255
- () => null,
259
+ (err) => {
260
+ if (signal?.aborted) throw err
261
+ return null
262
+ },
256
263
  ),
257
264
  ])
265
+ if (signal?.aborted) throw Object.assign(new Error("The operation was aborted"), { name: "AbortError" })
258
266
  const raw = modelsOf(Array.isArray(j?.models) ? j.models : [], ids)
259
267
  if (!raw.length) throw new Error("Cursor listed no models")
260
- lists.set(h, { at: Date.now(), raw })
268
+ store(lists, h, { raw, expires: 0 }, MODELS_KEEP)
261
269
  return raw
262
270
  }
263
271
 
@@ -317,6 +325,23 @@ function thinkingLevelMap(levels) {
317
325
  return map
318
326
  }
319
327
 
328
+ // Fast must have an account-served variant with the normal request's other
329
+ // parameters intact. A fast variant at another context or effort is not enough.
330
+ export function supportsFast(raw, id, effort = "off") {
331
+ const entry = raw.find((model) => model.id === id)
332
+ if (!entry?.offersFast) return false
333
+ const normal = Object.fromEntries(pick(entry, effort, false).params.map((p) => [p.id, p.value]))
334
+ const quick = Object.fromEntries(pick(entry, effort, true).params.map((p) => [p.id, p.value]))
335
+ if (quick.fast !== "true" || Object.keys({ ...normal, ...quick }).some((key) => key !== "fast" && normal[key] !== quick[key])) return false
336
+ return entry.variants.some((variant) => {
337
+ const have = valuesOf(variant)
338
+ if (have.fast !== "true") return false
339
+ return Object.keys({ ...normal, ...have }).every((key) =>
340
+ key === "fast" || have[key] === normal[key],
341
+ )
342
+ })
343
+ }
344
+
320
345
  /** Pi chat-model configs. Cost stays zero: a subscription bill is not a token price. */
321
346
  export function piModelConfigs(raw) {
322
347
  return raw.map((m) => {
@@ -331,6 +356,7 @@ export function piModelConfigs(raw) {
331
356
  cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
332
357
  contextWindow: m.context || DEFAULT_CONTEXT,
333
358
  maxTokens: 32_000,
359
+ cursorFastLevels: PI_LEVELS.filter(([level]) => supportsFast(raw, m.id, level)).map(([level]) => level),
334
360
  }
335
361
  })
336
362
  }