Open History to see the last commit
1/**
2 * A record's dedupe key carries its timestamp and an occurrence index counted within one fetch. A
3 * refetched range therefore replaces every cached record in that range rather than adding to it,
4 * so each timestamp's records always come from a single fetch and their occurrence indexes cannot
5 * collide.
6 */
7import { cursorRateModel } from "./accountUsage.ts";
8import type { UsageRecord } from "@t3tools/provider-core/server/usage";
9
10export type CursorCredentialSource = string | { readonly kind: "keychain" };
11
12export const CURSOR_ACCOUNT_TTL_MS = 60 * 1000;
13
14/** Dashboard events can be finalized after they were first read. */
15const REFETCH_OVERLAP_MS = 60 * 60 * 1000;
16
17export interface CursorAccountCache {
18 readonly accountKey: string;
19 readonly sinceMs: number;
20 readonly untilMs: number;
21 readonly fetchedAtMs: number;
22 readonly records: readonly UsageRecord[];
23}
24
25interface CursorFetchRange {
26 readonly sinceMs: number;
27 readonly untilMs: number;
28}
29
30export function isCursorCacheFresh(
31 cache: CursorAccountCache | undefined,
32 nowMs: number,
33): cache is CursorAccountCache {
34 return cache !== undefined && nowMs - cache.fetchedAtMs < CURSOR_ACCOUNT_TTL_MS;
35}
36
37export function cursorFetchRange(
38 cache: CursorAccountCache | undefined,
39 retentionStartMs: number,
40 nowMs: number,
41): CursorFetchRange {
42 return cache === undefined ||
43 cache.sinceMs > retentionStartMs ||
44 cache.untilMs - REFETCH_OVERLAP_MS < retentionStartMs
45 ? { sinceMs: retentionStartMs, untilMs: nowMs }
46 : { sinceMs: cache.untilMs - REFETCH_OVERLAP_MS, untilMs: nowMs };
47}
48
49export function mergeCursorFetch(
50 cache: CursorAccountCache | undefined,
51 accountKey: string,
52 range: CursorFetchRange,
53 fetched: readonly UsageRecord[],
54 nowMs: number,
55 retentionStartMs: number,
56) {
57 const inRange = (record: UsageRecord) =>
58 record.timestampMs >= range.sinceMs && record.timestampMs <= range.untilMs;
59 const previous = cache?.records ?? [];
60 const added = fetched.filter(inRange);
61 const replacedKeys = new Set(previous.filter(inRange).map((record) => record.dedupeKey));
62 const changed =
63 cache === undefined ||
64 replacedKeys.size !== added.length ||
65 added.some((record) => !replacedKeys.has(record.dedupeKey));
66 return {
67 changed,
68 cache: {
69 accountKey,
70 sinceMs: retentionStartMs,
71 untilMs: range.untilMs,
72 fetchedAtMs: nowMs,
73 records: [
74 ...previous.filter((record) => !inRange(record) && record.timestampMs >= retentionStartMs),
75 ...added,
76 ],
77 } satisfies CursorAccountCache,
78 };
79}
80
81/**
82 * Each version writes its own file, as the scan cache does, so servers of
83 * different versions sharing a state directory keep their own caches.
84 */
85export const CURSOR_ACCOUNT_CACHE_FILE_NAME = "usage-cursor-account-cache-v1.json";
86const CURSOR_ACCOUNT_CACHE_VERSION = 1;
87
88type SerializedRecord = readonly [
89 timestampMs: number,
90 modelIndex: number,
91 sessionIndex: number,
92 uncachedInputTokens: number,
93 cachedInputTokens: number,
94 cacheCreationTokens: number,
95 outputTokens: number,
96 reportedCostUsd: number | null,
97 dedupeKey: string | null,
98];
99
100interface SerializedAccount {
101 readonly accountKey: string;
102 readonly sinceMs: number;
103 readonly untilMs: number;
104 readonly fetchedAtMs: number;
105 readonly records: readonly SerializedRecord[];
106}
107
108export function encodeCursorAccountCaches(caches: ReadonlyMap<string, CursorAccountCache>): string {
109 const strings: string[] = [];
110 const indexes = new Map<string, number>();
111 const intern = (value: string) => {
112 let index = indexes.get(value);
113 if (index === undefined) {
114 index = strings.length;
115 strings.push(value);
116 indexes.set(value, index);
117 }
118 return index;
119 };
120 const accounts: Record<string, SerializedAccount> = {};
121 for (const [credentialKey, cache] of caches) {
122 accounts[credentialKey] = {
123 accountKey: cache.accountKey,
124 sinceMs: cache.sinceMs,
125 untilMs: cache.untilMs,
126 fetchedAtMs: cache.fetchedAtMs,
127 records: cache.records.map((record) => [
128 record.timestampMs,
129 intern(record.model),
130 intern(record.sessionId),
131 record.totals.uncachedInputTokens,
132 record.totals.cachedInputTokens,
133 record.totals.cacheCreationTokens,
134 record.totals.outputTokens,
135 record.reportedCostUsd,
136 record.dedupeKey,
137 ]),
138 };
139 }
140 return JSON.stringify({ version: CURSOR_ACCOUNT_CACHE_VERSION, strings, accounts });
141}
142
143const isFiniteNumber = (value: unknown): value is number =>
144 typeof value === "number" && Number.isFinite(value);
145
146/**
147 * Rebuilds the caches from a parsed document. A malformed account is dropped
148 * whole, costing one refetch; keeping its survivors would leave a gap the
149 * covered range claims is complete.
150 */
151export function decodeCursorAccountCaches(document: unknown): Map<string, CursorAccountCache> {
152 const caches = new Map<string, CursorAccountCache>();
153 if (typeof document !== "object" || document === null) return caches;
154 const root = document as {
155 readonly version?: unknown;
156 readonly strings?: unknown;
157 readonly accounts?: unknown;
158 };
159 const strings = root.strings;
160 if (
161 root.version !== CURSOR_ACCOUNT_CACHE_VERSION ||
162 !Array.isArray(strings) ||
163 !strings.every((value): value is string => typeof value === "string") ||
164 typeof root.accounts !== "object" ||
165 root.accounts === null
166 ) {
167 return caches;
168 }
169 const stringAt = (index: unknown): string | undefined =>
170 typeof index === "number" ? strings[index] : undefined;
171
172 const decodeRecord = (row: unknown): UsageRecord | null => {
173 if (!Array.isArray(row)) return null;
174 const [
175 timestampMs,
176 modelIndex,
177 sessionIndex,
178 uncached,
179 cached,
180 creation,
181 output,
182 cost,
183 key,
184 ]: readonly unknown[] = row;
185 const model = stringAt(modelIndex);
186 const sessionId = stringAt(sessionIndex);
187 if (
188 !isFiniteNumber(timestampMs) ||
189 model === undefined ||
190 sessionId === undefined ||
191 !isFiniteNumber(uncached) ||
192 !isFiniteNumber(cached) ||
193 !isFiniteNumber(creation) ||
194 !isFiniteNumber(output) ||
195 (cost !== null && !isFiniteNumber(cost)) ||
196 (key !== null && typeof key !== "string")
197 ) {
198 return null;
199 }
200 return {
201 provider: "cursor",
202 timestampMs,
203 model,
204 rateModel: cursorRateModel(model),
205 sessionId,
206 totals: {
207 uncachedInputTokens: uncached,
208 cachedInputTokens: cached,
209 cacheCreationTokens: creation,
210 outputTokens: output,
211 reasoningTokens: 0,
212 },
213 reportedCostUsd: cost,
214 speed: "standard",
215 dedupeKey: key,
216 };
217 };
218
219 for (const [credentialKey, raw] of Object.entries(root.accounts)) {
220 if (typeof raw !== "object" || raw === null) continue;
221 const account = raw as Partial<Record<keyof SerializedAccount, unknown>>;
222 if (
223 typeof account.accountKey !== "string" ||
224 !isFiniteNumber(account.sinceMs) ||
225 !isFiniteNumber(account.untilMs) ||
226 !isFiniteNumber(account.fetchedAtMs) ||
227 !Array.isArray(account.records)
228 ) {
229 continue;
230 }
231 const records: UsageRecord[] = [];
232 for (const row of account.records) {
233 const record = decodeRecord(row);
234 if (record === null) break;
235 records.push(record);
236 }
237 if (records.length !== account.records.length) continue;
238 caches.set(credentialKey, {
239 accountKey: account.accountKey,
240 sinceMs: account.sinceMs,
241 untilMs: account.untilMs,
242 fetchedAtMs: account.fetchedAtMs,
243 records,
244 });
245 }
246 return caches;
247}