@caph42/pi-cursor-provider 0.5.0 → 0.5.2

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/src/client.ts CHANGED
@@ -4,7 +4,6 @@
4
4
  * Ported from magpie's Cursor provider (MIT):
5
5
  * https://github.com/magpie-community/plugins/tree/main/packages/cursor
6
6
  */
7
- // @ts-nocheck
8
7
  import { basename, dirname, join } from "node:path"
9
8
  import { homedir, platform, tmpdir } from "node:os"
10
9
  import { readdir, realpath, stat } from "node:fs/promises"
@@ -17,10 +16,10 @@ export const CALL = "CallDynamicTool"
17
16
  export const NAMESPACE = "pi"
18
17
  export const DEFAULT_CONTEXT = 200_000
19
18
  export const MODELS_KEEP = 10 * 60 * 1000
20
- export const GOOS = { win32: "windows" }[platform()] ?? platform()
19
+ export const GOOS = platform() === "win32" ? "windows" : platform()
21
20
  export const tempDir = tmpdir
22
21
 
23
- const exists = (p) => stat(p).then((s) => !s.isDirectory(), () => false)
22
+ const exists = (p: string) => stat(p).then((s) => !s.isDirectory(), () => false)
24
23
 
25
24
  async function cursorExecutable() {
26
25
  const dirs = (process.env.PATH ?? "").split(GOOS === "windows" ? ";" : ":").filter(Boolean)
@@ -39,11 +38,12 @@ async function cursorExecutable() {
39
38
  }
40
39
 
41
40
  const VERSION_RE = /^\d{4}\.\d{2}\.\d{2}-[0-9a-f]+$/
42
- let versionSaid = ""
41
+ const VERSION_TTL = 10 * 60 * 1000
42
+ let versionCache = { value: "", expires: 0 }
43
43
 
44
44
  /** "cli-<installed cursor-agent version>", or the fallback the API still accepts. */
45
45
  export async function clientVersion() {
46
- if (versionSaid) return versionSaid
46
+ if (versionCache.value && Date.now() < versionCache.expires) return versionCache.value
47
47
  let v = ""
48
48
  const exe = await cursorExecutable()
49
49
  if (exe) {
@@ -56,11 +56,11 @@ export async function clientVersion() {
56
56
  for (const dir of dirs)
57
57
  for (const n of await readdir(dir).catch(() => [])) if (VERSION_RE.test(n) && n > v) v = n
58
58
  }
59
- versionSaid = "cli-" + (v || VERSION_FALLBACK)
60
- return versionSaid
59
+ versionCache = { value: "cli-" + (v || VERSION_FALLBACK), expires: Date.now() + VERSION_TTL }
60
+ return versionCache.value
61
61
  }
62
62
 
63
- export async function headersFor(tok) {
63
+ export async function headersFor(tok: string) {
64
64
  return {
65
65
  "Content-Type": "application/json",
66
66
  "Connect-Protocol-Version": "1",
@@ -72,7 +72,7 @@ export async function headersFor(tok) {
72
72
  }
73
73
 
74
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) {
75
+ export async function unary(base: string, path: string, tok: string, body: unknown = {}, timeout = 15_000, signal?: AbortSignal) {
76
76
  const deadline = AbortSignal.timeout(timeout)
77
77
  const res = await fetch(base + "/" + path, {
78
78
  method: "POST",
@@ -83,9 +83,7 @@ export async function unary(base, path, tok, body = {}, timeout = 15_000, signal
83
83
  const text = await res.text()
84
84
  if (!res.ok) {
85
85
  const f = failure(res.status, text)
86
- const e = new Error(f.message)
87
- e.status = f.status
88
- throw e
86
+ throw Object.assign(new Error(f.message), { status: f.status })
89
87
  }
90
88
  return JSON.parse(text || "{}")
91
89
  }
package/src/doctor.ts ADDED
@@ -0,0 +1,149 @@
1
+ /**
2
+ * /cursor.doctor. Reads each store through its owner's view and the journal
3
+ * through trace.turns(). It changes no state and prints nothing derived from
4
+ * a token. Every clock it prints is UTC.
5
+ */
6
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"
7
+ import { resolveAccessToken, type AuthSource } from "./auth.ts"
8
+ import { API, clientVersion } from "./client.ts"
9
+ import { configPath, hiddenPatterns } from "./config.ts"
10
+ import { ledgerState, type LedgerState } from "./ledger.ts"
11
+ import { nativeSessions, type NativeState } from "./native-session.ts"
12
+ import { runState, type RunState } from "./run.ts"
13
+ import { Account, hostOf, trace, type Decision, type TurnLog } from "./trace.ts"
14
+
15
+ type Report = {
16
+ now: number
17
+ /** null when nothing is signed in. */
18
+ auth: { source: AuthSource; account: Account } | null
19
+ version: string
20
+ hidden: { patterns: readonly string[]; path: string }
21
+ run: RunState
22
+ native: NativeState
23
+ ledger: LedgerState
24
+ /** null while CURSOR_DEBUG is off. */
25
+ journal: readonly TurnLog[] | null
26
+ }
27
+
28
+ type Notice = { text: string; level: "info" | "warning" }
29
+
30
+ export function registerCursorDoctor(pi: ExtensionAPI): void {
31
+ pi.registerCommand("cursor.doctor", {
32
+ description: "Show Cursor's credential, transport, agent host, native owners, and usage ledger, without printing the token",
33
+ handler: async (args, ctx) => {
34
+ const { text, level } = render(await gather())
35
+ ctx.ui.notify(args.trim() ? `${text}\nThis command does not take arguments.` : text, level)
36
+ },
37
+ })
38
+ }
39
+
40
+ // Pi's own credential lookup can refresh OAuth over the network, so the doctor
41
+ // reads the local credential, as /cursor.usage does.
42
+ async function gather(): Promise<Report> {
43
+ const auth = await resolveAccessToken()
44
+ const version = await clientVersion()
45
+ const account = auth ? Account.of(auth.token) : undefined
46
+ const now = Date.now()
47
+ return {
48
+ now,
49
+ auth: auth && account ? { source: auth.source, account } : null,
50
+ version,
51
+ hidden: { patterns: hiddenPatterns(), path: configPath() },
52
+ run: runState(account, now),
53
+ native: nativeSessions.state(account),
54
+ ledger: ledgerState(account, now),
55
+ journal: trace?.turns() ?? null,
56
+ }
57
+ }
58
+
59
+ const clock = (ms: number) => `${new Date(ms).toISOString().slice(11, 19)}Z`
60
+ const count = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`
61
+
62
+ function render(report: Report): Notice {
63
+ const { auth, run, native, ledger, journal } = report
64
+ const lines = [`Cursor doctor at ${clock(report.now)}`]
65
+ lines.push(
66
+ auth
67
+ ? `Credential: ${auth.source}. Token not shown. Client ${report.version}.`
68
+ : `Cursor is not signed in. Run /login cursor or set CURSOR_ACCESS_TOKEN. Client ${report.version}.`,
69
+ )
70
+ const { patterns, path } = report.hidden
71
+ lines.push(patterns.length ? `Hidden from /model: ${patterns.join(", ")} (${path}).` : `No models hidden (${path}).`)
72
+ lines.push(
73
+ run.transport.via === "h2"
74
+ ? "Transport: h2."
75
+ : `Transport: h1, sticky until ${clock(run.transport.until)}. HTTP/2 failed on this network, so Runs use HTTP/1.1 at ${hostOf(API)} until then.`,
76
+ )
77
+ lines.push(agentLine(report))
78
+ if (run.maxModeForced.length) lines.push(`Max mode forced for: ${run.maxModeForced.join(", ")}.`)
79
+
80
+ const active = native.owners.filter((owner) => owner.phase !== "complete").length
81
+ lines.push(
82
+ `Native owners: ${active} active, ${native.owners.length - active} kept for replay (limits ${native.limits.perAccount} per account, ${native.limits.perProcess} per process).`,
83
+ )
84
+ for (const owner of native.owners) {
85
+ const ends = owner.phase === "complete" ? "kept for replay" : `lifetime ends ${clock(owner.lifetimeEnds)}`
86
+ const mode = owner.maxMode ? " in max mode" : ""
87
+ lines.push(` ${owner.phase}, ${owner.model || "unknown model"}${mode}, ${count(owner.rounds, "tool round")}, ${ends}, ${owner.current ? "this account" : "another account"}`)
88
+ }
89
+
90
+ const refused = ledger.unreadableOthers + (ledger.current?.unreadableUntil != null ? 1 : 0)
91
+ const { runs, conversations, collecting } = ledger.owed
92
+ lines.push(
93
+ `Ledger: ${count(runs, "Run")} owed over ${count(conversations, "conversation")}, ${count(collecting, "collection")} running, ${count(refused, "account")} unreadable.`,
94
+ )
95
+ if (ledger.current) {
96
+ const { runsOwed, misses, stepsWait, unreadableUntil } = ledger.current
97
+ const skip = stepsWait ? "" : ", so steps skip the usage wait"
98
+ const read = unreadableUntil === null ? "Usage events readable." : `Cursor refuses its usage events until ${clock(unreadableUntil)}.`
99
+ lines.push(` This account: ${count(runsOwed, "Run")} owed, ${count(misses, "usage miss", "usage misses")} in a row${skip}. ${read}`)
100
+ }
101
+
102
+ if (!journal) lines.push("Decision journal off. Start Pi with CURSOR_DEBUG=1 to record retry and fallback reasons.")
103
+ else if (!journal.length) lines.push("Decision journal on (CURSOR_DEBUG). No turn has run yet.")
104
+ else {
105
+ lines.push("Recent decisions (CURSOR_DEBUG), oldest turn first:")
106
+ for (const log of journal) {
107
+ const whose = log.account && auth?.account.same(log.account) ? "this account" : "another account"
108
+ lines.push(log.account ? ` Turn ${log.turn} at ${clock(log.started)}, ${log.model || "no model"}, ${whose}` : " Outside any turn")
109
+ for (const entry of log.entries) lines.push(` ${say(entry)}${entry.count > 1 ? ` ×${entry.count}` : ""}`)
110
+ if (log.dropped) lines.push(` ${count(log.dropped, "later decision")} not kept`)
111
+ }
112
+ }
113
+
114
+ const degraded = !auth || ledger.current?.unreadableUntil != null || run.transport.via === "h1"
115
+ return { text: lines.join("\n"), level: degraded ? "warning" : "info" }
116
+ }
117
+
118
+ function agentLine({ auth, run }: Report): string {
119
+ const n = run.otherAgents
120
+ const others = n ? ` ${count(n, "other account")} ${n === 1 ? "has" : "have"} a cached host.` : ""
121
+ if (!auth) return `Agent host: unknown while signed out.${others}`
122
+ if (!run.agent) return `Agent host: none cached for this account. The next turn asks GetServerConfig.${others}`
123
+ const named = run.agent.source === "server-config" ? "named by GetServerConfig" : "the global default because GetServerConfig named none"
124
+ return `Agent host: ${run.agent.host}, ${named}, asked again after ${clock(run.agent.until)}.${others}`
125
+ }
126
+
127
+ function say(d: Decision): string {
128
+ switch (d.kind) {
129
+ case "endpoint":
130
+ if (d.source === "server-config") return `endpoint: ${d.host}, named by GetServerConfig`
131
+ return d.source === "kept-regional" ? `endpoint: kept ${d.host} (${d.why})` : `endpoint: ${d.host}, the global default (${d.why})`
132
+ case "transport":
133
+ if (d.via === "h2") return `run: h2 to ${d.host}`
134
+ if (d.cause === "sticky") return `run: h1 to ${d.host}, sticky until ${clock(d.until)}`
135
+ return `run: h1 to ${d.host}. HTTP/2 to ${d.h2Host} failed (${d.why})${d.until === null ? "" : `, sticky until ${clock(d.until)}`}.`
136
+ case "native":
137
+ return "why" in d ? `native: ${d.path}, ${d.why}` : `native: ${d.path}`
138
+ case "owner-ended":
139
+ return `owner ended: ${d.phase}, ${d.model || "unknown model"} (${d.why})`
140
+ case "retry":
141
+ if (d.rule === "max-mode") return `max mode required for ${d.model} (${d.status}, ${d.why}). Retried with max mode.`
142
+ if ("retriedOn" in d) return `region error (${d.status}, ${d.why}). Retried on ${d.retriedOn}.`
143
+ return `region error (${d.status}, ${d.why}). Not retried because ${d.notRetried === "cancelled" ? "the turn was cancelled" : "the agent host did not change and the Run used HTTP/2"}.`
144
+ case "failed":
145
+ return `failed (${d.status}, ${d.why})${d.bodyCut ? ", error body cut short" : ""}`
146
+ case "usage":
147
+ return d.outcome === "failed" ? `usage read failed (${d.why})` : `usage read ${d.outcome} (${d.status})`
148
+ }
149
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Ported from magpie's Cursor provider (MIT):
3
+ * https://github.com/magpie-community/plugins/tree/main/packages/cursor
4
+ */
5
+ import { AGENT, API, unary } from "./client.ts"
6
+ import { recall, store, tokenKey } from "./cache.ts"
7
+ import { hostOf, trace, type Account, type Host } from "./trace.ts"
8
+
9
+ type Endpoint = { url: string; listed: boolean; expires: number }
10
+ const endpoints = new Map<string, Endpoint>()
11
+ const ENDPOINT_TTL = 10 * 60 * 1000
12
+ const ENDPOINT_MISS_TTL = 60_000
13
+
14
+ export function endpointCacheKeys(): string[] {
15
+ return [...endpoints.keys()]
16
+ }
17
+
18
+ export async function agentURL(tok: string, fresh: boolean, signal?: AbortSignal): Promise<string> {
19
+ const key = tokenKey(tok)
20
+ const had = recall(endpoints, key)
21
+ if (!fresh && had) return had.url
22
+ let url = AGENT
23
+ let listed = false
24
+ let error: unknown
25
+ try {
26
+ const cfg = await unary(API, "aiserver.v1.ServerConfigService/GetServerConfig", tok, {}, 10_000, signal)
27
+ for (const raw of [cfg?.agentUrlConfig?.agentUrl, cfg?.agentUrlConfig?.agentnUrl]) {
28
+ try {
29
+ const u = new URL(raw)
30
+ if ((u.protocol === "https:" || u.protocol === "http:") && u.host) {
31
+ url = raw.replace(/\/+$/, "")
32
+ listed = true
33
+ break
34
+ }
35
+ } catch {}
36
+ }
37
+ } catch (e) {
38
+ if (signal?.aborted) throw e
39
+ error = e
40
+ }
41
+ if (signal?.aborted) throw Object.assign(new Error("The operation was aborted"), { name: "AbortError" })
42
+ const kept = !listed && fresh && !!had?.url
43
+ trace?.note("endpoint", { url: kept ? had.url : url, listed, kept, error })
44
+ if (kept) return had.url
45
+ store(endpoints, key, { url, listed, expires: 0 }, listed ? ENDPOINT_TTL : ENDPOINT_MISS_TTL)
46
+ return url
47
+ }
48
+
49
+ export function clearAgentCache(): void {
50
+ endpoints.clear()
51
+ }
52
+
53
+ export type AgentHit = {
54
+ host: Host
55
+ source: "server-config" | "global-fallback"
56
+ until: number
57
+ }
58
+
59
+ export function endpointView(account: Account | undefined, now: number): { agent: AgentHit | null; otherAgents: number } {
60
+ let agent: AgentHit | null = null
61
+ let otherAgents = 0
62
+ for (const [key, entry] of endpoints) {
63
+ if (now >= entry.expires) continue
64
+ if (account?.is(key)) agent = { host: hostOf(entry.url), source: entry.listed ? "server-config" : "global-fallback", until: entry.expires }
65
+ else otherAgents++
66
+ }
67
+ return { agent, otherAgents }
68
+ }
package/src/fast.ts CHANGED
@@ -31,11 +31,12 @@ export function registerCursorFast(pi: ExtensionAPI) {
31
31
  }
32
32
 
33
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)
34
+ // Publish the status unconditionally: footers that render extension statuses
35
+ // (pi-ccline, or Pi's own footer before 1.4) show it even when another
36
+ // extension owns the footer slot. Our own footer filters this key out
37
+ // (fast-footer.ts), so the inline badge is never duplicated.
38
+ ctx.ui.setStatus(STATUS, text)
39
+ if (ctx.mode !== "tui" || !supportsInlineFastFooter) return
39
40
  if (!text) { clearFooter(); return }
40
41
  badge = text
41
42
  if (!footerInstalled && !footerYielded) {
package/src/index.ts CHANGED
@@ -11,7 +11,8 @@ import type { Model, Provider } from "@earendil-works/pi-ai"
11
11
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"
12
12
  import { login, refresh, resolveAccessToken } from "./auth.ts"
13
13
  import { AGENT, clientVersion } from "./client.ts"
14
- import { configPath, hiddenPatterns, visible } from "./config.ts"
14
+ import { hiddenPatterns, visible } from "./config.ts"
15
+ import { registerCursorDoctor } from "./doctor.ts"
15
16
  import { piModelConfigs, usable } from "./models.ts"
16
17
  import { registerCursorFast } from "./fast.ts"
17
18
  import { fetchUsage, formatUsage } from "./usage.ts"
@@ -137,21 +138,7 @@ export default function (pi: ExtensionAPI) {
137
138
  if (error && ctx.hasUI) ctx.ui.notify(`Cursor model catalogue: ${error.message}`, "warning")
138
139
  })
139
140
 
140
- pi.registerCommand("cursor.doctor", {
141
- description: "Show which Cursor credential would be used, without printing the token",
142
- handler: async (args, ctx) => {
143
- const extra = args.trim() ? " This command does not take arguments." : ""
144
- const auth = await resolveAccessToken()
145
- const version = await clientVersion()
146
- const patterns = hiddenPatterns()
147
- const hiddenText = patterns.length ? `Hidden from /model: ${patterns.join(", ")} (${configPath()}).` : `No models hidden (${configPath()}).`
148
- if (!auth) {
149
- ctx.ui.notify(`Cursor is not signed in (${version}). Run /login cursor or set CURSOR_ACCESS_TOKEN. ${hiddenText}${extra}`, "warning")
150
- return
151
- }
152
- ctx.ui.notify(`Cursor auth source: ${auth.source}. Client ${version}. ${hiddenText} Token not shown.${extra}`, "info")
153
- },
154
- })
141
+ registerCursorDoctor(pi)
155
142
 
156
143
  pi.registerCommand("cursor.usage", {
157
144
  description: "Show Cursor plan usage for this billing period",
package/src/ledger.ts CHANGED
@@ -13,6 +13,7 @@
13
13
  import { createHash } from "node:crypto"
14
14
  import { API, headersFor } from "./client.ts"
15
15
  import { sleep } from "./sleep.ts"
16
+ import { trace, type Account } from "./trace.ts"
16
17
 
17
18
  // STEP_WAIT is how long a step's event is looked for: first after that long,
18
19
  // then every so often until the end (each ask given `ask` to answer).
@@ -56,14 +57,59 @@ export const misses = new Map()
56
57
  const tokKey = (tok) => createHash("sha256").update(tok).digest("hex")
57
58
  export const usageKey = (tok, conv) => tokKey(tok) + "\0" + conv
58
59
 
60
+ const stepsWait = (missed) => missed < STEP_WAIT.skipAfter || missed % STEP_WAIT.retryEvery === 0
61
+ const refusedUntil = (at) => at + STEP_WAIT.owedFor
62
+
59
63
  export function canRead(tok) {
60
64
  const at = unreadable.get(tokKey(tok))
61
65
  if (at === undefined) return true
62
- if (Date.now() - at < STEP_WAIT.owedFor) return false
66
+ if (Date.now() < refusedUntil(at)) return false
63
67
  unreadable.delete(tokKey(tok))
64
68
  return true
65
69
  }
66
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
+
67
113
  const ZERO = () => ({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0, reasoning: 0 })
68
114
  function addUsage(a, b) {
69
115
  if (!b) return a
@@ -136,8 +182,10 @@ export async function usageEvents(tok, conv, since, want, { poll = false, first
136
182
  })
137
183
  if (res.status >= 400 && res.status < 500 && res.status !== 429) {
138
184
  unreadable.set(tokKey(tok), Date.now())
185
+ trace?.note("usage", { status: res.status, refused: true })
139
186
  return { usage, events, got, counts, refused: true }
140
187
  }
188
+ if (!res.ok) trace?.note("usage", { status: res.status })
141
189
  const evs = res.ok ? ((await res.json())?.usageEventsDisplay ?? []) : []
142
190
  const found = evs
143
191
  .filter((e) => e?.conversationId === conv && e.tokenUsage && num(e.timestamp) >= since - 1000 && !claimed.has(key + "\0" + e.timestamp))
@@ -157,7 +205,9 @@ export async function usageEvents(tok, conv, since, want, { poll = false, first
157
205
  got++
158
206
  }
159
207
  if (got >= want) break
160
- } catch {}
208
+ } catch (e) {
209
+ if (!signal?.aborted) trace?.note("usage", { error: e })
210
+ }
161
211
  if (!poll || Date.now() + STEP_WAIT.every > end) break
162
212
  await wait(STEP_WAIT.every)
163
213
  }
@@ -180,7 +230,10 @@ function collect(tok, conv, { poll = false, first, signal, over = () => false, a
180
230
  let r = { usage: null, events: [], got: 0 }
181
231
  if (want > 0 && canRead(tok)) r = await usageEvents(tok, conv, Math.min(...groups.map((g) => g.since)), want, {
182
232
  poll, first, signal, abortFetch, before: () => d.before ?? Infinity, ...(d.groups ? { groups } : {}),
183
- }).catch(() => r)
233
+ }).catch((e) => {
234
+ trace?.note("usage", { error: e })
235
+ return r
236
+ })
184
237
  let short = false
185
238
  for (const [i, g] of groups.entries()) {
186
239
  const remaining = g.n - (d.groups ? r.counts?.[i] ?? 0 : r.got)
@@ -246,9 +299,14 @@ export function ledger(tok, conv, since, signal, kept, { before } = {}) {
246
299
  async own() {
247
300
  if (!canRead(tok)) return null
248
301
  const m = misses.get(key) ?? 0
249
- const waits = m < STEP_WAIT.skipAfter || m % STEP_WAIT.retryEvery === 0
302
+ const waits = stepsWait(m)
250
303
  if (!kept) {
251
- 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
+ : {}
252
310
  if (r.usage) misses.delete(key)
253
311
  else if (!r.refused) misses.set(key, m + 1)
254
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,11 +241,14 @@ 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 function modelCacheKeys() {
245
+ return [...lists.keys()]
246
+ }
244
247
  export async function usable(tok, force = false, signal?: AbortSignal) {
248
+ const h = tokenKey(tok)
249
+ const had = recall(lists, h)
245
250
  if (signal?.aborted) throw Object.assign(new Error("The operation was aborted"), { name: "AbortError" })
246
- const h = createHash("sha256").update(tok).digest("hex")
247
- const had = lists.get(h)
248
- if (!force && had && Date.now() - had.at < MODELS_KEEP) return had.raw
251
+ if (!force && had) return had.raw
249
252
  const [j, ids] = await Promise.all([
250
253
  unary(API, "aiserver.v1.AiService/AvailableModels", tok, { useModelParameters: true, doNotUseMarkdown: true }, 30_000, signal),
251
254
  unary(API, "agent.v1.AgentService/GetUsableModels", tok, {}, 8_000, signal).then(
@@ -262,7 +265,7 @@ export async function usable(tok, force = false, signal?: AbortSignal) {
262
265
  if (signal?.aborted) throw Object.assign(new Error("The operation was aborted"), { name: "AbortError" })
263
266
  const raw = modelsOf(Array.isArray(j?.models) ? j.models : [], ids)
264
267
  if (!raw.length) throw new Error("Cursor listed no models")
265
- lists.set(h, { at: Date.now(), raw })
268
+ store(lists, h, { raw, expires: 0 }, MODELS_KEEP)
266
269
  return raw
267
270
  }
268
271
 
@@ -5,7 +5,7 @@
5
5
  * Ported from magpie's native-session.mjs (MIT):
6
6
  * https://github.com/magpie-community/plugins/tree/main/packages/cursor
7
7
  * Self-contained. The only import is node:crypto. Run wiring passes pb, exec,
8
- * usageOf, and failure in. This file does not import the rest of the package.
8
+ * usageOf, failure, and trace in. This file does not import the rest of the package.
9
9
  */
10
10
  import { createHash, randomBytes } from "node:crypto"
11
11
 
@@ -352,6 +352,27 @@ class Segment {
352
352
  }
353
353
  }
354
354
 
355
+ /** States an owner in entries can be in. fail() removes an owner as it sets failed, cancelled, or expired. */
356
+ export type OwnerPhase = "opening" | "running" | "submitting" | "awaiting-results" | "finalizing" | "complete"
357
+
358
+ export type OwnerView = {
359
+ phase: OwnerPhase
360
+ model: string
361
+ maxMode: boolean
362
+ /** Tool batches handed back to the caller. */
363
+ rounds: number
364
+ /** The Run's absolute lifetime deadline. */
365
+ lifetimeEnds: number
366
+ /** Whether the owner belongs to the account the reader asked about. */
367
+ current: boolean
368
+ }
369
+
370
+ /** The pool in a form the doctor may print. */
371
+ export type NativeState = {
372
+ owners: readonly OwnerView[]
373
+ limits: { perAccount: number; perProcess: number }
374
+ }
375
+
355
376
  export class NativeSessionPool {
356
377
  constructor(limits = NATIVE_LIMITS) {
357
378
  this.limits = limits
@@ -359,6 +380,21 @@ export class NativeSessionPool {
359
380
  this.handles = new Map()
360
381
  this.selectors = new Map()
361
382
  }
383
+ // Takes anything with Account's is(), so this file imports nothing. Unlike
384
+ // prepare, create, and response(), it changes no owner.
385
+ state(account?: { is(fingerprint: string): boolean }): NativeState {
386
+ return {
387
+ owners: [...this.entries].sort((a, b) => a.expiresAt - b.expiresAt).map((owner) => ({
388
+ phase: owner.state,
389
+ model: owner.resolution?.id ?? "",
390
+ maxMode: !!owner.resolution?.maxMode,
391
+ rounds: owner.segments,
392
+ lifetimeEnds: owner.expiresAt,
393
+ current: !!account?.is(owner.account),
394
+ })),
395
+ limits: { perAccount: this.limits.perAccount, perProcess: this.limits.perProcess },
396
+ }
397
+ }
362
398
  // selector is conversationID(chat, session): session/cache key AND first
363
399
  // user identity. Task subagents sharing a session must not own its parent.
364
400
  prepare(tok, chat, selector, tools) {
@@ -401,7 +437,7 @@ export class NativeSessionPool {
401
437
  return { owner, batch, results, encoded, digest, chat }
402
438
  } catch (e) {
403
439
  if (!(e instanceof NativeSessionError)) throw e
404
- return fallback("history incompatible with retained owner")
440
+ return { fallback: "history incompatible with retained owner", detail: e.message }
405
441
  }
406
442
  }
407
443
  // Pending ancestors, new input, and terminal old handles are ordinary
@@ -411,19 +447,20 @@ export class NativeSessionPool {
411
447
  return { account, selector, controls, selected: !!selector, chat }
412
448
  }
413
449
  create(prepared, resolution, wire) {
414
- if (prepared.fallback || prepared.selected && this.selectors.has(prepared.account + ":" + prepared.selector)) return null
450
+ if (prepared.fallback) return prepared
451
+ if (prepared.selected && this.selectors.has(prepared.account + ":" + prepared.selector)) return { fallback: "owner busy" }
415
452
  const crowded = () => this.entries.size >= this.limits.perProcess || [...this.entries].filter((e) => e.account === prepared.account).length >= this.limits.perAccount
416
453
  while (crowded()) {
417
454
  const accountFull = [...this.entries].filter((e) => e.account === prepared.account).length >= this.limits.perAccount
418
455
  const finished = [...this.entries].find((e) => ["complete", "failed", "cancelled", "expired"].includes(e.state) && (!accountFull || e.account === prepared.account))
419
- if (!finished) return null
456
+ if (!finished) return { fallback: accountFull ? "account owner limit" : "process owner limit" }
420
457
  this.forget(finished)
421
458
  }
422
459
  let owner
423
460
  try { owner = new NativeSession(this, prepared, resolution, wire) }
424
461
  catch (e) {
425
462
  if (!(e instanceof NativeSessionError)) throw e
426
- return null
463
+ return { fallback: "opening history not retainable", detail: e.message }
427
464
  }
428
465
  this.entries.add(owner)
429
466
  if (prepared.selected) this.selectors.set(owner.account + ":" + owner.selector, owner)
@@ -524,6 +561,7 @@ class NativeSession {
524
561
  if (this.error || this.state === "complete") return
525
562
  this.error = error
526
563
  this.state = state
564
+ this.wire.trace?.note("owner-ended", { state, model: this.resolution?.id, error })
527
565
  this.segment.fail(error)
528
566
  for (const segment of this.batches ?? []) segment.detach?.()
529
567
  this.segment.detach?.()
@@ -898,7 +936,7 @@ class NativeSession {
898
936
  }
899
937
  break
900
938
  case 2: {
901
- const c = exec(m.data, this.chatTools, (b) => this.send(b), (id) => this.execClose(id), null, true)
939
+ const c = exec(m.data, this.chatTools, (b) => this.send(b), (id) => this.execClose(id), true)
902
940
  if (c) this.acceptCall(c)
903
941
  // request_context is Cursor asking for the environment, not a call
904
942
  else if (!nativeFields(m.data).some((e) => e.num === 10)) this.answeredCall()