The best way to control Claude Code, Codex and more from any computer or phone
| 1 | // Occurrence indices are fetch-local; replace entire refetched ranges to prevent key collisions. |
| 2 | import { cursorRateModel } from "./accountUsage.ts"; |
| 3 | import type { UsageRecord } from "@t3tools/provider-core/server/usage"; |
| 4 | |
| 5 | export type CursorCredentialSource = { readonly kind: "apiKey"; readonly apiKey: string }; |
| 6 | |
| 7 | export const CURSOR_ACCOUNT_TTL_MS = 60 * 1000; |
| 8 | |
| 9 | /** Dashboard events can be finalized after they were first read. */ |
| 10 | const REFETCH_OVERLAP_MS = 60 * 60 * 1000; |
| 11 | |
| 12 | export interface CursorAccountCache { |
| 13 | readonly accountKey: string; |
| 14 | readonly sinceMs: number; |
| 15 | readonly untilMs: number; |
| 16 | readonly fetchedAtMs: number; |
| 17 | readonly records: readonly UsageRecord[]; |
| 18 | } |
| 19 | |
| 20 | interface CursorFetchRange { |
| 21 | readonly sinceMs: number; |
| 22 | readonly untilMs: number; |
| 23 | } |
| 24 | |
| 25 | export function isCursorCacheFresh( |
| 26 | cache: CursorAccountCache | undefined, |
| 27 | nowMs: number, |
| 28 | retentionStartMs: number, |
| 29 | ): cache is CursorAccountCache { |
| 30 | return ( |
| 31 | cache !== undefined && |
| 32 | cache.sinceMs <= retentionStartMs && |
| 33 | nowMs - cache.fetchedAtMs < CURSOR_ACCOUNT_TTL_MS |
| 34 | ); |
| 35 | } |
| 36 | |
| 37 | /** Narrowest read a refresh falls back to after failed reads of wider ranges. */ |
| 38 | export const CURSOR_MIN_FETCH_SPAN_MS = 60 * 1000; |
| 39 | |
| 40 | /** |
| 41 | * The next range to read, at most `maxSpanMs` wide unless it only tops up a complete cache: |
| 42 | * the newest history first, then older history down to the retention start. |
| 43 | */ |
| 44 | export function cursorFetchRange( |
| 45 | cache: CursorAccountCache | undefined, |
| 46 | retentionStartMs: number, |
| 47 | nowMs: number, |
| 48 | maxSpanMs = Number.POSITIVE_INFINITY, |
| 49 | ): CursorFetchRange { |
| 50 | if (cache === undefined || cache.untilMs - REFETCH_OVERLAP_MS < retentionStartMs) { |
| 51 | return { sinceMs: Math.max(retentionStartMs, nowMs - maxSpanMs), untilMs: nowMs }; |
| 52 | } |
| 53 | if (cache.untilMs < nowMs || cache.sinceMs <= retentionStartMs) { |
| 54 | // Overlap at most half the span so a narrow read still moves forward. |
| 55 | const sinceMs = cache.untilMs - Math.min(REFETCH_OVERLAP_MS, maxSpanMs / 2); |
| 56 | return { sinceMs, untilMs: Math.min(nowMs, sinceMs + maxSpanMs) }; |
| 57 | } |
| 58 | return { |
| 59 | sinceMs: Math.max(retentionStartMs, cache.sinceMs - maxSpanMs), |
| 60 | untilMs: cache.sinceMs, |
| 61 | }; |
| 62 | } |
| 63 | |
| 64 | export function mergeCursorFetch( |
| 65 | cache: CursorAccountCache | undefined, |
| 66 | accountKey: string, |
| 67 | range: CursorFetchRange, |
| 68 | fetched: readonly UsageRecord[], |
| 69 | nowMs: number, |
| 70 | retentionStartMs: number, |
| 71 | ) { |
| 72 | const inRange = (record: UsageRecord) => |
| 73 | record.timestampMs >= range.sinceMs && record.timestampMs <= range.untilMs; |
| 74 | const base = |
| 75 | cache !== undefined && range.sinceMs <= cache.untilMs && range.untilMs >= cache.sinceMs |
| 76 | ? cache |
| 77 | : undefined; |
| 78 | const older = base !== undefined && range.untilMs <= base.sinceMs; |
| 79 | const previous = base?.records ?? []; |
| 80 | const added = fetched.filter(inRange); |
| 81 | const replacedKeys = new Set<string | null>(); |
| 82 | let pruned = false; |
| 83 | for (const record of previous) { |
| 84 | if (inRange(record)) replacedKeys.add(record.dedupeKey); |
| 85 | else if (record.timestampMs < retentionStartMs) pruned = true; |
| 86 | } |
| 87 | const changed = |
| 88 | base === undefined || |
| 89 | base.sinceMs > retentionStartMs || |
| 90 | pruned || |
| 91 | replacedKeys.size !== added.length || |
| 92 | added.some((record) => !replacedKeys.has(record.dedupeKey)); |
| 93 | let records = previous; |
| 94 | if (changed) { |
| 95 | const kept = previous.filter( |
| 96 | (record) => !inRange(record) && record.timestampMs >= retentionStartMs, |
| 97 | ); |
| 98 | records = older ? added.concat(kept) : kept.concat(added); |
| 99 | } |
| 100 | return { |
| 101 | changed, |
| 102 | cache: { |
| 103 | accountKey, |
| 104 | sinceMs: Math.max(retentionStartMs, Math.min(base?.sinceMs ?? range.sinceMs, range.sinceMs)), |
| 105 | untilMs: older ? base.untilMs : range.untilMs, |
| 106 | fetchedAtMs: nowMs, |
| 107 | records, |
| 108 | } satisfies CursorAccountCache, |
| 109 | }; |
| 110 | } |
| 111 | |
| 112 | /** Versioned files isolate caches for different server versions sharing a state directory. */ |
| 113 | export const CURSOR_ACCOUNT_CACHE_FILE_NAME = "usage-cursor-account-cache-v2.json"; |
| 114 | const CURSOR_ACCOUNT_CACHE_VERSION = 2; |
| 115 | |
| 116 | type SerializedRecord = readonly [ |
| 117 | timestampMs: number, |
| 118 | modelIndex: number, |
| 119 | sessionIndex: number, |
| 120 | uncachedInputTokens: number, |
| 121 | cachedInputTokens: number, |
| 122 | cacheCreationTokens: number, |
| 123 | outputTokens: number, |
| 124 | reportedCostUsd: number | null, |
| 125 | dedupeKey: string | null, |
| 126 | ]; |
| 127 | |
| 128 | interface SerializedAccount { |
| 129 | readonly accountKey: string; |
| 130 | readonly sinceMs: number; |
| 131 | readonly untilMs: number; |
| 132 | readonly fetchedAtMs: number; |
| 133 | readonly records: readonly SerializedRecord[]; |
| 134 | } |
| 135 | |
| 136 | export function encodeCursorAccountCaches(caches: ReadonlyMap<string, CursorAccountCache>): string { |
| 137 | const strings: string[] = []; |
| 138 | const indexes = new Map<string, number>(); |
| 139 | const intern = (value: string) => { |
| 140 | let index = indexes.get(value); |
| 141 | if (index === undefined) { |
| 142 | index = strings.length; |
| 143 | strings.push(value); |
| 144 | indexes.set(value, index); |
| 145 | } |
| 146 | return index; |
| 147 | }; |
| 148 | const accounts: Record<string, SerializedAccount> = {}; |
| 149 | for (const [credentialKey, cache] of caches) { |
| 150 | accounts[credentialKey] = { |
| 151 | accountKey: cache.accountKey, |
| 152 | sinceMs: cache.sinceMs, |
| 153 | untilMs: cache.untilMs, |
| 154 | fetchedAtMs: cache.fetchedAtMs, |
| 155 | records: cache.records.map((record) => [ |
| 156 | record.timestampMs, |
| 157 | intern(record.model), |
| 158 | intern(record.sessionId), |
| 159 | record.totals.uncachedInputTokens, |
| 160 | record.totals.cachedInputTokens, |
| 161 | record.totals.cacheCreationTokens, |
| 162 | record.totals.outputTokens, |
| 163 | record.reportedCostUsd, |
| 164 | record.dedupeKey, |
| 165 | ]), |
| 166 | }; |
| 167 | } |
| 168 | return JSON.stringify({ version: CURSOR_ACCOUNT_CACHE_VERSION, strings, accounts }); |
| 169 | } |
| 170 | |
| 171 | const isFiniteNumber = (value: unknown): value is number => |
| 172 | typeof value === "number" && Number.isFinite(value); |
| 173 | |
| 174 | /** Drop a malformed account whole; surviving records would leave gaps in a range marked complete. */ |
| 175 | export function decodeCursorAccountCaches(document: unknown): Map<string, CursorAccountCache> { |
| 176 | const caches = new Map<string, CursorAccountCache>(); |
| 177 | if (typeof document !== "object" || document === null) return caches; |
| 178 | const root = document as { |
| 179 | readonly version?: unknown; |
| 180 | readonly strings?: unknown; |
| 181 | readonly accounts?: unknown; |
| 182 | }; |
| 183 | const strings = root.strings; |
| 184 | if ( |
| 185 | root.version !== CURSOR_ACCOUNT_CACHE_VERSION || |
| 186 | !Array.isArray(strings) || |
| 187 | !strings.every((value): value is string => typeof value === "string") || |
| 188 | typeof root.accounts !== "object" || |
| 189 | root.accounts === null |
| 190 | ) { |
| 191 | return caches; |
| 192 | } |
| 193 | const stringAt = (index: unknown): string | undefined => |
| 194 | typeof index === "number" ? strings[index] : undefined; |
| 195 | |
| 196 | const decodeRecord = (row: unknown): UsageRecord | null => { |
| 197 | if (!Array.isArray(row)) return null; |
| 198 | const [ |
| 199 | timestampMs, |
| 200 | modelIndex, |
| 201 | sessionIndex, |
| 202 | uncached, |
| 203 | cached, |
| 204 | creation, |
| 205 | output, |
| 206 | cost, |
| 207 | key, |
| 208 | ]: readonly unknown[] = row; |
| 209 | const model = stringAt(modelIndex); |
| 210 | const sessionId = stringAt(sessionIndex); |
| 211 | if ( |
| 212 | !isFiniteNumber(timestampMs) || |
| 213 | model === undefined || |
| 214 | sessionId === undefined || |
| 215 | !isFiniteNumber(uncached) || |
| 216 | !isFiniteNumber(cached) || |
| 217 | !isFiniteNumber(creation) || |
| 218 | !isFiniteNumber(output) || |
| 219 | (cost !== null && !isFiniteNumber(cost)) || |
| 220 | (key !== null && typeof key !== "string") |
| 221 | ) { |
| 222 | return null; |
| 223 | } |
| 224 | return { |
| 225 | provider: "cursor", |
| 226 | timestampMs, |
| 227 | model, |
| 228 | rateModel: cursorRateModel(model), |
| 229 | sessionId, |
| 230 | totals: { |
| 231 | uncachedInputTokens: uncached, |
| 232 | cachedInputTokens: cached, |
| 233 | cacheCreationTokens: creation, |
| 234 | outputTokens: output, |
| 235 | reasoningTokens: 0, |
| 236 | }, |
| 237 | reportedCostUsd: cost, |
| 238 | speed: "standard", |
| 239 | dedupeKey: key, |
| 240 | }; |
| 241 | }; |
| 242 | |
| 243 | for (const [credentialKey, raw] of Object.entries(root.accounts)) { |
| 244 | if (typeof raw !== "object" || raw === null) continue; |
| 245 | const account = raw as Partial<Record<keyof SerializedAccount, unknown>>; |
| 246 | if ( |
| 247 | typeof account.accountKey !== "string" || |
| 248 | !isFiniteNumber(account.sinceMs) || |
| 249 | !isFiniteNumber(account.untilMs) || |
| 250 | !isFiniteNumber(account.fetchedAtMs) || |
| 251 | !Array.isArray(account.records) |
| 252 | ) { |
| 253 | continue; |
| 254 | } |
| 255 | const records: UsageRecord[] = []; |
| 256 | for (const row of account.records) { |
| 257 | const record = decodeRecord(row); |
| 258 | if (record === null) break; |
| 259 | records.push(record); |
| 260 | } |
| 261 | if (records.length !== account.records.length) continue; |
| 262 | caches.set(credentialKey, { |
| 263 | accountKey: account.accountKey, |
| 264 | sinceMs: account.sinceMs, |
| 265 | untilMs: account.untilMs, |
| 266 | fetchedAtMs: account.fetchedAtMs, |
| 267 | records, |
| 268 | }); |
| 269 | } |
| 270 | return caches; |
| 271 | } |