Open History to see the last commit
1/**
2 * CursorUsageAccounts - Cursor's account usage as a usage source, answered
3 * from a cache.
4 *
5 * Cursor's account API is slow, so a read answers from the cached account
6 * history and marks itself `refreshing` while a background refresh runs;
7 * `awaitRefresh` waits for that refresh instead. The caches persist in the
8 * server's state directory, so a restart only refetches the newest edge. See
9 * `accountCache`.
10 *
11 * @module provider-cursor/server/CursorUsageAccounts
12 */
13import * as NodeOS from "node:os";
14
15import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
16import type { ProviderUsageScan } from "@t3tools/provider-core/server/usage";
17import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
18import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess";
19import * as Clock from "effect/Clock";
20import * as Context from "effect/Context";
21import * as Deferred from "effect/Deferred";
22import * as Effect from "effect/Effect";
23import * as Fiber from "effect/Fiber";
24import * as FileSystem from "effect/FileSystem";
25import * as Layer from "effect/Layer";
26import * as Path from "effect/Path";
27import * as Schema from "effect/Schema";
28import * as Semaphore from "effect/Semaphore";
29
30import {
31 CURSOR_ACCOUNT_CACHE_FILE_NAME,
32 CURSOR_ACCOUNT_TTL_MS,
33 cursorFetchRange,
34 decodeCursorAccountCaches,
35 encodeCursorAccountCaches,
36 isCursorCacheFresh,
37 mergeCursorFetch,
38 type CursorAccountCache,
39 type CursorCredentialSource,
40} from "./accountCache.ts";
41import * as CursorAccountReader from "./CursorAccountReader.ts";
42
43const CURSOR_ACCOUNT_READ_ERROR = "Cursor account usage could not be read.";
44
45/** The cache file is narrowed by hand in `accountCache`, so JSON is enough here. */
46const decodeCacheFile = Schema.decodeUnknownEffect(
47 Schema.fromJsonString(Schema.Unknown as unknown as Schema.Codec<unknown>),
48);
49
50export class CursorUsageAccounts extends Context.Service<
51 CursorUsageAccounts,
52 {
53 /** This environment's Cursor account usage source, if it has one to report. */
54 readonly scan: (input: {
55 /** From the same settings snapshot as the rest of the usage read. */
56 readonly keychainUsageEnabled: boolean;
57 readonly windowStartMs: number;
58 readonly retentionCutoffMs: number;
59 readonly awaitRefresh: boolean;
60 }) => Effect.Effect<ReadonlyArray<ProviderUsageScan>>;
61 /** Waits for every cache write scheduled so far, as a restart would need. */
62 readonly awaitPersisted: Effect.Effect<void>;
63 }
64>()("@t3tools/provider-cursor/server/CursorUsageAccounts") {}
65
66const make = Effect.gen(function* () {
67 const fileSystem = yield* FileSystem.FileSystem;
68 const path = yield* Path.Path;
69 const host = yield* ProviderHost.ProviderHost;
70 const accountReader = yield* CursorAccountReader.CursorAccountReader;
71 const hostEnvironment = yield* HostProcessEnvironment;
72 const platform = yield* HostProcessPlatform;
73
74 const cachePath = path.join(host.paths.stateDir, CURSOR_ACCOUNT_CACHE_FILE_NAME);
75 /** Account caches by credential source. */
76 const caches = new Map<string, CursorAccountCache>();
77 let cacheDirty = false;
78 /**
79 * The last failed refresh per credential source, standing for a TTL so a
80 * client refetching a broken login does not refetch Cursor each time. A
81 * `null` error means there is no login: no source to report.
82 */
83 const failures = new Map<string, { readonly atMs: number; readonly error: string | null }>();
84 /** The refresh in flight per credential source, which every read joins. */
85 const refreshes = new Map<string, Deferred.Deferred<void>>();
86
87 /** Loads the persisted caches once; concurrent first readers await the same load. */
88 const ensureLoaded = yield* Effect.cached(
89 fileSystem.readFileString(cachePath).pipe(
90 Effect.flatMap((raw) => decodeCacheFile(raw)),
91 Effect.catchCause(() => Effect.succeed(null)),
92 Effect.map((document) => {
93 for (const [key, cache] of decodeCursorAccountCaches(document)) caches.set(key, cache);
94 }),
95 ),
96 );
97
98 // Serialized so an older snapshot never lands after a newer one. The dirty
99 // flag is cleared before encoding, so a change while the write is in flight
100 // marks it dirty again; a failed write restores it so the next persist retries.
101 const persistLock = yield* Semaphore.make(1);
102 const persist = Effect.gen(function* () {
103 if (!cacheDirty) return;
104 cacheDirty = false;
105 yield* Effect.sync(() => encodeCursorAccountCaches(caches)).pipe(
106 Effect.flatMap((contents) => writeFileStringAtomically({ filePath: cachePath, contents })),
107 Effect.provideService(FileSystem.FileSystem, fileSystem),
108 Effect.provideService(Path.Path, path),
109 Effect.catchCause(() =>
110 Effect.sync(() => {
111 cacheDirty = true;
112 }),
113 ),
114 );
115 }).pipe(persistLock.withPermit, Effect.withSpan("CursorUsageAccounts.persist"));
116
117 const pendingPersists = new Set<Fiber.Fiber<void>>();
118 /** Writes the caches in the background, after the read that dirtied them answers. */
119 const schedulePersist = Effect.forkDetach(persist).pipe(
120 Effect.map((fiber) => {
121 pendingPersists.add(fiber);
122 fiber.addObserver(() => pendingPersists.delete(fiber));
123 }),
124 );
125 const awaitPersisted = Effect.suspend(() => Fiber.awaitAll([...pendingPersists])).pipe(
126 Effect.asVoid,
127 );
128 // A write still running at shutdown finishes first, so the next start keeps it.
129 yield* Effect.addFinalizer(() => awaitPersisted);
130
131 /** Fetches what one account cache is missing, then persists it if anything changed. */
132 const refreshAccount = Effect.fn("CursorUsageAccounts.refreshAccount")(function* (
133 credential: CursorCredentialSource,
134 credentialKey: string,
135 retentionStartMs: number,
136 ) {
137 const nowMs = yield* Clock.currentTimeMillis;
138 const fetchMissing = (cache: CursorAccountCache | undefined) => {
139 const range = cursorFetchRange(cache, retentionStartMs, nowMs);
140 return accountReader
141 .read(credential, range.sinceMs, range.untilMs)
142 .pipe(Effect.map((result) => ({ range, result })));
143 };
144 let base = caches.get(credentialKey);
145 let fetched = yield* fetchMissing(base);
146 // Another login's history replaces the cached account's, even if reading it fails.
147 if (
148 base !== undefined &&
149 fetched.result.accountKey !== null &&
150 fetched.result.accountKey !== base.accountKey
151 ) {
152 caches.delete(credentialKey);
153 cacheDirty = true;
154 base = undefined;
155 fetched = yield* fetchMissing(base);
156 }
157 const { range, result } = fetched;
158 if (result.missing || result.error !== null || result.accountKey === null) {
159 failures.set(credentialKey, {
160 atMs: nowMs,
161 error: result.missing || result.error !== null ? result.error : CURSOR_ACCOUNT_READ_ERROR,
162 });
163 yield* schedulePersist;
164 return;
165 }
166 const merged = mergeCursorFetch(
167 base,
168 result.accountKey,
169 range,
170 result.records,
171 nowMs,
172 retentionStartMs,
173 );
174 caches.set(credentialKey, merged.cache);
175 failures.delete(credentialKey);
176 // An unchanged edge is not worth rewriting the file for: after a restart
177 // the cache just refetches a slightly wider edge. Persisting anyway retries
178 // an earlier failed write; it is a no-op when nothing is dirty.
179 if (merged.changed) cacheDirty = true;
180 yield* schedulePersist;
181 });
182
183 /** Joins the refresh in flight, or starts one. */
184 const startRefresh = (
185 credential: CursorCredentialSource,
186 credentialKey: string,
187 retentionStartMs: number,
188 ) =>
189 // Enrollment and fork are atomic, so an interrupted caller cannot leave a
190 // registered refresh that nothing will finish.
191 Effect.uninterruptible(
192 Effect.gen(function* () {
193 const current = refreshes.get(credentialKey);
194 if (current !== undefined) return current;
195 const done = Deferred.makeUnsafe<void>();
196 refreshes.set(credentialKey, done);
197 // Detached: a departing client must not cancel a fetch later reads reuse.
198 yield* refreshAccount(credential, credentialKey, retentionStartMs).pipe(
199 Effect.catchCause(() =>
200 Clock.currentTimeMillis.pipe(
201 Effect.map((atMs) =>
202 failures.set(credentialKey, { atMs, error: CURSOR_ACCOUNT_READ_ERROR }),
203 ),
204 ),
205 ),
206 Effect.ensuring(
207 Effect.suspend(() => {
208 refreshes.delete(credentialKey);
209 return Deferred.succeed(done, undefined);
210 }),
211 ),
212 Effect.forkDetach,
213 );
214 return done;
215 }),
216 );
217
218 /**
219 * The account source. A cache inside its TTL, or a refresh that failed
220 * inside it, answers directly. Otherwise a refresh starts: `awaitRefresh`
221 * waits for it, and anything else answers from the cache marked `refreshing`.
222 */
223 const accountSource = Effect.fn("CursorUsageAccounts.accountSource")(function* (
224 credential: CursorCredentialSource,
225 authPath: string,
226 windowStartMs: number,
227 retentionStartMs: number,
228 awaitRefresh: boolean,
229 ) {
230 // No saved login means there is no account source to report, not a setup error.
231 if (
232 typeof credential === "string" &&
233 !(yield* fileSystem.exists(credential).pipe(Effect.orElseSucceed(() => true)))
234 ) {
235 return null;
236 }
237 yield* ensureLoaded;
238 const credentialKey = typeof credential === "string" ? credential : "keychain";
239 const nowMs = yield* Clock.currentTimeMillis;
240 const recentFailure = failures.get(credentialKey);
241 let refreshing = false;
242 if (
243 (recentFailure === undefined || nowMs - recentFailure.atMs >= CURSOR_ACCOUNT_TTL_MS) &&
244 !isCursorCacheFresh(caches.get(credentialKey), nowMs)
245 ) {
246 const refresh = yield* startRefresh(credential, credentialKey, retentionStartMs);
247 if (awaitRefresh) yield* Deferred.await(refresh);
248 else refreshing = true;
249 }
250
251 const cache = caches.get(credentialKey);
252 const failure = refreshing ? undefined : failures.get(credentialKey);
253 const failureMessage = failure === undefined ? undefined : failure.error;
254 if (failureMessage === null) return null;
255 if (cache === undefined) {
256 return {
257 dir: authPath,
258 // Never combine a local fallback with another server's account-wide history.
259 ...(refreshing
260 ? { files: [], refreshing: true }
261 : { files: null, message: failureMessage ?? CURSOR_ACCOUNT_READ_ERROR }),
262 } satisfies ProviderUsageScan;
263 }
264 // The same account includes CLI and desktop history from every machine.
265 // A stable remote fingerprint prevents connected environments counting it twice.
266 const source = `cursor-account:${cache.accountKey}`;
267 return {
268 dir: source,
269 hostId: "cursor.com",
270 volumeId: cache.accountKey,
271 files: [
272 {
273 path: source,
274 records: cache.records.filter((record) => record.timestampMs >= windowStartMs),
275 },
276 ],
277 ...(failureMessage === undefined
278 ? { status: "ok" }
279 : { status: "partial", message: failureMessage }),
280 ...(refreshing ? { refreshing: true } : {}),
281 } satisfies ProviderUsageScan;
282 });
283
284 const scan: CursorUsageAccounts["Service"]["scan"] = Effect.fn("CursorUsageAccounts.scan")(
285 function* ({ keychainUsageEnabled, windowStartMs, retentionCutoffMs, awaitRefresh }) {
286 const home = NodeOS.homedir();
287 const userHome =
288 (platform === "win32" ? hostEnvironment["USERPROFILE"] : hostEnvironment["HOME"]) || home;
289 const configHome = hostEnvironment["XDG_CONFIG_HOME"]?.trim();
290 const cursorHome =
291 platform === "darwin"
292 ? path.join(userHome, "Library", "Application Support")
293 : platform === "win32"
294 ? hostEnvironment["APPDATA"] || path.join(userHome, "AppData", "Roaming")
295 : configHome && path.isAbsolute(configHome)
296 ? configHome
297 : path.join(userHome, ".config");
298 const authPath =
299 platform === "darwin"
300 ? path.join(userHome, ".cursor", "auth.json")
301 : path.join(cursorHome, platform === "win32" ? "Cursor" : "cursor", "auth.json");
302 const credentialStore = hostEnvironment["AGENT_CLI_CREDENTIAL_STORE"];
303 const loginUnavailable =
304 Boolean(hostEnvironment["CURSOR_AUTH_TOKEN"]?.trim()) ||
305 Boolean(hostEnvironment["CURSOR_API_KEY"]?.trim()) ||
306 credentialStore === "memory";
307 const useKeychain = platform === "darwin" && credentialStore !== "file";
308 if (useKeychain && !loginUnavailable && !keychainUsageEnabled) {
309 return [
310 {
311 dir: authPath,
312 volumeId: "",
313 files: null,
314 message: "Cursor account usage is off on this environment.",
315 action: "enableCursorKeychain",
316 },
317 ];
318 }
319 if (loginUnavailable) {
320 return [
321 {
322 dir: authPath,
323 files: null,
324 message: "Cursor account history needs a Cursor CLI login on this server.",
325 },
326 ];
327 }
328 const source = yield* accountSource(
329 useKeychain ? { kind: "keychain" } : authPath,
330 authPath,
331 windowStartMs,
332 retentionCutoffMs,
333 awaitRefresh,
334 );
335 return source === null ? [] : [source];
336 },
337 );
338
339 return CursorUsageAccounts.of({ scan, awaitPersisted });
340});
341
342export const layer = Layer.effect(CursorUsageAccounts, make);