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