Open History to see the last commit
1import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
2import type { ProviderUsageScan } from "@t3tools/provider-core/server/usage";
3import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
4import * as HostProcess from "@t3tools/shared/HostProcess";
5import * as Clock from "effect/Clock";
6import * as Context from "effect/Context";
7import * as Deferred from "effect/Deferred";
8import * as Effect from "effect/Effect";
9import * as Fiber from "effect/Fiber";
10import * as FileSystem from "effect/FileSystem";
11import * as Layer from "effect/Layer";
12import * as Path from "effect/Path";
13import * as Schema from "effect/Schema";
14import * as Semaphore from "effect/Semaphore";
15
16import {
17 CURSOR_ACCOUNT_CACHE_FILE_NAME,
18 CURSOR_ACCOUNT_TTL_MS,
19 cursorFetchRange,
20 decodeCursorAccountCaches,
21 encodeCursorAccountCaches,
22 isCursorCacheFresh,
23 mergeCursorFetch,
24 type CursorAccountCache,
25 type CursorCredentialSource,
26} from "./accountCache.ts";
27import * as CursorAccountReader from "./CursorAccountReader.ts";
28
29const CURSOR_ACCOUNT_READ_ERROR = "Cursor account usage could not be read.";
30
31const decodeCacheFile = Schema.decodeUnknownEffect(
32 Schema.fromJsonString(Schema.Unknown as unknown as Schema.Codec<unknown>),
33);
34
35export class CursorUsageAccounts extends Context.Service<
36 CursorUsageAccounts,
37 {
38 readonly scan: (input: {
39 readonly keychainUsageEnabled: boolean;
40 readonly windowStartMs: number;
41 readonly retentionCutoffMs: number;
42 readonly awaitRefresh: boolean;
43 }) => Effect.Effect<ReadonlyArray<ProviderUsageScan>>;
44 readonly awaitPersisted: Effect.Effect<void>;
45 }
46>()("@t3tools/provider-cursor/server/CursorUsageAccounts") {}
47
48const make = Effect.gen(function* () {
49 const fileSystem = yield* FileSystem.FileSystem;
50 const path = yield* Path.Path;
51 const host = yield* ProviderHost.ProviderHost;
52 const accountReader = yield* CursorAccountReader.CursorAccountReader;
53 const hostEnvironment = yield* HostProcess.Environment;
54 const platform = yield* HostProcess.Platform;
55
56 const cachePath = path.join(host.paths.stateDir, CURSOR_ACCOUNT_CACHE_FILE_NAME);
57 const caches = new Map<string, CursorAccountCache>();
58 let cacheDirty = false;
59 /** Failed refreshes share the cache TTL to prevent repeated requests; null means no login. */
60 const failures = new Map<string, { readonly atMs: number; readonly error: string | null }>();
61 const refreshes = new Map<string, Deferred.Deferred<void>>();
62
63 const ensureLoaded = yield* Effect.cached(
64 fileSystem.readFileString(cachePath).pipe(
65 Effect.flatMap((raw) => decodeCacheFile(raw)),
66 Effect.catchCause(() => Effect.succeed(null)),
67 Effect.map((document) => {
68 for (const [key, cache] of decodeCursorAccountCaches(document)) caches.set(key, cache);
69 }),
70 ),
71 );
72
73 // Serialize snapshots; clear dirty before encoding and restore it on failure so changes retry.
74 const persistLock = yield* Semaphore.make(1);
75 const persist = Effect.gen(function* () {
76 if (!cacheDirty) return;
77 cacheDirty = false;
78 yield* Effect.sync(() => encodeCursorAccountCaches(caches)).pipe(
79 Effect.flatMap((contents) => writeFileStringAtomically({ filePath: cachePath, contents })),
80 Effect.provideService(FileSystem.FileSystem, fileSystem),
81 Effect.provideService(Path.Path, path),
82 Effect.catchCause(() =>
83 Effect.sync(() => {
84 cacheDirty = true;
85 }),
86 ),
87 );
88 }).pipe(persistLock.withPermit, Effect.withSpan("CursorUsageAccounts.persist"));
89
90 const pendingPersists = new Set<Fiber.Fiber<void>>();
91 const schedulePersist = Effect.forkDetach(persist).pipe(
92 Effect.map((fiber) => {
93 pendingPersists.add(fiber);
94 fiber.addObserver(() => pendingPersists.delete(fiber));
95 }),
96 );
97 const awaitPersisted = Effect.suspend(() => Fiber.awaitAll([...pendingPersists])).pipe(
98 Effect.asVoid,
99 );
100 yield* Effect.addFinalizer(() => awaitPersisted);
101
102 const refreshAccount = Effect.fn("CursorUsageAccounts.refreshAccount")(function* (
103 credential: CursorCredentialSource,
104 credentialKey: string,
105 retentionStartMs: number,
106 ) {
107 const nowMs = yield* Clock.currentTimeMillis;
108 const fetchMissing = (cache: CursorAccountCache | undefined) => {
109 const range = cursorFetchRange(cache, retentionStartMs, nowMs);
110 return accountReader
111 .read(credential, range.sinceMs, range.untilMs)
112 .pipe(Effect.map((result) => ({ range, result })));
113 };
114 let base = caches.get(credentialKey);
115 let fetched = yield* fetchMissing(base);
116 if (
117 base !== undefined &&
118 fetched.result.accountKey !== null &&
119 fetched.result.accountKey !== base.accountKey
120 ) {
121 caches.delete(credentialKey);
122 cacheDirty = true;
123 base = undefined;
124 fetched = yield* fetchMissing(base);
125 }
126 const { range, result } = fetched;
127 if (result.missing || result.error !== null || result.accountKey === null) {
128 failures.set(credentialKey, {
129 atMs: nowMs,
130 error: result.missing || result.error !== null ? result.error : CURSOR_ACCOUNT_READ_ERROR,
131 });
132 yield* schedulePersist;
133 return;
134 }
135 const merged = mergeCursorFetch(
136 base,
137 result.accountKey,
138 range,
139 result.records,
140 nowMs,
141 retentionStartMs,
142 );
143 caches.set(credentialKey, merged.cache);
144 failures.delete(credentialKey);
145 if (merged.changed) cacheDirty = true;
146 yield* schedulePersist;
147 });
148
149 const startRefresh = (
150 credential: CursorCredentialSource,
151 credentialKey: string,
152 retentionStartMs: number,
153 ) =>
154 // Enroll and fork atomically so interruption cannot strand a registered refresh.
155 Effect.uninterruptible(
156 Effect.gen(function* () {
157 const current = refreshes.get(credentialKey);
158 if (current !== undefined) return current;
159 const done = Deferred.makeUnsafe<void>();
160 refreshes.set(credentialKey, done);
161 // Detached: a departing client must not cancel a fetch later reads reuse.
162 yield* refreshAccount(credential, credentialKey, retentionStartMs).pipe(
163 Effect.catchCause(() =>
164 Clock.currentTimeMillis.pipe(
165 Effect.map((atMs) =>
166 failures.set(credentialKey, { atMs, error: CURSOR_ACCOUNT_READ_ERROR }),
167 ),
168 ),
169 ),
170 Effect.ensuring(
171 Effect.suspend(() => {
172 refreshes.delete(credentialKey);
173 return Deferred.succeed(done, undefined);
174 }),
175 ),
176 Effect.forkDetach,
177 );
178 return done;
179 }),
180 );
181
182 const accountSource = Effect.fn("CursorUsageAccounts.accountSource")(function* (
183 credential: CursorCredentialSource,
184 authPath: string,
185 windowStartMs: number,
186 retentionStartMs: number,
187 awaitRefresh: boolean,
188 ) {
189 // A Keychain login outlives an uninstalled Cursor, so it also needs Cursor's local directory.
190 const localLogin = typeof credential === "string" ? credential : path.dirname(authPath);
191 if (!(yield* fileSystem.exists(localLogin).pipe(Effect.orElseSucceed(() => true)))) {
192 return null;
193 }
194 yield* ensureLoaded;
195 const credentialKey = typeof credential === "string" ? credential : "keychain";
196 const nowMs = yield* Clock.currentTimeMillis;
197 const recentFailure = failures.get(credentialKey);
198 let refreshing = false;
199 if (
200 (recentFailure === undefined || nowMs - recentFailure.atMs >= CURSOR_ACCOUNT_TTL_MS) &&
201 !isCursorCacheFresh(caches.get(credentialKey), nowMs)
202 ) {
203 const refresh = yield* startRefresh(credential, credentialKey, retentionStartMs);
204 if (awaitRefresh) yield* Deferred.await(refresh);
205 else refreshing = true;
206 }
207
208 const cache = caches.get(credentialKey);
209 const failure = refreshing ? undefined : failures.get(credentialKey);
210 const failureMessage = failure === undefined ? undefined : failure.error;
211 if (failureMessage === null) return null;
212 if (cache === undefined) {
213 return {
214 dir: authPath,
215 // Never combine a local fallback with another server's account-wide history.
216 ...(refreshing
217 ? { files: [], refreshing: true }
218 : { files: null, message: failureMessage ?? CURSOR_ACCOUNT_READ_ERROR }),
219 } satisfies ProviderUsageScan;
220 }
221 // Account history spans machines; a stable fingerprint prevents duplicate environment counts.
222 const source = `cursor-account:${cache.accountKey}`;
223 return {
224 dir: source,
225 hostId: "cursor.com",
226 volumeId: cache.accountKey,
227 files: [
228 {
229 path: source,
230 records: cache.records.filter((record) => record.timestampMs >= windowStartMs),
231 },
232 ],
233 ...(failureMessage === undefined
234 ? { status: "ok" }
235 : { status: "partial", message: failureMessage }),
236 ...(refreshing ? { refreshing: true } : {}),
237 } satisfies ProviderUsageScan;
238 });
239
240 const scan: CursorUsageAccounts["Service"]["scan"] = Effect.fn("CursorUsageAccounts.scan")(
241 function* ({ keychainUsageEnabled, windowStartMs, retentionCutoffMs, awaitRefresh }) {
242 const home = yield* HostProcess.HomeDirectory;
243 const userHome =
244 (platform === "win32" ? hostEnvironment["USERPROFILE"] : hostEnvironment["HOME"]) || home;
245 const configHome = hostEnvironment["XDG_CONFIG_HOME"]?.trim();
246 const cursorHome =
247 platform === "darwin"
248 ? path.join(userHome, "Library", "Application Support")
249 : platform === "win32"
250 ? hostEnvironment["APPDATA"] || path.join(userHome, "AppData", "Roaming")
251 : configHome && path.isAbsolute(configHome)
252 ? configHome
253 : path.join(userHome, ".config");
254 const authPath =
255 platform === "darwin"
256 ? path.join(userHome, ".cursor", "auth.json")
257 : path.join(cursorHome, platform === "win32" ? "Cursor" : "cursor", "auth.json");
258 const credentialStore = hostEnvironment["AGENT_CLI_CREDENTIAL_STORE"];
259 const loginUnavailable =
260 Boolean(hostEnvironment["CURSOR_AUTH_TOKEN"]?.trim()) ||
261 Boolean(hostEnvironment["CURSOR_API_KEY"]?.trim()) ||
262 credentialStore === "memory";
263 const useKeychain = platform === "darwin" && credentialStore !== "file";
264 if (useKeychain && !loginUnavailable && !keychainUsageEnabled) {
265 return [
266 {
267 dir: authPath,
268 volumeId: "",
269 files: null,
270 message: "Cursor account usage is off on this environment.",
271 action: "enableCursorKeychain",
272 },
273 ];
274 }
275 if (loginUnavailable) {
276 return [
277 {
278 dir: authPath,
279 files: null,
280 message: "Cursor account history needs a Cursor CLI login on this server.",
281 },
282 ];
283 }
284 const source = yield* accountSource(
285 useKeychain ? { kind: "keychain" } : authPath,
286 authPath,
287 windowStartMs,
288 retentionCutoffMs,
289 awaitRefresh,
290 );
291 return source === null ? [] : [source];
292 },
293 );
294
295 return CursorUsageAccounts.of({ scan, awaitPersisted });
296});
297
298export const layer = Layer.effect(CursorUsageAccounts, make);