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 if (
190 typeof credential === "string" &&
191 !(yield* fileSystem.exists(credential).pipe(Effect.orElseSucceed(() => true)))
192 ) {
193 return null;
194 }
195 yield* ensureLoaded;
196 const credentialKey = typeof credential === "string" ? credential : "keychain";
197 const nowMs = yield* Clock.currentTimeMillis;
198 const recentFailure = failures.get(credentialKey);
199 let refreshing = false;
200 if (
201 (recentFailure === undefined || nowMs - recentFailure.atMs >= CURSOR_ACCOUNT_TTL_MS) &&
202 !isCursorCacheFresh(caches.get(credentialKey), nowMs)
203 ) {
204 const refresh = yield* startRefresh(credential, credentialKey, retentionStartMs);
205 if (awaitRefresh) yield* Deferred.await(refresh);
206 else refreshing = true;
207 }
208
209 const cache = caches.get(credentialKey);
210 const failure = refreshing ? undefined : failures.get(credentialKey);
211 const failureMessage = failure === undefined ? undefined : failure.error;
212 if (failureMessage === null) return null;
213 if (cache === undefined) {
214 return {
215 dir: authPath,
216 // Never combine a local fallback with another server's account-wide history.
217 ...(refreshing
218 ? { files: [], refreshing: true }
219 : { files: null, message: failureMessage ?? CURSOR_ACCOUNT_READ_ERROR }),
220 } satisfies ProviderUsageScan;
221 }
222 // Account history spans machines; a stable fingerprint prevents duplicate environment counts.
223 const source = `cursor-account:${cache.accountKey}`;
224 return {
225 dir: source,
226 hostId: "cursor.com",
227 volumeId: cache.accountKey,
228 files: [
229 {
230 path: source,
231 records: cache.records.filter((record) => record.timestampMs >= windowStartMs),
232 },
233 ],
234 ...(failureMessage === undefined
235 ? { status: "ok" }
236 : { status: "partial", message: failureMessage }),
237 ...(refreshing ? { refreshing: true } : {}),
238 } satisfies ProviderUsageScan;
239 });
240
241 const scan: CursorUsageAccounts["Service"]["scan"] = Effect.fn("CursorUsageAccounts.scan")(
242 function* ({ keychainUsageEnabled, windowStartMs, retentionCutoffMs, awaitRefresh }) {
243 const home = yield* HostProcess.HomeDirectory;
244 const userHome =
245 (platform === "win32" ? hostEnvironment["USERPROFILE"] : hostEnvironment["HOME"]) || home;
246 const configHome = hostEnvironment["XDG_CONFIG_HOME"]?.trim();
247 const cursorHome =
248 platform === "darwin"
249 ? path.join(userHome, "Library", "Application Support")
250 : platform === "win32"
251 ? hostEnvironment["APPDATA"] || path.join(userHome, "AppData", "Roaming")
252 : configHome && path.isAbsolute(configHome)
253 ? configHome
254 : path.join(userHome, ".config");
255 const authPath =
256 platform === "darwin"
257 ? path.join(userHome, ".cursor", "auth.json")
258 : path.join(cursorHome, platform === "win32" ? "Cursor" : "cursor", "auth.json");
259 const credentialStore = hostEnvironment["AGENT_CLI_CREDENTIAL_STORE"];
260 const loginUnavailable =
261 Boolean(hostEnvironment["CURSOR_AUTH_TOKEN"]?.trim()) ||
262 Boolean(hostEnvironment["CURSOR_API_KEY"]?.trim()) ||
263 credentialStore === "memory";
264 const useKeychain = platform === "darwin" && credentialStore !== "file";
265 if (useKeychain && !loginUnavailable && !keychainUsageEnabled) {
266 return [
267 {
268 dir: authPath,
269 volumeId: "",
270 files: null,
271 message: "Cursor account usage is off on this environment.",
272 action: "enableCursorKeychain",
273 },
274 ];
275 }
276 if (loginUnavailable) {
277 return [
278 {
279 dir: authPath,
280 files: null,
281 message: "Cursor account history needs a Cursor CLI login on this server.",
282 },
283 ];
284 }
285 const source = yield* accountSource(
286 useKeychain ? { kind: "keychain" } : authPath,
287 authPath,
288 windowStartMs,
289 retentionCutoffMs,
290 awaitRefresh,
291 );
292 return source === null ? [] : [source];
293 },
294 );
295
296 return CursorUsageAccounts.of({ scan, awaitPersisted });
297});
298
299export const layer = Layer.effect(CursorUsageAccounts, make);