@caph42/pi-cursor-provider 0.0.0-stage → 0.4.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/LICENSE +23 -0
- package/README.md +147 -2
- package/package.json +43 -4
- package/src/auth.ts +272 -0
- package/src/client.ts +90 -0
- package/src/codec.ts +235 -0
- package/src/config.ts +76 -0
- package/src/index.ts +105 -0
- package/src/ledger.ts +292 -0
- package/src/models.ts +336 -0
- package/src/native-session.ts +958 -0
- package/src/pi-stream.ts +330 -0
- package/src/run.ts +1268 -0
- package/src/usage.ts +257 -0
package/src/ledger.ts
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deferred dashboard usage ledger for AgentService/Run steps.
|
|
3
|
+
*
|
|
4
|
+
* Ported from magpie's Cursor provider (MIT):
|
|
5
|
+
* https://github.com/magpie-community/plugins/tree/main/packages/cursor
|
|
6
|
+
*
|
|
7
|
+
* A tool step has no TurnEndedUpdate. Usage is read from the dashboard's
|
|
8
|
+
* GetFilteredUsageEvents by conversation_id. Far from Cursor the event is
|
|
9
|
+
* late: the step says 0 and the conversation owes it; later steps collect
|
|
10
|
+
* it as magpie_deferred so prompt_tokens stay the step's own context size.
|
|
11
|
+
*/
|
|
12
|
+
// @ts-nocheck
|
|
13
|
+
import { createHash } from "node:crypto"
|
|
14
|
+
import { API, headersFor } from "./client.ts"
|
|
15
|
+
|
|
16
|
+
// STEP_WAIT is how long a step's event is looked for: first after that long,
|
|
17
|
+
// then every so often until the end (each ask given `ask` to answer).
|
|
18
|
+
// Far from Cursor none shows in that time (yetone/magpie#1053), and waiting
|
|
19
|
+
// longer would hold every tool step longer. So a tool step's Run is owed by
|
|
20
|
+
// its conversation: next steps collect it in the background from `owedAt`.
|
|
21
|
+
// After `skipAfter` misses in a row, steps stop waiting (but every
|
|
22
|
+
// `retryEvery`th). A debt not collected in `owedFor` is let go.
|
|
23
|
+
export const STEP_WAIT = {
|
|
24
|
+
first: 1500,
|
|
25
|
+
every: 500,
|
|
26
|
+
until: 6000,
|
|
27
|
+
ask: 5000,
|
|
28
|
+
skipAfter: 3,
|
|
29
|
+
retryEvery: 10,
|
|
30
|
+
owedAt: 5000,
|
|
31
|
+
owedFor: 600_000,
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// claimed are the usage events already counted, by account, conversation
|
|
35
|
+
// and time, so that two steps of one conversation never count the same one.
|
|
36
|
+
const claimed = new Map()
|
|
37
|
+
|
|
38
|
+
// owed are what each account's conversation still owes, by credential
|
|
39
|
+
// fingerprint and conversation_id: n Runs whose events are to be counted,
|
|
40
|
+
// the earliest started at since, looked for from ready on; and carry, a
|
|
41
|
+
// count collected that no step gave out.
|
|
42
|
+
export const owed = new Map()
|
|
43
|
+
|
|
44
|
+
// flights are each account's conversation collections still going, which
|
|
45
|
+
// a step that ends the turn waits for.
|
|
46
|
+
export const flights = new Map()
|
|
47
|
+
|
|
48
|
+
// unreadable are the accounts (by token) whose usage events Cursor won't
|
|
49
|
+
// give (a 4xx), for owedFor: their steps are guessed, as before, and owe
|
|
50
|
+
// nothing. misses are how many steps in a row of an account's left
|
|
51
|
+
// something owed.
|
|
52
|
+
export const unreadable = new Map()
|
|
53
|
+
export const misses = new Map()
|
|
54
|
+
|
|
55
|
+
const tokKey = (tok) => createHash("sha256").update(tok).digest("hex")
|
|
56
|
+
export const usageKey = (tok, conv) => tokKey(tok) + "\0" + conv
|
|
57
|
+
|
|
58
|
+
export function canRead(tok) {
|
|
59
|
+
const at = unreadable.get(tokKey(tok))
|
|
60
|
+
if (at === undefined) return true
|
|
61
|
+
if (Date.now() - at < STEP_WAIT.owedFor) return false
|
|
62
|
+
unreadable.delete(tokKey(tok))
|
|
63
|
+
return true
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const ZERO = () => ({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0, reasoning: 0 })
|
|
67
|
+
function addUsage(a, b) {
|
|
68
|
+
if (!b) return a
|
|
69
|
+
if (!a) return { ...b }
|
|
70
|
+
for (const k of Object.keys(a)) a[k] += b[k] ?? 0
|
|
71
|
+
return a
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// owe adds to the account/conversation's debt. A native Run bounds older
|
|
75
|
+
// event timestamps before its start: its authoritative final must never be
|
|
76
|
+
// collected as an earlier Run. Keep that bound when a later stateless Run
|
|
77
|
+
// adds unbounded debt. Ordinary stateless debt retains its original shape.
|
|
78
|
+
const DEBT_GROUP_LIMIT = 64
|
|
79
|
+
export function owe(key, { since = Date.now(), n = 0, ready = Date.now(), carry = null, before } = {}) {
|
|
80
|
+
for (const [k, d] of owed) {
|
|
81
|
+
if (d.groups) {
|
|
82
|
+
d.groups = d.groups.filter((g) => Date.now() - g.since <= STEP_WAIT.owedFor)
|
|
83
|
+
d.n = d.groups.reduce((sum, g) => sum + g.n, 0)
|
|
84
|
+
if (Date.now() - d.since > STEP_WAIT.owedFor) d.carry = null
|
|
85
|
+
if (!d.n && !d.carry) owed.delete(k)
|
|
86
|
+
else if (d.groups.length) d.since = Math.min(...d.groups.map((g) => g.since))
|
|
87
|
+
} else if (Date.now() - d.since > STEP_WAIT.owedFor) owed.delete(k)
|
|
88
|
+
}
|
|
89
|
+
if (n <= 0 && !carry) return
|
|
90
|
+
const d = owed.get(key)
|
|
91
|
+
if (!d) return void owed.set(key, { since, n, ready, carry: carry && { ...carry }, ...(before !== undefined ? { before } : {}) })
|
|
92
|
+
if (n > 0 && (d.groups || d.before !== undefined || before !== undefined)) {
|
|
93
|
+
const groups = d.groups ?? (d.n > 0 ? [{ since: d.since, n: d.n, ready: d.ready, before: d.before }] : [])
|
|
94
|
+
const same = groups.find((g) => g.before === before)
|
|
95
|
+
if (same) {
|
|
96
|
+
same.since = Math.min(same.since, since)
|
|
97
|
+
same.n += n
|
|
98
|
+
same.ready = Math.min(same.ready, ready)
|
|
99
|
+
} else groups.push({ since, n, ready, before })
|
|
100
|
+
// As with expired dashboard debt, overflow stays unknown, never estimated
|
|
101
|
+
// or merged across bounds into an authoritative native Run's event.
|
|
102
|
+
groups.sort((a, b) => a.since - b.since)
|
|
103
|
+
d.groups = groups.slice(-DEBT_GROUP_LIMIT)
|
|
104
|
+
delete d.before
|
|
105
|
+
d.n = d.groups.reduce((sum, g) => sum + g.n, 0)
|
|
106
|
+
d.since = Math.min(...d.groups.map((g) => g.since))
|
|
107
|
+
} else {
|
|
108
|
+
d.since = Math.min(d.since, since)
|
|
109
|
+
d.n += n
|
|
110
|
+
}
|
|
111
|
+
d.ready = Math.min(d.ready, ready)
|
|
112
|
+
d.carry = addUsage(d.carry, carry)
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// usageEvents are the dashboard's events of conversation conv from since
|
|
116
|
+
// on, the `want` oldest not counted yet, summed.
|
|
117
|
+
export async function usageEvents(tok, conv, since, want, { poll = false, first = STEP_WAIT.first, signal, before = () => Infinity, groups, abortFetch = false } = {}) {
|
|
118
|
+
const key = usageKey(tok, conv)
|
|
119
|
+
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
|
+
})
|
|
124
|
+
for (const [k, at] of claimed) if (Date.now() - at > 2 * STEP_WAIT.owedFor) claimed.delete(k)
|
|
125
|
+
const num = (v) => (Number.isFinite(Number(v)) ? Number(v) : 0)
|
|
126
|
+
let usage = null
|
|
127
|
+
let got = 0
|
|
128
|
+
const events = []
|
|
129
|
+
const counts = groups?.map(() => 0)
|
|
130
|
+
if (poll) await wait(first)
|
|
131
|
+
while (!signal?.aborted) {
|
|
132
|
+
try {
|
|
133
|
+
const res = await fetch(API + "/aiserver.v1.DashboardService/GetFilteredUsageEvents", {
|
|
134
|
+
method: "POST",
|
|
135
|
+
headers: await headersFor(tok),
|
|
136
|
+
body: JSON.stringify({ teamId: 0, startDate: String(since - 60_000), endDate: String(Date.now() + 60_000), page: 1, pageSize: 50 }),
|
|
137
|
+
signal: abortFetch && signal ? AbortSignal.any([signal, AbortSignal.timeout(STEP_WAIT.ask)]) : AbortSignal.timeout(STEP_WAIT.ask),
|
|
138
|
+
})
|
|
139
|
+
if (res.status >= 400 && res.status < 500 && res.status !== 429) {
|
|
140
|
+
unreadable.set(tokKey(tok), Date.now())
|
|
141
|
+
return { usage, events, got, counts, refused: true }
|
|
142
|
+
}
|
|
143
|
+
const evs = res.ok ? ((await res.json())?.usageEventsDisplay ?? []) : []
|
|
144
|
+
const found = evs
|
|
145
|
+
.filter((e) => e?.conversationId === conv && e.tokenUsage && num(e.timestamp) >= since - 1000 && !claimed.has(key + "\0" + e.timestamp))
|
|
146
|
+
.sort((a, b) => num(a.timestamp) - num(b.timestamp))
|
|
147
|
+
for (const ev of found) {
|
|
148
|
+
if (got >= want) break
|
|
149
|
+
const at = num(ev.timestamp)
|
|
150
|
+
if (at >= before()) continue
|
|
151
|
+
const group = groups?.findIndex((g, i) => counts[i] < g.n && at >= g.since - 1000 && at < (g.before ?? Infinity))
|
|
152
|
+
if (groups && group === -1) continue
|
|
153
|
+
if (groups) counts[group]++
|
|
154
|
+
claimed.set(key + "\0" + ev.timestamp, Date.now())
|
|
155
|
+
const t = ev.tokenUsage
|
|
156
|
+
const u = { input: num(t.inputTokens), output: num(t.outputTokens), cacheRead: num(t.cacheReadTokens), cacheWrite: num(t.cacheWriteTokens), reasoning: 0 }
|
|
157
|
+
usage = addUsage(usage ?? ZERO(), u)
|
|
158
|
+
events.push({ at: num(ev.timestamp), usage: u })
|
|
159
|
+
got++
|
|
160
|
+
}
|
|
161
|
+
if (got >= want) break
|
|
162
|
+
} catch {}
|
|
163
|
+
if (!poll || Date.now() + STEP_WAIT.every > end) break
|
|
164
|
+
await wait(STEP_WAIT.every)
|
|
165
|
+
}
|
|
166
|
+
return { usage, events, got, counts, refused: false }
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** The usage of one Run as the dashboard counts it; null when none shows in time. */
|
|
170
|
+
export async function stepUsage(tok, conv, since, signal) {
|
|
171
|
+
return (await usageEvents(tok, conv, since, 1, { poll: true, signal })).usage
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function collect(tok, conv, { poll = false, first, signal, over = () => false, abortFetch = false } = {}) {
|
|
175
|
+
const key = usageKey(tok, conv)
|
|
176
|
+
const d = owed.get(key)
|
|
177
|
+
if (!d) return Promise.resolve({ usage: null, carry: null, events: [], short: false })
|
|
178
|
+
owed.delete(key)
|
|
179
|
+
const p = (async () => {
|
|
180
|
+
const groups = (d.groups ?? [d]).filter((g) => (g.before === undefined && !d.groups) || Date.now() - g.since <= STEP_WAIT.owedFor)
|
|
181
|
+
const want = groups.reduce((sum, g) => sum + g.n, 0)
|
|
182
|
+
let r = { usage: null, events: [], got: 0 }
|
|
183
|
+
if (want > 0 && canRead(tok)) r = await usageEvents(tok, conv, Math.min(...groups.map((g) => g.since)), want, {
|
|
184
|
+
poll, first, signal, abortFetch, before: () => d.before ?? Infinity, ...(d.groups ? { groups } : {}),
|
|
185
|
+
}).catch(() => r)
|
|
186
|
+
let short = false
|
|
187
|
+
for (const [i, g] of groups.entries()) {
|
|
188
|
+
const remaining = g.n - (d.groups ? r.counts?.[i] ?? 0 : r.got)
|
|
189
|
+
if (remaining > 0 && canRead(tok)) {
|
|
190
|
+
short = true
|
|
191
|
+
owe(key, { since: g.since, n: remaining, ready: g.ready, before: g.before })
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
const carry = d.carry && { ...d.carry }
|
|
195
|
+
const usage = addUsage(d.carry, r.usage)
|
|
196
|
+
if (!over()) return { usage, carry, events: r.events ?? [], short }
|
|
197
|
+
owe(key, { carry: usage })
|
|
198
|
+
return { usage: null, carry: null, events: [], short }
|
|
199
|
+
})()
|
|
200
|
+
p.debt = d
|
|
201
|
+
const set = flights.get(key) ?? new Set()
|
|
202
|
+
flights.set(key, set.add(p))
|
|
203
|
+
p.finally(() => {
|
|
204
|
+
set.delete(p)
|
|
205
|
+
if (!set.size && flights.get(key) === set) flights.delete(key)
|
|
206
|
+
})
|
|
207
|
+
return p
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* How a Run of conversation conv, started at since, has its usage counted.
|
|
212
|
+
* kept when conversation_id names the session so a later Run can collect debt.
|
|
213
|
+
*/
|
|
214
|
+
export function ledger(tok, conv, since, signal, kept, { before } = {}) {
|
|
215
|
+
const key = tokKey(tok)
|
|
216
|
+
const debtKey = usageKey(tok, conv)
|
|
217
|
+
if (kept && before !== undefined) {
|
|
218
|
+
const debts = [owed.get(debtKey), ...[...(flights.get(debtKey) ?? [])].map((p) => p.debt)]
|
|
219
|
+
for (const d of debts) for (const g of d?.groups ?? (d ? [d] : [])) g.before = Math.min(g.before ?? Infinity, before)
|
|
220
|
+
}
|
|
221
|
+
let mine = null
|
|
222
|
+
let theirs = null
|
|
223
|
+
let over = false
|
|
224
|
+
const gather = (opts) =>
|
|
225
|
+
collect(tok, conv, { ...opts, over: () => over, abortFetch: before !== undefined }).then((r) => {
|
|
226
|
+
theirs = addUsage(theirs, r.carry)
|
|
227
|
+
for (const e of r.events ?? []) {
|
|
228
|
+
if (e.at >= since - 1000) mine = addUsage(mine, e.usage)
|
|
229
|
+
else theirs = addUsage(theirs, e.usage)
|
|
230
|
+
}
|
|
231
|
+
return r
|
|
232
|
+
})
|
|
233
|
+
let collecting = null
|
|
234
|
+
const debt = kept ? owed.get(debtKey) : undefined
|
|
235
|
+
const timer = debt ? setTimeout(() => (collecting = gather()), Math.max(0, debt.ready - Date.now())) : null
|
|
236
|
+
timer?.unref?.()
|
|
237
|
+
const takeMine = () => {
|
|
238
|
+
const u = mine
|
|
239
|
+
mine = null
|
|
240
|
+
return u
|
|
241
|
+
}
|
|
242
|
+
const take = () => {
|
|
243
|
+
const u = addUsage(theirs, mine)
|
|
244
|
+
mine = theirs = null
|
|
245
|
+
return u
|
|
246
|
+
}
|
|
247
|
+
return {
|
|
248
|
+
async own() {
|
|
249
|
+
if (!canRead(tok)) return null
|
|
250
|
+
const m = misses.get(key) ?? 0
|
|
251
|
+
const waits = m < STEP_WAIT.skipAfter || m % STEP_WAIT.retryEvery === 0
|
|
252
|
+
if (!kept) {
|
|
253
|
+
const r = waits ? await usageEvents(tok, conv, since, 1, { poll: true, signal }).catch(() => ({})) : {}
|
|
254
|
+
if (r.usage) misses.delete(key)
|
|
255
|
+
else if (!r.refused) misses.set(key, m + 1)
|
|
256
|
+
return r.usage ?? null
|
|
257
|
+
}
|
|
258
|
+
owe(debtKey, { since, n: 1, ready: Date.now() + STEP_WAIT.owedAt })
|
|
259
|
+
if (waits) {
|
|
260
|
+
const r = await gather({ poll: true, signal })
|
|
261
|
+
if (!canRead(tok)) return null
|
|
262
|
+
if (r.short) misses.set(key, m + 1)
|
|
263
|
+
else misses.delete(key)
|
|
264
|
+
} else misses.set(key, m + 1)
|
|
265
|
+
return takeMine() ?? false
|
|
266
|
+
},
|
|
267
|
+
async owed(final) {
|
|
268
|
+
if (!kept) return null
|
|
269
|
+
if (final) {
|
|
270
|
+
await collecting
|
|
271
|
+
await Promise.all([...(flights.get(debtKey) ?? [])])
|
|
272
|
+
if (owed.has(debtKey)) await gather({ poll: owed.get(debtKey).n > 0, first: 0, signal })
|
|
273
|
+
}
|
|
274
|
+
return take()
|
|
275
|
+
},
|
|
276
|
+
done() {
|
|
277
|
+
over = true
|
|
278
|
+
clearTimeout(timer)
|
|
279
|
+
const u = take()
|
|
280
|
+
if (u) owe(debtKey, { carry: u })
|
|
281
|
+
},
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** Clear process-local ledger state (tests). */
|
|
286
|
+
export function clearLedger() {
|
|
287
|
+
claimed.clear()
|
|
288
|
+
owed.clear()
|
|
289
|
+
flights.clear()
|
|
290
|
+
unreadable.clear()
|
|
291
|
+
misses.clear()
|
|
292
|
+
}
|
package/src/models.ts
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cursor model picker: AvailableModels filtered by GetUsableModels.
|
|
3
|
+
*
|
|
4
|
+
* Ported from magpie's Cursor provider (MIT):
|
|
5
|
+
* https://github.com/magpie-community/plugins/tree/main/packages/cursor
|
|
6
|
+
* Billing-period windows live in usage.ts; per-step deferred usage in ledger.ts.
|
|
7
|
+
*/
|
|
8
|
+
// @ts-nocheck
|
|
9
|
+
import { createHash } from "node:crypto"
|
|
10
|
+
import { API, DEFAULT_CONTEXT, MODELS_KEEP, unary } from "./client.ts"
|
|
11
|
+
|
|
12
|
+
const LEVEL_RANK = ["none", "minimal", "low", "medium", "high", "xhigh", "max"]
|
|
13
|
+
const EFFORT_PARAMS = ["effort", "reasoning_effort", "reasoning"]
|
|
14
|
+
|
|
15
|
+
// the effort words of Cursor's own ids and the levels they are; extra-high
|
|
16
|
+
// before high
|
|
17
|
+
const ID_EFFORTS = [["extra-high", "xhigh"], ["xhigh", "xhigh"], ["minimal", "minimal"], ["none", "none"], ["low", "low"], ["medium", "medium"], ["high", "high"], ["max", "max"]]
|
|
18
|
+
|
|
19
|
+
const cut = (s, suffix) => (s.endsWith(suffix) && s.length > suffix.length ? s.slice(0, -suffix.length) : null)
|
|
20
|
+
|
|
21
|
+
// splitID is one of Cursor's own ids (a variant's legacySlug, as
|
|
22
|
+
// cursor-agent models lists it) taken apart: its family, and the effort
|
|
23
|
+
// ("" for none named) it is at. Thinking comes before the effort or after
|
|
24
|
+
// it; in the family it goes after, as does fast. The family is the id 0.1.x
|
|
25
|
+
// listed a model by.
|
|
26
|
+
function splitID(id) {
|
|
27
|
+
let s = id
|
|
28
|
+
let fast = false
|
|
29
|
+
let thinking = false
|
|
30
|
+
let effort = ""
|
|
31
|
+
let b
|
|
32
|
+
if ((b = cut(s, "-fast")) !== null) [s, fast] = [b, true]
|
|
33
|
+
if ((b = cut(s, "-thinking")) !== null) [s, thinking] = [b, true]
|
|
34
|
+
for (const [word, level] of ID_EFFORTS) {
|
|
35
|
+
if ((b = cut(s, "-" + word)) !== null) {
|
|
36
|
+
;[s, effort] = [b, level]
|
|
37
|
+
break
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
if (!thinking && (b = cut(s, "-thinking")) !== null) [s, thinking] = [b, true]
|
|
41
|
+
if (thinking) s += "-thinking"
|
|
42
|
+
if (fast) s += "-fast"
|
|
43
|
+
return [s, effort]
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// left out of the CLI's picker as it leaves them out (model-service.ts)
|
|
47
|
+
const PICKER_SKIP = new Set(["claude-4.5-haiku", "claude-4.5-haiku-thinking", "gemini-2.5-pro", "gemini-2.5-flash", "claude-haiku-4-5"])
|
|
48
|
+
|
|
49
|
+
const clean = (s) => String(s ?? "").replaceAll("\u200b", "").split(/\s+/).filter(Boolean).join(" ")
|
|
50
|
+
|
|
51
|
+
// tokensOf is a context value as tokens: "300k" 300000, "1m" 1000000.
|
|
52
|
+
function tokensOf(value) {
|
|
53
|
+
const m = /^(\d+(?:\.\d+)?)([km])$/i.exec(String(value ?? "").trim())
|
|
54
|
+
return m ? Math.round(Number(m[1]) * (m[2].toLowerCase() === "m" ? 1_000_000 : 1_000)) : 0
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// paramDefs is a picker model's parameters: id to the values it takes.
|
|
58
|
+
function paramDefs(m) {
|
|
59
|
+
const out = {}
|
|
60
|
+
for (const d of m.parameterDefinitions ?? []) {
|
|
61
|
+
const t = d?.parameterType ?? {}
|
|
62
|
+
const vs = (t.enumParameter ?? t.booleanParameter)?.values ?? []
|
|
63
|
+
if (d?.id) out[d.id] = vs.map((v) => String(v.value))
|
|
64
|
+
}
|
|
65
|
+
return out
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const valuesOf = (v) => Object.fromEntries((v?.parameterValues ?? []).map((p) => [String(p.id), String(p.value)]))
|
|
69
|
+
|
|
70
|
+
// defaultVariant is the variant the CLI picks for a model asked for by
|
|
71
|
+
// name: its default without Max Mode, else with it, else the first.
|
|
72
|
+
const defaultVariant = (m) => {
|
|
73
|
+
const vs = m?.variants ?? []
|
|
74
|
+
return vs.find((v) => v.isDefaultNonMaxConfig) ?? vs.find((v) => v.isDefaultMaxConfig) ?? vs[0]
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// needsMax is whether a variant is run in Max Mode only, as the CLI reads
|
|
78
|
+
// it: a model with no other mode, or a Max Mode variant.
|
|
79
|
+
const needsMax = (m, v) => m?.supportsNonMaxMode === false || v?.isMaxMode === true
|
|
80
|
+
|
|
81
|
+
// effortsOf is the efforts a model takes, as pi's levels, each with the
|
|
82
|
+
// value Cursor's parameter has for it (extra-high is xhigh).
|
|
83
|
+
function effortsOf(defs) {
|
|
84
|
+
const pid = EFFORT_PARAMS.find((p) => defs[p]?.length)
|
|
85
|
+
// thinking alone, on or off: high and none
|
|
86
|
+
if (!pid && defs.thinking?.includes("true") && defs.thinking.includes("false")) return { pid: "thinking", levels: { none: "false", high: "true" } }
|
|
87
|
+
if (!pid) return { pid: "", levels: {} }
|
|
88
|
+
const levels = {}
|
|
89
|
+
for (const v of defs[pid]) {
|
|
90
|
+
const l = v === "extra-high" ? "xhigh" : v
|
|
91
|
+
if (LEVEL_RANK.includes(l)) levels[l] = v
|
|
92
|
+
}
|
|
93
|
+
return { pid, levels }
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// served is a picker model's variants the account is served. With the
|
|
97
|
+
// usable list at hand (the ids cursor-agent models shows), a variant whose
|
|
98
|
+
// own id isn't in it is one the account hasn't got (Sonnet 4.6 at any effort
|
|
99
|
+
// but medium, say). A model the usable list has nothing of is the picker's
|
|
100
|
+
// alone (GLM-5.3), and is kept whole.
|
|
101
|
+
function served(m, ids) {
|
|
102
|
+
const vs = m.variants ?? []
|
|
103
|
+
if (!ids) return vs
|
|
104
|
+
const got = vs.filter((v) => !v.legacySlug || ids.has(v.legacySlug))
|
|
105
|
+
return got.some((v) => v.legacySlug) ? got : vs
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// modelsOf is the picker's models as offered: one entry for each context
|
|
109
|
+
// size a model has, or one with Cursor's limit when it has none. A model
|
|
110
|
+
// served in part is offered at the sizes and efforts it is served at.
|
|
111
|
+
function modelsOf(picker, ids) {
|
|
112
|
+
const out = []
|
|
113
|
+
const used = new Set()
|
|
114
|
+
for (const m of picker) {
|
|
115
|
+
if (!m?.name || m.isHidden || m.isChatOnly || m.onlySupportsCmdK || m.supportsAgent === false || PICKER_SKIP.has(m.name)) continue
|
|
116
|
+
const defs = paramDefs(m)
|
|
117
|
+
const variants = served(m, ids)
|
|
118
|
+
const partial = variants.length < (m.variants ?? []).length
|
|
119
|
+
const has = (pid, value) => !partial || !variants.some((v) => pid in valuesOf(v)) || variants.some((v) => valuesOf(v)[pid] === value)
|
|
120
|
+
const def = defaultVariant({ variants })
|
|
121
|
+
const { pid, levels: all } = effortsOf(defs)
|
|
122
|
+
const levels = Object.fromEntries(Object.entries(all).filter(([, value]) => has(pid, value)))
|
|
123
|
+
const base = { run: m.name, title: clean(m.clientDisplayName || m.name), pid, levels, fast: !!defs.fast?.length, variants, def, partial, model: m }
|
|
124
|
+
const contexts = (defs.context ?? []).filter((c) => has("context", c))
|
|
125
|
+
if (contexts.length) {
|
|
126
|
+
for (const c of contexts) {
|
|
127
|
+
const id = m.name + "@" + c
|
|
128
|
+
if (used.has(id)) continue
|
|
129
|
+
used.add(id)
|
|
130
|
+
out.push({ ...base, id, name: base.title + " @ " + c, context: tokensOf(c) || DEFAULT_CONTEXT, size: c, offersFast: fastAt(variants, c) })
|
|
131
|
+
}
|
|
132
|
+
} else if (!used.has(m.name)) {
|
|
133
|
+
used.add(m.name)
|
|
134
|
+
const limit = needsMax(m, def) ? m.contextTokenLimitForMaxMode || m.contextTokenLimit : m.contextTokenLimit
|
|
135
|
+
out.push({ ...base, id: m.name === "default" ? "auto" : m.name, name: base.title, context: limit > 0 ? limit : DEFAULT_CONTEXT, size: "", offersFast: fastAt(variants, "") })
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return out
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// fastAt is whether Cursor has a fast variant the account is served at
|
|
142
|
+
// the context size (any, for a model without sizes): what magpie offers
|
|
143
|
+
// fast for, which 0.1.x said with a -fast model of its own.
|
|
144
|
+
const fastAt = (variants, size) =>
|
|
145
|
+
variants.some((v) => {
|
|
146
|
+
const have = valuesOf(v)
|
|
147
|
+
return have.fast === "true" && (!size || have.context === undefined || have.context === size)
|
|
148
|
+
})
|
|
149
|
+
|
|
150
|
+
// nearest is the variant of vs most like the parameters wanted, one at
|
|
151
|
+
// their context size before any other.
|
|
152
|
+
function nearest(vs, want) {
|
|
153
|
+
let best
|
|
154
|
+
let most = -1
|
|
155
|
+
for (const v of vs) {
|
|
156
|
+
const have = valuesOf(v)
|
|
157
|
+
const n = Object.keys(want).filter((k) => have[k] === want[k]).length + (have.context === want.context ? 100 : 0)
|
|
158
|
+
if (n > most) [best, most] = [v, n]
|
|
159
|
+
}
|
|
160
|
+
return best
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// pick is the variant a request runs as: the model's context size, the
|
|
164
|
+
// effort asked for (else the default's) and fast as asked, matched against
|
|
165
|
+
// Cursor's variants. With no variant that matches, the parameters go as
|
|
166
|
+
// they are, from the default's; of a model served in part, as the nearest
|
|
167
|
+
// variant the account has. seed is the variant an id of Cursor's own named
|
|
168
|
+
// (request), in the default's place.
|
|
169
|
+
function pick(entry, effort, fast, seed) {
|
|
170
|
+
const def = entry.def
|
|
171
|
+
const want = { ...valuesOf(seed ?? def) }
|
|
172
|
+
if (entry.size) want.context = entry.size
|
|
173
|
+
if (effort === "off") effort = "none"
|
|
174
|
+
if (entry.pid && entry.pid !== "thinking" && effort === "none" && !("none" in entry.levels) && "thinking" in want) {
|
|
175
|
+
// a Claude asked not to think: thinking off at its default effort
|
|
176
|
+
want.thinking = "false"
|
|
177
|
+
} else if (entry.pid) {
|
|
178
|
+
const at = effort ? fitEffort(effort, Object.keys(entry.levels)) : ""
|
|
179
|
+
if (at && entry.levels[at]) want[entry.pid] = entry.levels[at]
|
|
180
|
+
// a variant named says for itself whether it thinks
|
|
181
|
+
if (!seed && entry.pid !== "thinking" && "thinking" in want && at) want.thinking = "true"
|
|
182
|
+
}
|
|
183
|
+
// fast only when asked: it costs more
|
|
184
|
+
if (entry.fast) want.fast = fast ? "true" : "false"
|
|
185
|
+
const same = (v) => {
|
|
186
|
+
const have = valuesOf(v)
|
|
187
|
+
return Object.keys({ ...have, ...want }).every((k) => have[k] === undefined || want[k] === undefined || have[k] === want[k])
|
|
188
|
+
}
|
|
189
|
+
const v = entry.variants.find(same) ?? (seed ? branch(entry, want) : undefined) ?? (entry.partial ? nearest(entry.variants, want) : undefined)
|
|
190
|
+
const params = Object.entries(v ? { ...want, ...valuesOf(v) } : want).map(([id, value]) => ({ id, value }))
|
|
191
|
+
// no variant: Max Mode when the size is more than Cursor allows outside it
|
|
192
|
+
const maxMode = v ? needsMax(entry.model, v) : needsMax(entry.model, def) || tokensOf(entry.size) > (entry.model.contextTokenLimit || Infinity)
|
|
193
|
+
// the agent API takes the variant's own id (its legacySlug, as
|
|
194
|
+
// cursor-agent models lists it: claude-opus-5-5-high), not the picker's
|
|
195
|
+
// model name; the default's when no variant matched
|
|
196
|
+
const id = v?.legacySlug || def?.legacySlug || entry.run
|
|
197
|
+
return { id, params, maxMode }
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// branch is, for an id of Cursor's own asked at an effort no variant has
|
|
201
|
+
// with the rest of its parameters (claude-opus-5-low at xhigh: Opus 5
|
|
202
|
+
// without thinking stops at high), the variant with those parameters at the
|
|
203
|
+
// nearest effort it has, not the default's id with parameters that
|
|
204
|
+
// contradict it (claude-opus-5-thinking-high with thinking=false). Where
|
|
205
|
+
// the default differs from what is asked in the effort alone, the effort
|
|
206
|
+
// goes as asked, as for a listed model.
|
|
207
|
+
function branch(entry, want) {
|
|
208
|
+
if (!entry.pid || entry.pid === "thinking") return undefined
|
|
209
|
+
const def = valuesOf(entry.def)
|
|
210
|
+
if (Object.keys(want).every((k) => k === entry.pid || k === "context" || def[k] === undefined || def[k] === want[k])) return undefined
|
|
211
|
+
const vs = entry.variants.filter((v) => {
|
|
212
|
+
const have = valuesOf(v)
|
|
213
|
+
return entry.pid in have && Object.keys(want).every((k) => k === entry.pid || have[k] === undefined || have[k] === want[k])
|
|
214
|
+
})
|
|
215
|
+
const level = (x) => (x === "extra-high" ? "xhigh" : x)
|
|
216
|
+
const at = fitEffort(level(want[entry.pid]), vs.map((v) => level(valuesOf(v)[entry.pid])))
|
|
217
|
+
return at ? vs.find((v) => level(valuesOf(v)[entry.pid]) === at) : undefined
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// fitEffort is the nearest effort a model has to the one asked for; max
|
|
221
|
+
// for ultra, and none only when asked.
|
|
222
|
+
function fitEffort(want, levels) {
|
|
223
|
+
if (want === "ultra") want = "max"
|
|
224
|
+
if (!levels.length || levels.includes(want)) return want
|
|
225
|
+
const at = LEVEL_RANK.indexOf(want)
|
|
226
|
+
if (at < 0) return ""
|
|
227
|
+
let best = ""
|
|
228
|
+
let dist = LEVEL_RANK.length
|
|
229
|
+
for (const l of levels) {
|
|
230
|
+
const i = LEVEL_RANK.indexOf(l)
|
|
231
|
+
if (i < 0 || l === "none") continue
|
|
232
|
+
const d = Math.abs(i - at)
|
|
233
|
+
if (d < dist || (d === dist && i > at)) [best, dist] = [l, d]
|
|
234
|
+
}
|
|
235
|
+
return best
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// usable is the account's list, kept a while, by token: Cursor's picker,
|
|
239
|
+
// less the variants the usable list (AgentService/GetUsableModels, what
|
|
240
|
+
// cursor-agent models shows) says the account hasn't got. A picker Cursor
|
|
241
|
+
// can't give is a failure: magpie keeps the list it had. A usable list it
|
|
242
|
+
// can't give leaves the picker as it is.
|
|
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
|
|
248
|
+
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(
|
|
251
|
+
(u) => {
|
|
252
|
+
const ids = new Set((u?.models ?? []).flatMap((m) => [m.modelId, m.displayModelId]).filter(Boolean))
|
|
253
|
+
return ids.size ? ids : null
|
|
254
|
+
},
|
|
255
|
+
() => null,
|
|
256
|
+
),
|
|
257
|
+
])
|
|
258
|
+
const raw = modelsOf(Array.isArray(j?.models) ? j.models : [], ids)
|
|
259
|
+
if (!raw.length) throw new Error("Cursor listed no models")
|
|
260
|
+
lists.set(h, { at: Date.now(), raw })
|
|
261
|
+
return raw
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// named is the model and variant an id the list doesn't have stands for,
|
|
265
|
+
// when it is one of Cursor's own, as the CLI reads one and as 0.1.x listed
|
|
266
|
+
// them, so a model picked before the list changed still runs: a variant's
|
|
267
|
+
// own id (claude-opus-5-5-high) is that variant; a family of them, the id
|
|
268
|
+
// 0.1.x listed (claude-opus-5-5, claude-opus-5-5-fast, cursor-grok-4.6,
|
|
269
|
+
// or with an effort the account lacks), is the family's variant nearest
|
|
270
|
+
// the default, fast when the family is and at the id's effort; the picker's
|
|
271
|
+
// name for a model, or a legacy slug of it, is its default. Each at the
|
|
272
|
+
// variant's context size, the default's when the id doesn't say.
|
|
273
|
+
function named(raw, id) {
|
|
274
|
+
const models = raw.filter((e, i) => raw.findIndex((x) => x.model === e.model) === i)
|
|
275
|
+
const at = (e, v) => raw.find((x) => x.model === e.model && x.size === (valuesOf(v).context ?? "")) ?? e
|
|
276
|
+
const as = (e, vs, effort) => {
|
|
277
|
+
const seed = nearest(vs, valuesOf(e.def))
|
|
278
|
+
return { entry: at(e, seed), seed, effort, fast: valuesOf(seed).fast === "true" }
|
|
279
|
+
}
|
|
280
|
+
for (const e of models) {
|
|
281
|
+
const vs = e.variants.filter((v) => v.legacySlug === id)
|
|
282
|
+
if (vs.length) return as(e, vs, "")
|
|
283
|
+
}
|
|
284
|
+
const [family, effort] = splitID(id)
|
|
285
|
+
for (const e of models) {
|
|
286
|
+
const vs = e.variants.filter((v) => v.legacySlug && splitID(v.legacySlug)[0] === family)
|
|
287
|
+
if (vs.length) return as(e, vs, effort)
|
|
288
|
+
}
|
|
289
|
+
for (const e of models) {
|
|
290
|
+
const m = e.model
|
|
291
|
+
if ([m.name, ...(m.legacySlugs ?? []), ...(m.idAliases ?? [])].includes(id)) return { entry: at(e, e.def), seed: undefined, effort: "", fast: false }
|
|
292
|
+
}
|
|
293
|
+
return null
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// request is how a chat's model is asked of Cursor: the variant's own id,
|
|
297
|
+
// its parameters and its mode. An id the list doesn't have that is one of
|
|
298
|
+
// Cursor's own goes as the variant it names, at the effort asked for, fast
|
|
299
|
+
// when it says so or the request does; any other goes as it is named.
|
|
300
|
+
export function request(raw, model, effort, fast) {
|
|
301
|
+
const entry = raw.find((m) => m.id === model)
|
|
302
|
+
if (entry) return pick(entry, effort, fast)
|
|
303
|
+
const old = named(raw, model)
|
|
304
|
+
if (old) return pick(old.entry, effort || old.effort, fast || old.fast, old.seed)
|
|
305
|
+
return { id: model === "auto" ? "default" : model, params: [], maxMode: false }
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
const PI_LEVELS = [["off", "none"], ["minimal", "minimal"], ["low", "low"], ["medium", "medium"], ["high", "high"], ["xhigh", "xhigh"], ["max", "max"]]
|
|
309
|
+
|
|
310
|
+
function thinkingLevelMap(levels) {
|
|
311
|
+
if (!levels || !Object.keys(levels).length) return undefined
|
|
312
|
+
const map = {}
|
|
313
|
+
for (const [pi, cur] of PI_LEVELS) {
|
|
314
|
+
if (Object.prototype.hasOwnProperty.call(levels, cur)) map[pi] = levels[cur]
|
|
315
|
+
else if (pi !== "off") map[pi] = null
|
|
316
|
+
}
|
|
317
|
+
return map
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** Pi chat-model configs. Cost stays zero: a subscription bill is not a token price. */
|
|
321
|
+
export function piModelConfigs(raw) {
|
|
322
|
+
return raw.map((m) => {
|
|
323
|
+
const thinking = thinkingLevelMap(m.levels)
|
|
324
|
+
return {
|
|
325
|
+
id: m.id,
|
|
326
|
+
name: m.name,
|
|
327
|
+
api: "cursor-run",
|
|
328
|
+
reasoning: !!thinking,
|
|
329
|
+
...(thinking ? { thinkingLevelMap: thinking } : {}),
|
|
330
|
+
input: ["text", "image"],
|
|
331
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
332
|
+
contextWindow: m.context || DEFAULT_CONTEXT,
|
|
333
|
+
maxTokens: 32_000,
|
|
334
|
+
}
|
|
335
|
+
})
|
|
336
|
+
}
|