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

CursorUsageAccounts.ts

364 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 Digest from "effect/crypto/Digest";
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 digest = yield* Digest.Digest;
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* digest.digest(Digest.sha256, new TextEncoder().encode(credential.apiKey)),
219 )}`
220 : "keychain";
221 const nowMs = yield* Clock.currentTimeMillis;
222 const recentFailure = failures.get(credentialKey);
223 let refreshing = false;
224 if (
225 (recentFailure === undefined || nowMs - recentFailure.atMs >= CURSOR_ACCOUNT_TTL_MS) &&
226 !isCursorCacheFresh(caches.get(credentialKey), nowMs)
227 ) {
228 const refresh = yield* startRefresh(credential, credentialKey, retentionStartMs);
229 if (awaitRefresh) yield* Deferred.await(refresh);
230 else refreshing = true;
231 }
232​
233 const cache = caches.get(credentialKey);
234 const failure = refreshing ? undefined : failures.get(credentialKey);
235 const failureMessage = failure === undefined ? undefined : failure.error;
236 if (failureMessage === null) return null;
237 if (cache === undefined) {
238 return {
239 dir: authPath,
240 // Never combine a local fallback with another server's account-wide history.
241 ...(refreshing
242 ? { files: [], refreshing: true }
243 : { files: null, message: failureMessage ?? CURSOR_ACCOUNT_READ_ERROR }),
244 } satisfies ProviderUsageScan;
245 }
246 // Account history spans machines; a stable fingerprint prevents duplicate environment counts.
247 const source = `cursor-account:${cache.accountKey}`;
248 return {
249 dir: source,
250 hostId: "cursor.com",
251 volumeId: cache.accountKey,
252 files: [
253 {
254 path: source,
255 records: cache.records.filter((record) => record.timestampMs >= windowStartMs),
256 },
257 ],
258 ...(failureMessage === undefined
259 ? { status: "ok" }
260 : { status: "partial", message: failureMessage }),
261 ...(refreshing ? { refreshing: true } : {}),
262 } satisfies ProviderUsageScan;
263 });
264​
265 const scan: CursorUsageAccounts["Service"]["scan"] = Effect.fn("CursorUsageAccounts.scan")(
266 function* ({
267 instances,
268 keychainUsageEnabled,
269 windowStartMs,
270 retentionCutoffMs,
271 awaitRefresh,
272 }) {
273 const home = yield* HostProcess.HomeDirectory;
274 const userHome =
275 (platform === "win32" ? hostEnvironment["USERPROFILE"] : hostEnvironment["HOME"]) || home;
276 const configHome = hostEnvironment["XDG_CONFIG_HOME"]?.trim();
277 const cursorHome =
278 platform === "darwin"
279 ? path.join(userHome, "Library", "Application Support")
280 : platform === "win32"
281 ? hostEnvironment["APPDATA"] || path.join(userHome, "AppData", "Roaming")
282 : configHome && path.isAbsolute(configHome)
283 ? configHome
284 : path.join(userHome, ".config");
285 const authPath =
286 platform === "darwin"
287 ? path.join(userHome, ".cursor", "auth.json")
288 : path.join(cursorHome, platform === "win32" ? "Cursor" : "cursor", "auth.json");
289 // T3's Cursor sign-in and CURSOR_API_KEY name the account the agent uses, so they win.
290 const apiKeys = yield* Effect.forEach(instances, ({ instanceId, environment }) =>
291 environment.CURSOR_API_KEY?.trim()
292 ? Effect.succeed(environment.CURSOR_API_KEY.trim())
293 : readStoredCursorApiKey(instanceId).pipe(
294 Effect.provideService(ProviderHost.ProviderHost, host),
295 Effect.orElseSucceed(() => undefined),
296 ),
297 );
298 const uniqueApiKeys = [...new Set(apiKeys.filter((apiKey) => apiKey !== undefined))];
299 if (uniqueApiKeys.length > 0) {
300 const sources: ReadonlyArray<ProviderUsageScan | null> = yield* Effect.forEach(
301 uniqueApiKeys,
302 (apiKey) =>
303 accountSource(
304 { kind: "apiKey", apiKey },
305 authPath,
306 windowStartMs,
307 retentionCutoffMs,
308 awaitRefresh,
309 ),
310 );
311 // Keys for one account share its source, and a repeated source would count sessions twice.
312 // A failed key can hold older records, so a current read wins, then a refresh the client
313 // must follow up on.
314 const rank = (source: ProviderUsageScan) =>
315 source.status === "ok" ? 2 : source.refreshing ? 1 : 0;
316 const byAccount = new Map<string, ProviderUsageScan>();
317 for (const source of sources) {
318 if (source === null) continue;
319 const kept = byAccount.get(source.dir);
320 if (kept === undefined || rank(source) > rank(kept)) {
321 byAccount.set(source.dir, source);
322 }
323 }
324 return [...byAccount.values()];
325 }
326 const credentialStore = hostEnvironment["AGENT_CLI_CREDENTIAL_STORE"];
327 const loginUnavailable =
328 Boolean(hostEnvironment["CURSOR_AUTH_TOKEN"]?.trim()) || credentialStore === "memory";
329 const useKeychain = platform === "darwin" && credentialStore !== "file";
330 if (useKeychain && !loginUnavailable && !keychainUsageEnabled) {
331 return [
332 {
333 dir: authPath,
334 volumeId: "",
335 files: null,
336 message: "Cursor account usage is off on this environment.",
337 action: "enableCursorKeychain",
338 },
339 ];
340 }
341 if (loginUnavailable) {
342 return [
343 {
344 dir: authPath,
345 files: null,
346 message: "Cursor account history needs a Cursor CLI login on this server.",
347 },
348 ];
349 }
350 const source = yield* accountSource(
351 useKeychain ? { kind: "keychain" } : authPath,
352 authPath,
353 windowStartMs,
354 retentionCutoffMs,
355 awaitRefresh,
356 );
357 return source === null ? [] : [source];
358 },
359 );
360​
361 return CursorUsageAccounts.of({ scan, awaitPersisted });
362});
363​
364export const layer = Layer.effect(CursorUsageAccounts, make);