@caph42/pi-cursor-provider 0.3.0 → 0.5.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/README.md +38 -0
- package/package.json +4 -2
- package/src/auth.ts +3 -18
- package/src/client.ts +4 -3
- package/src/config.ts +77 -0
- package/src/fast-autocomplete.ts +21 -0
- package/src/fast-footer.ts +83 -0
- package/src/fast.ts +156 -0
- package/src/index.ts +122 -33
- package/src/ledger.ts +2 -4
- package/src/models.ts +27 -4
- package/src/pi-stream.ts +12 -2
- package/src/run.ts +23 -14
- package/src/sleep.ts +29 -0
- package/src/usage.ts +32 -14
package/README.md
CHANGED
|
@@ -41,6 +41,44 @@ Then select a model:
|
|
|
41
41
|
/model cursor/<id>
|
|
42
42
|
```
|
|
43
43
|
|
|
44
|
+
## Hide models
|
|
45
|
+
|
|
46
|
+
`/model` lists every model Cursor offers the account. To shorten it, put `cursor.json` beside Pi's config (`$PI_CODING_AGENT_DIR/cursor.json`, else `~/.pi/agent/cursor.json`):
|
|
47
|
+
|
|
48
|
+
```json
|
|
49
|
+
{ "hiddenModels": ["claude-*", "gpt-5", "cursor/gpt-5-mini"] }
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
The extension registers a native Pi provider. Its synchronous model directory and availability filter read `cursor.json`, so local rules apply even when Cursor cannot refresh its remote catalogue. The availability filter also covers models added through `models.json`.
|
|
53
|
+
|
|
54
|
+
Successful discovery saves the complete catalogue in Pi's `models-store.json`. Startup and `/reload` restore that catalogue before applying the current hide rules; a session-start refresh discovers models when no cache exists. Offline mode restores the cache without fetching. A failed remote refresh keeps the previous catalogue, and a first-load failure is reported instead of silently returning an empty list.
|
|
55
|
+
|
|
56
|
+
A pattern matches the whole id `/model` shows (the part after `cursor/`), ignoring case. `*` stands for any run of characters; every other character, `?` included, is literal. A pattern without the `@300k` size suffix hides every context size of that model. A missing or malformed file hides nothing, and `/cursor.doctor` prints the patterns in force. Reopen `/model` and let its catalogue refresh finish to see the new list. After updating the extension itself, run `/reload` once. When developing from a checkout, configure that local path as the package source; `/reload` reloads configured sources and does not copy checkout changes into an npm installation.
|
|
57
|
+
|
|
58
|
+
Hidden models are removed from the live provider directory, so normal directory lookups no longer resolve their ids. A session already running on a hidden model keeps it; resuming one may require selecting another model. `/cursor.usage` still classifies usage by every model the account has.
|
|
59
|
+
|
|
60
|
+
Pi keeps a separate scoped model list (`/scoped-models`, `enabledModels`, or `--models`). Its picker can retain previously scoped model objects independently of the provider directory. If a hidden model still appears under **scoped**, remove it with `/scoped-models` and update any matching scope patterns. Provider filtering cannot remove those saved references through the public extension API.
|
|
61
|
+
|
|
62
|
+
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.
|
|
63
|
+
|
|
64
|
+
## Fast mode
|
|
65
|
+
|
|
66
|
+
Select a Cursor model, then use:
|
|
67
|
+
|
|
68
|
+
```text
|
|
69
|
+
/cursor.fast on
|
|
70
|
+
/cursor.fast status
|
|
71
|
+
/cursor.fast off
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
With no argument, `/cursor.fast` shows the current status. 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. You can still type `/cursor.fast status` explicitly to query the status. In the TUI, `fast: on`, `fast: off`, or `fast: unavailable` appears on the second footer row beside the model/thinking information. Other extension statuses retain their own row. 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.
|
|
75
|
+
|
|
76
|
+
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.
|
|
77
|
+
|
|
78
|
+
If fast is enabled and a later thinking change or catalogue update removes support, the footer shows `fast: on (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`.
|
|
79
|
+
|
|
80
|
+
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.
|
|
81
|
+
|
|
44
82
|
## How this relates to other Cursor packages
|
|
45
83
|
|
|
46
84
|
| Package | Role |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@caph42/pi-cursor-provider",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "Cursor provider for Pi: one HTTP/2 AgentService/Run per turn (magpie-aligned).",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -31,11 +31,13 @@
|
|
|
31
31
|
},
|
|
32
32
|
"peerDependencies": {
|
|
33
33
|
"@earendil-works/pi-ai": "*",
|
|
34
|
-
"@earendil-works/pi-coding-agent": "*"
|
|
34
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
35
|
+
"@earendil-works/pi-tui": "*"
|
|
35
36
|
},
|
|
36
37
|
"devDependencies": {
|
|
37
38
|
"@earendil-works/pi-ai": "1.4.0",
|
|
38
39
|
"@earendil-works/pi-coding-agent": "1.4.0",
|
|
40
|
+
"@earendil-works/pi-tui": "1.4.0",
|
|
39
41
|
"@types/node": "^22.20.5",
|
|
40
42
|
"typescript": "5.9"
|
|
41
43
|
},
|
package/src/auth.ts
CHANGED
|
@@ -15,6 +15,9 @@ import { join } from "node:path"
|
|
|
15
15
|
import type { OAuthCredentials, OAuthLoginCallbacks } from "@earendil-works/pi-ai"
|
|
16
16
|
import { readStoredCredential } from "@earendil-works/pi-coding-agent"
|
|
17
17
|
import { API, clientVersion } from "./client.ts"
|
|
18
|
+
import { sleep } from "./sleep.ts"
|
|
19
|
+
|
|
20
|
+
export { sleep }
|
|
18
21
|
|
|
19
22
|
const LOGIN_URL = "https://cursor.com/loginDeepControl"
|
|
20
23
|
const POLL_URL = `${API}/auth/poll`
|
|
@@ -60,24 +63,6 @@ export function expiresAt(token: string): number {
|
|
|
60
63
|
return Math.max(exp - 5 * 60 * 1000, Date.now() + 60 * 1000)
|
|
61
64
|
}
|
|
62
65
|
|
|
63
|
-
function sleep(ms: number, signal?: AbortSignal): Promise<void> {
|
|
64
|
-
return new Promise((resolve, reject) => {
|
|
65
|
-
if (signal?.aborted) {
|
|
66
|
-
reject(new Error("Cursor sign-in cancelled"))
|
|
67
|
-
return
|
|
68
|
-
}
|
|
69
|
-
const timer = setTimeout(resolve, ms)
|
|
70
|
-
signal?.addEventListener(
|
|
71
|
-
"abort",
|
|
72
|
-
() => {
|
|
73
|
-
clearTimeout(timer)
|
|
74
|
-
reject(new Error("Cursor sign-in cancelled"))
|
|
75
|
-
},
|
|
76
|
-
{ once: true },
|
|
77
|
-
)
|
|
78
|
-
})
|
|
79
|
-
}
|
|
80
|
-
|
|
81
66
|
function openBrowser(url: string) {
|
|
82
67
|
try {
|
|
83
68
|
const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open"
|
package/src/client.ts
CHANGED
|
@@ -71,13 +71,14 @@ export async function headersFor(tok) {
|
|
|
71
71
|
}
|
|
72
72
|
}
|
|
73
73
|
|
|
74
|
-
/** Connect unary call in JSON. */
|
|
75
|
-
export async function unary(base, path, tok, body = {}, timeout = 15_000) {
|
|
74
|
+
/** Connect unary call in JSON. `signal` aborts the request. `timeout` still does. */
|
|
75
|
+
export async function unary(base, path, tok, body = {}, timeout = 15_000, signal?: AbortSignal) {
|
|
76
|
+
const deadline = AbortSignal.timeout(timeout)
|
|
76
77
|
const res = await fetch(base + "/" + path, {
|
|
77
78
|
method: "POST",
|
|
78
79
|
headers: await headersFor(tok),
|
|
79
80
|
body: JSON.stringify(body),
|
|
80
|
-
signal: AbortSignal.
|
|
81
|
+
signal: signal ? AbortSignal.any([deadline, signal]) : deadline,
|
|
81
82
|
})
|
|
82
83
|
const text = await res.text()
|
|
83
84
|
if (!res.ok) {
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which Cursor models Pi's picker offers.
|
|
3
|
+
*
|
|
4
|
+
* Cursor lists every model (and every context size and effort of it) a
|
|
5
|
+
* subscription may use; that is long enough that the useful ones get lost in
|
|
6
|
+
* `/model`. `cursor.json` in Pi's config directory (`PI_CODING_AGENT_DIR`,
|
|
7
|
+
* else `~/.pi/agent`) names what to hide:
|
|
8
|
+
*
|
|
9
|
+
* { "hiddenModels": ["claude-*", "gpt-5", "cursor/gpt-5-mini"] }
|
|
10
|
+
*
|
|
11
|
+
* A pattern globs the id `/model` shows (the part after `cursor/`): `*` is any
|
|
12
|
+
* run of characters, everything else is literal, and the match ignores case.
|
|
13
|
+
* Hiding removes models from the live directory too: sessions already using a
|
|
14
|
+
* hidden model keep it, but resuming one may require selecting another model.
|
|
15
|
+
* A missing, unreadable or malformed file hides nothing.
|
|
16
|
+
*/
|
|
17
|
+
import { readFileSync } from "node:fs"
|
|
18
|
+
import { homedir } from "node:os"
|
|
19
|
+
import { join } from "node:path"
|
|
20
|
+
|
|
21
|
+
export const CONFIG_FILE = "cursor.json"
|
|
22
|
+
|
|
23
|
+
/** `cursor.json` beside the rest of Pi's config. */
|
|
24
|
+
export function configPath(env: NodeJS.ProcessEnv = process.env): string {
|
|
25
|
+
const dir = (env.PI_CODING_AGENT_DIR ?? "").trim()
|
|
26
|
+
return join(dir || join(homedir(), ".pi", "agent"), CONFIG_FILE)
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** `hiddenModels` as patterns: strings only, trimmed, empty ones dropped. */
|
|
30
|
+
function patternsOf(value: unknown): string[] {
|
|
31
|
+
if (!Array.isArray(value)) return []
|
|
32
|
+
return value.flatMap((v) => (typeof v === "string" && v.trim() ? [v.trim()] : []))
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The patterns in `cursor.json`. A file that is absent or not JSON hides nothing. */
|
|
36
|
+
export function hiddenPatterns(path: string = configPath()): string[] {
|
|
37
|
+
let text: string
|
|
38
|
+
try {
|
|
39
|
+
text = readFileSync(path, "utf8")
|
|
40
|
+
} catch {
|
|
41
|
+
return []
|
|
42
|
+
}
|
|
43
|
+
try {
|
|
44
|
+
const json: unknown = JSON.parse(text)
|
|
45
|
+
return patternsOf((json as { hiddenModels?: unknown } | null)?.hiddenModels)
|
|
46
|
+
} catch {
|
|
47
|
+
return []
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** A pattern as a regex: `*` any run, the rest literal (a `?` is a question mark, not a wildcard),
|
|
52
|
+
* the whole id, ignoring case. */
|
|
53
|
+
function globRe(pattern: string): RegExp {
|
|
54
|
+
const body = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*")
|
|
55
|
+
return new RegExp(`^${body}$`, "i")
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** A model id as /model spells it: no `cursor/` prefix. */
|
|
59
|
+
const bare = (id: string) => (id.startsWith("cursor/") ? id.slice("cursor/".length) : id)
|
|
60
|
+
|
|
61
|
+
/** Whether any pattern hides this model id. Both the id and the pattern may carry `cursor/`, and a
|
|
62
|
+
* pattern without the `@size` suffix hides every context size of that model. */
|
|
63
|
+
export function hidden(patterns: string[], id: string): boolean {
|
|
64
|
+
const name = bare(id)
|
|
65
|
+
const at = name.indexOf("@")
|
|
66
|
+
const family = at < 0 ? name : name.slice(0, at)
|
|
67
|
+
return patterns.some((p) => {
|
|
68
|
+
const re = globRe(bare(p))
|
|
69
|
+
return re.test(name) || re.test(family)
|
|
70
|
+
})
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** The models a pattern list keeps, in order. No patterns keeps all of them. */
|
|
74
|
+
export function visible<T extends { id: string }>(models: readonly T[], patterns: string[]): T[] {
|
|
75
|
+
if (!patterns.length) return [...models]
|
|
76
|
+
return models.filter((m) => !hidden(patterns, m.id))
|
|
77
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { AutocompleteProvider } from "@earendil-works/pi-tui"
|
|
2
|
+
|
|
3
|
+
/** Pi 1.4 routes Tab after slash-command arguments through file completion. */
|
|
4
|
+
export function cursorFastAutocomplete(current: AutocompleteProvider): AutocompleteProvider {
|
|
5
|
+
const argumentsAt = (lines: string[], line: number, col: number) =>
|
|
6
|
+
line === 0 && /^[ \t]*\/cursor\.fast +/.test((lines[line] ?? "").slice(0, col))
|
|
7
|
+
|
|
8
|
+
return {
|
|
9
|
+
triggerCharacters: current.triggerCharacters,
|
|
10
|
+
shouldTriggerFileCompletion(lines, line, col) {
|
|
11
|
+
if (argumentsAt(lines, line, col)) return true
|
|
12
|
+
return current.shouldTriggerFileCompletion?.(lines, line, col) ?? true
|
|
13
|
+
},
|
|
14
|
+
getSuggestions(lines, line, col, options) {
|
|
15
|
+
return current.getSuggestions(lines, line, col, argumentsAt(lines, line, col) ? { ...options, force: false } : options)
|
|
16
|
+
},
|
|
17
|
+
applyCompletion(lines, line, col, item, prefix) {
|
|
18
|
+
return current.applyCompletion(lines, line, col, item, prefix)
|
|
19
|
+
},
|
|
20
|
+
}
|
|
21
|
+
}
|
|
@@ -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,48 +6,135 @@
|
|
|
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
|
|
10
|
-
import type {
|
|
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"
|
|
14
|
+
import { configPath, hiddenPatterns, visible } from "./config.ts"
|
|
13
15
|
import { piModelConfigs, usable } from "./models.ts"
|
|
14
|
-
import {
|
|
16
|
+
import { registerCursorFast } from "./fast.ts"
|
|
15
17
|
import { fetchUsage, formatUsage } from "./usage.ts"
|
|
16
18
|
|
|
17
19
|
export { fetchUsage, formatUsage, onDemandOf } from "./usage.ts"
|
|
18
20
|
|
|
19
|
-
|
|
21
|
+
// One catalogue per credential: a refresh for one account must never serve
|
|
22
|
+
// its models to another.
|
|
23
|
+
const catalogs = new Map<string, Model<"cursor-run">[]>()
|
|
20
24
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
const fromCred =
|
|
24
|
-
ctx.credential?.type === "oauth" ? ctx.credential.access : ctx.credential?.type === "api_key" ? ctx.credential.key : undefined
|
|
25
|
-
const auth = await resolveAccessToken({ apiKey: fromCred })
|
|
26
|
-
if (!auth) return models
|
|
27
|
-
try {
|
|
28
|
-
models = piModelConfigs(await usable(auth.token, ctx.force === true)) as ProviderModelConfig[]
|
|
29
|
-
return models
|
|
30
|
-
} catch {
|
|
31
|
-
return models
|
|
32
|
-
}
|
|
25
|
+
function credentialKey(token: string): string {
|
|
26
|
+
return createHash("sha256").update(token).digest("hex")
|
|
33
27
|
}
|
|
34
28
|
|
|
29
|
+
|
|
35
30
|
export default function (pi: ExtensionAPI) {
|
|
36
|
-
|
|
31
|
+
// Keep the complete catalogue per registration. Local visibility rules must
|
|
32
|
+
// also run on synchronous reads, not only when a remote refresh completes.
|
|
33
|
+
let offered: Model<"cursor-run">[] = []
|
|
34
|
+
// Which credential produced `offered`; undefined when it came from Pi's cache
|
|
35
|
+
// alone, whose provenance this provider cannot see.
|
|
36
|
+
let offeredKey: string | undefined
|
|
37
|
+
const fast = registerCursorFast(pi)
|
|
38
|
+
const provider: Provider<"cursor-run"> = {
|
|
39
|
+
id: "cursor",
|
|
37
40
|
name: "Cursor",
|
|
38
41
|
baseUrl: AGENT,
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
models,
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
42
|
+
getModels: () => visible(offered, hiddenPatterns()),
|
|
43
|
+
// Pi applies this after models.json overlays, including user-added models.
|
|
44
|
+
filterModels: (models) => visible(models, hiddenPatterns()),
|
|
45
|
+
auth: {
|
|
46
|
+
apiKey: {
|
|
47
|
+
name: "Cursor access token",
|
|
48
|
+
resolve: async ({ ctx, credential }) => {
|
|
49
|
+
const auth = await resolveAccessToken({
|
|
50
|
+
apiKey: credential?.key,
|
|
51
|
+
env: { CURSOR_ACCESS_TOKEN: await ctx.env("CURSOR_ACCESS_TOKEN") },
|
|
52
|
+
})
|
|
53
|
+
return auth ? { auth: { apiKey: auth.token }, source: auth.source } : undefined
|
|
54
|
+
},
|
|
55
|
+
},
|
|
56
|
+
oauth: {
|
|
57
|
+
name: "Cursor",
|
|
58
|
+
isSubscription: true,
|
|
59
|
+
login: async (interaction) => ({
|
|
60
|
+
...(await login({
|
|
61
|
+
onAuth: (info) => interaction.notify({ type: "auth_url", ...info }),
|
|
62
|
+
onDeviceCode: (info) => interaction.notify({ type: "device_code", ...info }),
|
|
63
|
+
onSelect: (prompt) => interaction.prompt({ type: "select", ...prompt }),
|
|
64
|
+
onPrompt: (prompt) => interaction.prompt({ type: "text", ...prompt }),
|
|
65
|
+
onProgress: (message) => interaction.notify({ type: "progress", message }),
|
|
66
|
+
signal: interaction.signal,
|
|
67
|
+
})),
|
|
68
|
+
type: "oauth",
|
|
69
|
+
}),
|
|
70
|
+
refresh: async (credential, signal) => ({ ...(await refresh(credential, signal)), type: "oauth" }),
|
|
71
|
+
toAuth: async (credential) => ({ apiKey: credential.access }),
|
|
72
|
+
},
|
|
73
|
+
},
|
|
74
|
+
refreshModels: async (ctx) => {
|
|
75
|
+
if (ctx.signal.aborted) return
|
|
76
|
+
// Pi initializes and reloads extensions without network access. Restore
|
|
77
|
+
// the unfiltered catalogue before that phase returns, including when a
|
|
78
|
+
// subsequent network refresh fails or is cancelled.
|
|
79
|
+
if (!offered.length && ctx.stored) {
|
|
80
|
+
const cached = ctx.stored.models.filter((model): model is Model<"cursor-run"> =>
|
|
81
|
+
model.provider === "cursor" && model.api === "cursor-run" && (model.type === undefined || model.type === "chat"),
|
|
82
|
+
)
|
|
83
|
+
if (cached.length) await ctx.publish({ update: () => { offered = cached; offeredKey = undefined; fast.catalogueChanged() } })
|
|
84
|
+
}
|
|
85
|
+
const hinted = ctx.credential?.type === "oauth" ? ctx.credential.access : ctx.credential?.type === "api_key" ? ctx.credential.key : undefined
|
|
86
|
+
const auth = ctx.signal.aborted ? undefined : await resolveAccessToken({ apiKey: hinted })
|
|
87
|
+
if (ctx.signal.aborted) return
|
|
88
|
+
const token = auth?.token ?? hinted
|
|
89
|
+
// Serve the catalogue this credential already discovered, without the
|
|
90
|
+
// network, so an offline reload does not look like a signed-out account.
|
|
91
|
+
const kept = token ? catalogs.get(credentialKey(token)) : undefined
|
|
92
|
+
if (!ctx.allowNetwork || !auth) {
|
|
93
|
+
if (kept?.length) {
|
|
94
|
+
await ctx.publish({ update: () => { offered = kept; offeredKey = token ? credentialKey(token) : undefined; fast.catalogueChanged() } })
|
|
95
|
+
}
|
|
96
|
+
return
|
|
97
|
+
}
|
|
98
|
+
const key = credentialKey(auth.token)
|
|
99
|
+
try {
|
|
100
|
+
const next = piModelConfigs(await usable(auth.token, ctx.force === true, ctx.signal)).map((model: Model<"cursor-run">) => ({
|
|
101
|
+
...model,
|
|
102
|
+
provider: "cursor",
|
|
103
|
+
baseUrl: AGENT,
|
|
104
|
+
})) as Model<"cursor-run">[]
|
|
105
|
+
if (ctx.signal.aborted) return
|
|
106
|
+
catalogs.set(key, next)
|
|
107
|
+
await ctx.publish({
|
|
108
|
+
persist: { models: next, checkedAt: Date.now() },
|
|
109
|
+
update: () => { offered = next; offeredKey = key; fast.catalogueChanged() },
|
|
110
|
+
})
|
|
111
|
+
} catch (error) {
|
|
112
|
+
// Never keep another credential's catalogue after a failed refresh: fall
|
|
113
|
+
// back to what this one discovered, even if that is nothing.
|
|
114
|
+
const unknownSource = offeredKey === undefined
|
|
115
|
+
const previous = catalogs.get(key) ?? []
|
|
116
|
+
await ctx.publish({ update: () => { offered = previous; offeredKey = key; fast.catalogueChanged() } })
|
|
117
|
+
// Surface a first-load failure instead of reporting an empty provider as
|
|
118
|
+
// a successful refresh.
|
|
119
|
+
if (!previous.length && unknownSource) throw error
|
|
120
|
+
}
|
|
48
121
|
},
|
|
49
|
-
|
|
50
|
-
streamSimple:
|
|
122
|
+
stream: fast.stream,
|
|
123
|
+
streamSimple: fast.stream,
|
|
124
|
+
}
|
|
125
|
+
pi.registerProvider(provider)
|
|
126
|
+
|
|
127
|
+
// Startup and /reload restore cached models first. Discover the catalogue
|
|
128
|
+
// for a first install too, once the host has bound credentials and context.
|
|
129
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
130
|
+
const result = await ctx.modelRegistry.refresh({
|
|
131
|
+
providers: ["cursor"],
|
|
132
|
+
allowNetwork: process.env.PI_OFFLINE === undefined,
|
|
133
|
+
signal: AbortSignal.timeout(15_000),
|
|
134
|
+
})
|
|
135
|
+
fast.updateStatus(ctx)
|
|
136
|
+
const error = result.errors.get("cursor")
|
|
137
|
+
if (error && ctx.hasUI) ctx.ui.notify(`Cursor model catalogue: ${error.message}`, "warning")
|
|
51
138
|
})
|
|
52
139
|
|
|
53
140
|
pi.registerCommand("cursor.doctor", {
|
|
@@ -56,11 +143,13 @@ export default function (pi: ExtensionAPI) {
|
|
|
56
143
|
const extra = args.trim() ? " This command does not take arguments." : ""
|
|
57
144
|
const auth = await resolveAccessToken()
|
|
58
145
|
const version = await clientVersion()
|
|
146
|
+
const patterns = hiddenPatterns()
|
|
147
|
+
const hiddenText = patterns.length ? `Hidden from /model: ${patterns.join(", ")} (${configPath()}).` : `No models hidden (${configPath()}).`
|
|
59
148
|
if (!auth) {
|
|
60
|
-
ctx.ui.notify(`Cursor is not signed in (${version}). Run /login cursor or set CURSOR_ACCESS_TOKEN
|
|
149
|
+
ctx.ui.notify(`Cursor is not signed in (${version}). Run /login cursor or set CURSOR_ACCESS_TOKEN. ${hiddenText}${extra}`, "warning")
|
|
61
150
|
return
|
|
62
151
|
}
|
|
63
|
-
ctx.ui.notify(`Cursor auth source: ${auth.source}. Client ${version}. Token not shown.${extra}`, "info")
|
|
152
|
+
ctx.ui.notify(`Cursor auth source: ${auth.source}. Client ${version}. ${hiddenText} Token not shown.${extra}`, "info")
|
|
64
153
|
},
|
|
65
154
|
})
|
|
66
155
|
|
|
@@ -74,16 +163,16 @@ export default function (pi: ExtensionAPI) {
|
|
|
74
163
|
ctx.ui.notify(`Cursor is not signed in (${version}). Run /login cursor or set CURSOR_ACCESS_TOKEN.${extra}`, "warning")
|
|
75
164
|
return
|
|
76
165
|
}
|
|
77
|
-
let ids =
|
|
166
|
+
let ids = (catalogs.get(credentialKey(auth.token)) ?? offered).map((m) => m.id)
|
|
78
167
|
if (!ids.length) {
|
|
79
168
|
try {
|
|
80
|
-
ids = (await usable(auth.token)).map((m: { id: string }) => m.id)
|
|
169
|
+
ids = (await usable(auth.token, false, ctx.signal)).map((m: { id: string }) => m.id)
|
|
81
170
|
} catch {
|
|
82
171
|
ids = []
|
|
83
172
|
}
|
|
84
173
|
}
|
|
85
174
|
try {
|
|
86
|
-
const report = await fetchUsage(auth.token, ids)
|
|
175
|
+
const report = await fetchUsage(auth.token, ids, ctx.signal)
|
|
87
176
|
ctx.ui.notify(formatUsage(report) + extra, report.error ? "warning" : "info")
|
|
88
177
|
} catch (e) {
|
|
89
178
|
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,7 @@
|
|
|
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"
|
|
15
16
|
|
|
16
17
|
// STEP_WAIT is how long a step's event is looked for: first after that long,
|
|
17
18
|
// then every so often until the end (each ask given `ask` to answer).
|
|
@@ -117,10 +118,7 @@ export function owe(key, { since = Date.now(), n = 0, ready = Date.now(), carry
|
|
|
117
118
|
export async function usageEvents(tok, conv, since, want, { poll = false, first = STEP_WAIT.first, signal, before = () => Infinity, groups, abortFetch = false } = {}) {
|
|
118
119
|
const key = usageKey(tok, conv)
|
|
119
120
|
const end = Date.now() + STEP_WAIT.until
|
|
120
|
-
const wait = (ms) =>
|
|
121
|
-
const t = setTimeout(r, ms)
|
|
122
|
-
signal?.addEventListener("abort", () => (clearTimeout(t), r()), { once: true })
|
|
123
|
-
})
|
|
121
|
+
const wait = (ms) => sleep(ms, signal, "resolve")
|
|
124
122
|
for (const [k, at] of claimed) if (Date.now() - at > 2 * STEP_WAIT.owedFor) claimed.delete(k)
|
|
125
123
|
const num = (v) => (Number.isFinite(Number(v)) ? Number(v) : 0)
|
|
126
124
|
let usage = null
|
package/src/models.ts
CHANGED
|
@@ -241,20 +241,25 @@ 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) {
|
|
244
|
+
export async function usable(tok, force = false, signal?: AbortSignal) {
|
|
245
|
+
if (signal?.aborted) throw Object.assign(new Error("The operation was aborted"), { name: "AbortError" })
|
|
245
246
|
const h = createHash("sha256").update(tok).digest("hex")
|
|
246
247
|
const had = lists.get(h)
|
|
247
248
|
if (!force && had && Date.now() - had.at < MODELS_KEEP) return had.raw
|
|
248
249
|
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(
|
|
250
|
+
unary(API, "aiserver.v1.AiService/AvailableModels", tok, { useModelParameters: true, doNotUseMarkdown: true }, 30_000, signal),
|
|
251
|
+
unary(API, "agent.v1.AgentService/GetUsableModels", tok, {}, 8_000, signal).then(
|
|
251
252
|
(u) => {
|
|
252
253
|
const ids = new Set((u?.models ?? []).flatMap((m) => [m.modelId, m.displayModelId]).filter(Boolean))
|
|
253
254
|
return ids.size ? ids : null
|
|
254
255
|
},
|
|
255
|
-
() =>
|
|
256
|
+
(err) => {
|
|
257
|
+
if (signal?.aborted) throw err
|
|
258
|
+
return null
|
|
259
|
+
},
|
|
256
260
|
),
|
|
257
261
|
])
|
|
262
|
+
if (signal?.aborted) throw Object.assign(new Error("The operation was aborted"), { name: "AbortError" })
|
|
258
263
|
const raw = modelsOf(Array.isArray(j?.models) ? j.models : [], ids)
|
|
259
264
|
if (!raw.length) throw new Error("Cursor listed no models")
|
|
260
265
|
lists.set(h, { at: Date.now(), raw })
|
|
@@ -317,6 +322,23 @@ function thinkingLevelMap(levels) {
|
|
|
317
322
|
return map
|
|
318
323
|
}
|
|
319
324
|
|
|
325
|
+
// Fast must have an account-served variant with the normal request's other
|
|
326
|
+
// parameters intact. A fast variant at another context or effort is not enough.
|
|
327
|
+
export function supportsFast(raw, id, effort = "off") {
|
|
328
|
+
const entry = raw.find((model) => model.id === id)
|
|
329
|
+
if (!entry?.offersFast) return false
|
|
330
|
+
const normal = Object.fromEntries(pick(entry, effort, false).params.map((p) => [p.id, p.value]))
|
|
331
|
+
const quick = Object.fromEntries(pick(entry, effort, true).params.map((p) => [p.id, p.value]))
|
|
332
|
+
if (quick.fast !== "true" || Object.keys({ ...normal, ...quick }).some((key) => key !== "fast" && normal[key] !== quick[key])) return false
|
|
333
|
+
return entry.variants.some((variant) => {
|
|
334
|
+
const have = valuesOf(variant)
|
|
335
|
+
if (have.fast !== "true") return false
|
|
336
|
+
return Object.keys({ ...normal, ...have }).every((key) =>
|
|
337
|
+
key === "fast" || have[key] === normal[key],
|
|
338
|
+
)
|
|
339
|
+
})
|
|
340
|
+
}
|
|
341
|
+
|
|
320
342
|
/** Pi chat-model configs. Cost stays zero: a subscription bill is not a token price. */
|
|
321
343
|
export function piModelConfigs(raw) {
|
|
322
344
|
return raw.map((m) => {
|
|
@@ -331,6 +353,7 @@ export function piModelConfigs(raw) {
|
|
|
331
353
|
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
332
354
|
contextWindow: m.context || DEFAULT_CONTEXT,
|
|
333
355
|
maxTokens: 32_000,
|
|
356
|
+
cursorFastLevels: PI_LEVELS.filter(([level]) => supportsFast(raw, m.id, level)).map(([level]) => level),
|
|
334
357
|
}
|
|
335
358
|
})
|
|
336
359
|
}
|
package/src/pi-stream.ts
CHANGED
|
@@ -29,6 +29,11 @@ import type {
|
|
|
29
29
|
} from "@earendil-works/pi-ai"
|
|
30
30
|
import { resolveAccessToken } from "./auth.ts"
|
|
31
31
|
import { runAnswer } from "./run.ts"
|
|
32
|
+
import { supportsFast, usable } from "./models.ts"
|
|
33
|
+
|
|
34
|
+
export interface CursorStreamOptions extends SimpleStreamOptions {
|
|
35
|
+
fast?: boolean
|
|
36
|
+
}
|
|
32
37
|
|
|
33
38
|
/** Shown when no Cursor credential is available. */
|
|
34
39
|
export const CURSOR_NOT_SIGNED_IN = "Cursor isn't signed in. Run /login cursor or set CURSOR_ACCESS_TOKEN."
|
|
@@ -269,7 +274,7 @@ export async function emitCursorEvents(
|
|
|
269
274
|
export function streamCursor(
|
|
270
275
|
model: Model<Api>,
|
|
271
276
|
context: TranscriptContext,
|
|
272
|
-
options?:
|
|
277
|
+
options?: CursorStreamOptions,
|
|
273
278
|
): AssistantMessageEventStream {
|
|
274
279
|
const stream = createAssistantMessageEventStream()
|
|
275
280
|
void pump(stream, model, context, options)
|
|
@@ -280,7 +285,7 @@ async function pump(
|
|
|
280
285
|
stream: AssistantMessageEventStream,
|
|
281
286
|
model: Model<Api>,
|
|
282
287
|
context: TranscriptContext,
|
|
283
|
-
options?:
|
|
288
|
+
options?: CursorStreamOptions,
|
|
284
289
|
) {
|
|
285
290
|
const message = blank(model)
|
|
286
291
|
const fail = (reason: Extract<StopReason, "error" | "aborted">, text: string) => {
|
|
@@ -298,12 +303,17 @@ async function pump(
|
|
|
298
303
|
fail("error", CURSOR_NOT_SIGNED_IN)
|
|
299
304
|
return
|
|
300
305
|
}
|
|
306
|
+
if (options?.fast && !supportsFast(await usable(auth.token), model.id, options.reasoning ?? "off")) {
|
|
307
|
+
fail("error", `Cursor fast is enabled but unavailable for ${model.id} at thinking ${options.reasoning ?? "off"}. Use /cursor.fast off or choose a supported thinking level.`)
|
|
308
|
+
return
|
|
309
|
+
}
|
|
301
310
|
const piTools = options?.toolChoice === "none" ? [] : getCurrentTools(context.messages)
|
|
302
311
|
const system = getCurrentSystemPrompt(context.messages)
|
|
303
312
|
const ran = await runAnswer({
|
|
304
313
|
tok: auth.token,
|
|
305
314
|
model: model.id,
|
|
306
315
|
effort: options?.reasoning ?? "",
|
|
316
|
+
fast: options?.fast,
|
|
307
317
|
messages: toChat(context.messages, system),
|
|
308
318
|
tools: piTools.map((tool) => ({
|
|
309
319
|
name: tool.name,
|
package/src/run.ts
CHANGED
|
@@ -85,8 +85,12 @@ function toolsOf(chat) {
|
|
|
85
85
|
// those calls went nowhere (#11).
|
|
86
86
|
function catalog(tools) {
|
|
87
87
|
if (!tools.length) return ""
|
|
88
|
+
const visible = (value) => String(value ?? "").replaceAll("<", "\\u003c")
|
|
88
89
|
let s = `\n\n<dynamic_tool_catalog>\nThe MCP namespace "pi" has the tools below. They are reached only through \`${CALL}\`, never as tools of their own. Each entry is the exact call to make; its arguments must match the schema given. The schemas are complete, so there is no need to call \`GetDynamicTools\` first.\n`
|
|
89
|
-
for (const t of tools)
|
|
90
|
+
for (const t of tools) {
|
|
91
|
+
const name = JSON.stringify(String(t.name ?? "")).replaceAll("<", "\\u003c")
|
|
92
|
+
s += `<call>${CALL}({"namespace":"${NAMESPACE}","toolName":${name},"arguments":{...}})\n${visible(t.description)}\narguments schema: ${visible(t.schemaText)}\n</call>\n`
|
|
93
|
+
}
|
|
90
94
|
return s + "</dynamic_tool_catalog>"
|
|
91
95
|
}
|
|
92
96
|
|
|
@@ -293,14 +297,14 @@ function buildRun(msgs, lastUser, tools, model, conv = "", { maxMode = false, pa
|
|
|
293
297
|
// while it can't be had.
|
|
294
298
|
|
|
295
299
|
const endpoints = new Map()
|
|
296
|
-
export async function agentURL(tok, fresh) {
|
|
300
|
+
export async function agentURL(tok, fresh, signal?: AbortSignal) {
|
|
297
301
|
const key = createHash("sha256").update(tok).digest("hex")
|
|
298
302
|
const had = endpoints.get(key)
|
|
299
303
|
if (!fresh && had && (had.listed || Date.now() - had.at < 60_000)) return had.url
|
|
300
304
|
let url = AGENT
|
|
301
305
|
let listed = false
|
|
302
306
|
try {
|
|
303
|
-
const cfg = await unary(API, "aiserver.v1.ServerConfigService/GetServerConfig", tok, {}, 10_000)
|
|
307
|
+
const cfg = await unary(API, "aiserver.v1.ServerConfigService/GetServerConfig", tok, {}, 10_000, signal)
|
|
304
308
|
for (const raw of [cfg?.agentUrlConfig?.agentUrl, cfg?.agentUrlConfig?.agentnUrl]) {
|
|
305
309
|
try {
|
|
306
310
|
const u = new URL(raw)
|
|
@@ -311,7 +315,10 @@ export async function agentURL(tok, fresh) {
|
|
|
311
315
|
}
|
|
312
316
|
} catch {}
|
|
313
317
|
}
|
|
314
|
-
} catch {
|
|
318
|
+
} catch (e) {
|
|
319
|
+
if (signal?.aborted) throw e
|
|
320
|
+
}
|
|
321
|
+
if (signal?.aborted) throw Object.assign(new Error("The operation was aborted"), { name: "AbortError" })
|
|
315
322
|
// A refresh that learns nothing must not replace a regional URL with the global one.
|
|
316
323
|
if (!listed && fresh && had?.url) return had.url
|
|
317
324
|
endpoints.set(key, { url, at: Date.now(), listed })
|
|
@@ -330,9 +337,9 @@ export function clearAgentCache() {
|
|
|
330
337
|
// connection that failed (refused, no network) or a stream the server
|
|
331
338
|
// refused leaves the next Run to try HTTP/2 again.
|
|
332
339
|
//
|
|
333
|
-
// Tests may inject `connect`; that path stays HTTP/2-only
|
|
340
|
+
// Tests may inject `connect`; that path stays HTTP/2-only. Both paths wait
|
|
341
|
+
// headerWaitMs for response headers. The default is H2.wait.
|
|
334
342
|
let h1Until = 0
|
|
335
|
-
const HEADER_WAIT_MS = 30_000
|
|
336
343
|
const H2 = {
|
|
337
344
|
wait: 15_000,
|
|
338
345
|
retryAfter: 10 * 60_000,
|
|
@@ -508,14 +515,14 @@ function openH1(headers, signal) {
|
|
|
508
515
|
return Promise.resolve(signal?.aborted ? cancelledOpen() : { session: { close, destroy: close }, req: Object.assign(req, { close }), status: 200, h1: true, headers: {} })
|
|
509
516
|
}
|
|
510
517
|
|
|
511
|
-
async function open(base, headers, signal, connect = defaultConnect, headerWaitMs =
|
|
518
|
+
async function open(base, headers, signal, connect = defaultConnect, headerWaitMs = H2.wait) {
|
|
512
519
|
if (signal?.aborted) return cancelledOpen()
|
|
513
520
|
// Injected connect (tests): HTTP/2 only, keep the caller's header wait.
|
|
514
521
|
if (connect !== defaultConnect) {
|
|
515
522
|
return openH2(base, headers, signal, connect, headerWaitMs)
|
|
516
523
|
}
|
|
517
524
|
if (Date.now() >= h1Until) {
|
|
518
|
-
const o = await openH2(base, headers, signal, defaultConnect,
|
|
525
|
+
const o = await openH2(base, headers, signal, defaultConnect, headerWaitMs)
|
|
519
526
|
if (signal?.aborted) {
|
|
520
527
|
try { o.req?.close?.(http2.constants.NGHTTP2_CANCEL) } catch {}
|
|
521
528
|
try { o.session?.destroy?.() } catch {}
|
|
@@ -1166,7 +1173,7 @@ export async function runAnswer({
|
|
|
1166
1173
|
onResponse,
|
|
1167
1174
|
onPayload,
|
|
1168
1175
|
headers,
|
|
1169
|
-
headerWaitMs =
|
|
1176
|
+
headerWaitMs = H2.wait,
|
|
1170
1177
|
toolIdleMs = TOOL_IDLE_MS,
|
|
1171
1178
|
}: {
|
|
1172
1179
|
tok: string
|
|
@@ -1178,7 +1185,7 @@ export async function runAnswer({
|
|
|
1178
1185
|
session?: string
|
|
1179
1186
|
signal?: AbortSignal
|
|
1180
1187
|
connect?: (origin: string) => unknown
|
|
1181
|
-
resolveAgentURL?: (tok: string, fresh: boolean) => Promise<string> | string
|
|
1188
|
+
resolveAgentURL?: (tok: string, fresh: boolean, signal?: AbortSignal) => Promise<string> | string
|
|
1182
1189
|
rawModels?: unknown
|
|
1183
1190
|
onResponse?: (response: { status: number; headers: Record<string, string> }) => unknown
|
|
1184
1191
|
onPayload?: (payload: unknown) => unknown
|
|
@@ -1231,7 +1238,7 @@ export async function runAnswer({
|
|
|
1231
1238
|
let raw = rawModels
|
|
1232
1239
|
if (raw === undefined) {
|
|
1233
1240
|
try {
|
|
1234
|
-
raw = await usable(tok)
|
|
1241
|
+
raw = await usable(tok, false, signal)
|
|
1235
1242
|
} catch {
|
|
1236
1243
|
raw = []
|
|
1237
1244
|
}
|
|
@@ -1241,7 +1248,7 @@ export async function runAnswer({
|
|
|
1241
1248
|
let params = resolved.params
|
|
1242
1249
|
let maxMode = resolved.maxMode || maxOnly.has(id)
|
|
1243
1250
|
const conv = conversation(chat, listed)
|
|
1244
|
-
let base = await resolveAgentURL(tok, false)
|
|
1251
|
+
let base = await resolveAgentURL(tok, false, signal)
|
|
1245
1252
|
const once = async () => {
|
|
1246
1253
|
const native = prepared.fallback ? null : nativeSessions.create(prepared, { id, maxMode, params }, { pb, exec, usageOf, failure })
|
|
1247
1254
|
const args = { tok, base, id, tools: listed, conv, convID, signal, maxMode, params, connect, onResponse, onPayload, headers, headerWaitMs, toolIdleMs }
|
|
@@ -1250,15 +1257,17 @@ export async function runAnswer({
|
|
|
1250
1257
|
return response
|
|
1251
1258
|
}
|
|
1252
1259
|
let ran = await once()
|
|
1260
|
+
if (signal?.aborted) return ran
|
|
1253
1261
|
if (ran.error && regional(ran.error.message)) {
|
|
1254
1262
|
resetH1()
|
|
1255
|
-
const fresh = await resolveAgentURL(tok, true)
|
|
1263
|
+
const fresh = await resolveAgentURL(tok, true, signal)
|
|
1256
1264
|
const viaH1 = !!ran.h1
|
|
1257
|
-
if (fresh !== base || viaH1) {
|
|
1265
|
+
if ((fresh !== base || viaH1) && !signal?.aborted) {
|
|
1258
1266
|
base = fresh
|
|
1259
1267
|
ran = await once()
|
|
1260
1268
|
}
|
|
1261
1269
|
}
|
|
1270
|
+
if (signal?.aborted) return ran
|
|
1262
1271
|
if (ran.error && !maxMode && maxRequired(ran.error.message)) {
|
|
1263
1272
|
maxMode = true
|
|
1264
1273
|
maxOnly.add(id)
|
package/src/sleep.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
const CANCELLED = "Cursor sign-in cancelled"
|
|
2
|
+
|
|
3
|
+
export function sleep(
|
|
4
|
+
ms: number,
|
|
5
|
+
signal?: AbortSignal,
|
|
6
|
+
onAbort: "reject" | "resolve" = "reject",
|
|
7
|
+
): Promise<void> {
|
|
8
|
+
return new Promise((resolve, reject) => {
|
|
9
|
+
const cancel = () => {
|
|
10
|
+
if (onAbort === "resolve") resolve()
|
|
11
|
+
else reject(new Error(CANCELLED))
|
|
12
|
+
}
|
|
13
|
+
if (signal?.aborted) {
|
|
14
|
+
cancel()
|
|
15
|
+
return
|
|
16
|
+
}
|
|
17
|
+
let settled = false
|
|
18
|
+
const finish = (fn: () => void) => {
|
|
19
|
+
if (settled) return
|
|
20
|
+
settled = true
|
|
21
|
+
clearTimeout(timer)
|
|
22
|
+
signal?.removeEventListener("abort", abort)
|
|
23
|
+
fn()
|
|
24
|
+
}
|
|
25
|
+
const abort = () => finish(cancel)
|
|
26
|
+
const timer = setTimeout(() => finish(resolve), ms)
|
|
27
|
+
signal?.addEventListener("abort", abort)
|
|
28
|
+
})
|
|
29
|
+
}
|
package/src/usage.ts
CHANGED
|
@@ -15,6 +15,15 @@ export const WEBSITE = "https://cursor.com"
|
|
|
15
15
|
const PLAN_TTL = 3600_000
|
|
16
16
|
const plans = new Map<string, { plan: string; at: number }>()
|
|
17
17
|
|
|
18
|
+
function until(ms: number, signal?: AbortSignal): AbortSignal {
|
|
19
|
+
const deadline = AbortSignal.timeout(ms)
|
|
20
|
+
return signal ? AbortSignal.any([deadline, signal]) : deadline
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function cancelled(signal: AbortSignal | undefined, err: unknown): boolean {
|
|
24
|
+
return signal?.aborted === true || (err instanceof Error && err.name === "AbortError")
|
|
25
|
+
}
|
|
26
|
+
|
|
18
27
|
export type UsageWindow = {
|
|
19
28
|
name: string
|
|
20
29
|
used: number
|
|
@@ -102,31 +111,32 @@ export function onDemandOf(data: { spendLimitUsage?: Spend } | undefined, hard:
|
|
|
102
111
|
return limit > 0 ? { kind: "fixed", usedDollars, limitDollars: limit } : { kind: "disabled", usedDollars }
|
|
103
112
|
}
|
|
104
113
|
|
|
105
|
-
async function hardLimit(tok: string): Promise<HardLimit | undefined> {
|
|
114
|
+
async function hardLimit(tok: string, signal?: AbortSignal): Promise<HardLimit | undefined> {
|
|
106
115
|
try {
|
|
107
116
|
const res = await fetch(API + "/aiserver.v1.DashboardService/GetHardLimit", {
|
|
108
117
|
method: "POST",
|
|
109
118
|
headers: { Authorization: `Bearer ${tok}`, "Content-Type": "application/json", "Connect-Protocol-Version": "1" },
|
|
110
119
|
body: "{}",
|
|
111
|
-
signal:
|
|
120
|
+
signal: until(15_000, signal),
|
|
112
121
|
})
|
|
113
122
|
return res.ok ? ((await res.json()) ?? undefined) : undefined
|
|
114
|
-
} catch {
|
|
123
|
+
} catch (err) {
|
|
124
|
+
if (cancelled(signal, err)) throw err
|
|
115
125
|
return undefined
|
|
116
126
|
}
|
|
117
127
|
}
|
|
118
128
|
|
|
119
129
|
const dollars = (n: number) => "$" + n.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })
|
|
120
130
|
|
|
121
|
-
async function periodUsage(tok: string, ids: string[]): Promise<UsageReport> {
|
|
131
|
+
async function periodUsage(tok: string, ids: string[], signal?: AbortSignal): Promise<UsageReport> {
|
|
122
132
|
const [res, hard] = await Promise.all([
|
|
123
133
|
fetch(API + "/aiserver.v1.DashboardService/GetCurrentPeriodUsage", {
|
|
124
134
|
method: "POST",
|
|
125
135
|
headers: { Authorization: `Bearer ${tok}`, "Content-Type": "application/json", "Connect-Protocol-Version": "1" },
|
|
126
136
|
body: "{}",
|
|
127
|
-
signal:
|
|
137
|
+
signal: until(15_000, signal),
|
|
128
138
|
}),
|
|
129
|
-
hardLimit(tok),
|
|
139
|
+
hardLimit(tok, signal),
|
|
130
140
|
])
|
|
131
141
|
if (!res.ok) return { error: statusText(res.status), windows: [] }
|
|
132
142
|
const data = (await res.json()) as Period
|
|
@@ -168,20 +178,22 @@ async function periodUsage(tok: string, ids: string[]): Promise<UsageReport> {
|
|
|
168
178
|
}
|
|
169
179
|
}
|
|
170
180
|
|
|
171
|
-
async function planOf(tok: string): Promise<string> {
|
|
181
|
+
async function planOf(tok: string, signal?: AbortSignal): Promise<string> {
|
|
172
182
|
const had = plans.get(tok)
|
|
173
183
|
if (had && Date.now() - had.at < PLAN_TTL) return had.plan
|
|
174
184
|
try {
|
|
175
|
-
const body = await unary(API, "aiserver.v1.DashboardService/GetPlanInfo", tok)
|
|
185
|
+
const body = await unary(API, "aiserver.v1.DashboardService/GetPlanInfo", tok, {}, 15_000, signal)
|
|
186
|
+
if (signal?.aborted) throw Object.assign(new Error("The operation was aborted"), { name: "AbortError" })
|
|
176
187
|
const plan = String(body?.planInfo?.planName ?? "").trim()
|
|
177
188
|
if (plan) plans.set(tok, { plan, at: Date.now() })
|
|
178
189
|
return plan || had?.plan || ""
|
|
179
|
-
} catch {
|
|
190
|
+
} catch (err) {
|
|
191
|
+
if (cancelled(signal, err)) throw err
|
|
180
192
|
return had?.plan ?? ""
|
|
181
193
|
}
|
|
182
194
|
}
|
|
183
195
|
|
|
184
|
-
async function botUsage(tok: string): Promise<UsageWindow[]> {
|
|
196
|
+
async function botUsage(tok: string, signal?: AbortSignal): Promise<UsageWindow[]> {
|
|
185
197
|
try {
|
|
186
198
|
const subject = JSON.parse(Buffer.from(tok.split(".")[1] ?? "", "base64url").toString()).sub
|
|
187
199
|
if (typeof subject !== "string") return []
|
|
@@ -197,8 +209,9 @@ async function botUsage(tok: string): Promise<UsageWindow[]> {
|
|
|
197
209
|
},
|
|
198
210
|
body: "{}",
|
|
199
211
|
redirect: "error",
|
|
200
|
-
signal:
|
|
212
|
+
signal: until(5_000, signal),
|
|
201
213
|
})
|
|
214
|
+
if (signal?.aborted) throw Object.assign(new Error("The operation was aborted"), { name: "AbortError" })
|
|
202
215
|
if (!res.ok) return []
|
|
203
216
|
const data = (await res.json()) as {
|
|
204
217
|
includedLimitZero?: boolean
|
|
@@ -219,14 +232,19 @@ async function botUsage(tok: string): Promise<UsageWindow[]> {
|
|
|
219
232
|
...(Number.isFinite(reset) ? { resetsAt: new Date(reset).toISOString(), span: 604800 } : {}),
|
|
220
233
|
},
|
|
221
234
|
]
|
|
222
|
-
} catch {
|
|
235
|
+
} catch (err) {
|
|
236
|
+
if (cancelled(signal, err)) throw err
|
|
223
237
|
return []
|
|
224
238
|
}
|
|
225
239
|
}
|
|
226
240
|
|
|
227
241
|
/** Plan name plus the billing-period windows. GetPlanInfo is cached for about an hour per token. */
|
|
228
|
-
export async function fetchUsage(tok: string, modelIds: string[]): Promise<UsageReport> {
|
|
229
|
-
const [u, plan, bot] = await Promise.all([
|
|
242
|
+
export async function fetchUsage(tok: string, modelIds: string[], signal?: AbortSignal): Promise<UsageReport> {
|
|
243
|
+
const [u, plan, bot] = await Promise.all([
|
|
244
|
+
periodUsage(tok, modelIds, signal),
|
|
245
|
+
planOf(tok, signal),
|
|
246
|
+
botUsage(tok, signal),
|
|
247
|
+
])
|
|
230
248
|
const last = (w: UsageWindow) => w.name === "Total" || (w.name === "On-demand" && w.aside)
|
|
231
249
|
const windows = [...u.windows.filter((w) => !last(w)), ...bot, ...u.windows.filter(last)]
|
|
232
250
|
return { ...u, windows, ...(plan ? { plan } : {}) }
|