Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CursorUsageAccounts.ts

366 lines13.5 KB

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