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

CursorUsageAccounts.ts

307 lines11.3 KB

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 /**
60 * The last failed refresh per credential source, standing for a TTL so a
61 * client refetching a broken login does not refetch Cursor each time. A
62 * `null` error means there is no login: no source to report.
63 */
64 const failures = new Map<string, { readonly atMs: number; readonly error: string | null }>();
65 const refreshes = new Map<string, Deferred.Deferred<void>>();
66​
67 const ensureLoaded = yield* Effect.cached(
68 fileSystem.readFileString(cachePath).pipe(
69 Effect.flatMap((raw) => decodeCacheFile(raw)),
70 Effect.catchCause(() => Effect.succeed(null)),
71 Effect.map((document) => {
72 for (const [key, cache] of decodeCursorAccountCaches(document)) caches.set(key, cache);
73 }),
74 ),
75 );
76​
77 // Serialized so an older snapshot never lands after a newer one. The dirty
78 // flag is cleared before encoding, so a change while the write is in flight
79 // marks it dirty again; a failed write restores it so the next persist retries.
80 const persistLock = yield* Semaphore.make(1);
81 const persist = Effect.gen(function* () {
82 if (!cacheDirty) return;
83 cacheDirty = false;
84 yield* Effect.sync(() => encodeCursorAccountCaches(caches)).pipe(
85 Effect.flatMap((contents) => writeFileStringAtomically({ filePath: cachePath, contents })),
86 Effect.provideService(FileSystem.FileSystem, fileSystem),
87 Effect.provideService(Path.Path, path),
88 Effect.catchCause(() =>
89 Effect.sync(() => {
90 cacheDirty = true;
91 }),
92 ),
93 );
94 }).pipe(persistLock.withPermit, Effect.withSpan("CursorUsageAccounts.persist"));
95​
96 const pendingPersists = new Set<Fiber.Fiber<void>>();
97 const schedulePersist = Effect.forkDetach(persist).pipe(
98 Effect.map((fiber) => {
99 pendingPersists.add(fiber);
100 fiber.addObserver(() => pendingPersists.delete(fiber));
101 }),
102 );
103 const awaitPersisted = Effect.suspend(() => Fiber.awaitAll([...pendingPersists])).pipe(
104 Effect.asVoid,
105 );
106 yield* Effect.addFinalizer(() => awaitPersisted);
107​
108 const refreshAccount = Effect.fn("CursorUsageAccounts.refreshAccount")(function* (
109 credential: CursorCredentialSource,
110 credentialKey: string,
111 retentionStartMs: number,
112 ) {
113 const nowMs = yield* Clock.currentTimeMillis;
114 const fetchMissing = (cache: CursorAccountCache | undefined) => {
115 const range = cursorFetchRange(cache, retentionStartMs, nowMs);
116 return accountReader
117 .read(credential, range.sinceMs, range.untilMs)
118 .pipe(Effect.map((result) => ({ range, result })));
119 };
120 let base = caches.get(credentialKey);
121 let fetched = yield* fetchMissing(base);
122 if (
123 base !== undefined &&
124 fetched.result.accountKey !== null &&
125 fetched.result.accountKey !== base.accountKey
126 ) {
127 caches.delete(credentialKey);
128 cacheDirty = true;
129 base = undefined;
130 fetched = yield* fetchMissing(base);
131 }
132 const { range, result } = fetched;
133 if (result.missing || result.error !== null || result.accountKey === null) {
134 failures.set(credentialKey, {
135 atMs: nowMs,
136 error: result.missing || result.error !== null ? result.error : CURSOR_ACCOUNT_READ_ERROR,
137 });
138 yield* schedulePersist;
139 return;
140 }
141 const merged = mergeCursorFetch(
142 base,
143 result.accountKey,
144 range,
145 result.records,
146 nowMs,
147 retentionStartMs,
148 );
149 caches.set(credentialKey, merged.cache);
150 failures.delete(credentialKey);
151 if (merged.changed) cacheDirty = true;
152 yield* schedulePersist;
153 });
154​
155 const startRefresh = (
156 credential: CursorCredentialSource,
157 credentialKey: string,
158 retentionStartMs: number,
159 ) =>
160 // Enrollment and fork are atomic, so an interrupted caller cannot leave a
161 // registered refresh that nothing will finish.
162 Effect.uninterruptible(
163 Effect.gen(function* () {
164 const current = refreshes.get(credentialKey);
165 if (current !== undefined) return current;
166 const done = Deferred.makeUnsafe<void>();
167 refreshes.set(credentialKey, done);
168 // Detached: a departing client must not cancel a fetch later reads reuse.
169 yield* refreshAccount(credential, credentialKey, retentionStartMs).pipe(
170 Effect.catchCause(() =>
171 Clock.currentTimeMillis.pipe(
172 Effect.map((atMs) =>
173 failures.set(credentialKey, { atMs, error: CURSOR_ACCOUNT_READ_ERROR }),
174 ),
175 ),
176 ),
177 Effect.ensuring(
178 Effect.suspend(() => {
179 refreshes.delete(credentialKey);
180 return Deferred.succeed(done, undefined);
181 }),
182 ),
183 Effect.forkDetach,
184 );
185 return done;
186 }),
187 );
188​
189 const accountSource = Effect.fn("CursorUsageAccounts.accountSource")(function* (
190 credential: CursorCredentialSource,
191 authPath: string,
192 windowStartMs: number,
193 retentionStartMs: number,
194 awaitRefresh: boolean,
195 ) {
196 if (
197 typeof credential === "string" &&
198 !(yield* fileSystem.exists(credential).pipe(Effect.orElseSucceed(() => true)))
199 ) {
200 return null;
201 }
202 yield* ensureLoaded;
203 const credentialKey = typeof credential === "string" ? credential : "keychain";
204 const nowMs = yield* Clock.currentTimeMillis;
205 const recentFailure = failures.get(credentialKey);
206 let refreshing = false;
207 if (
208 (recentFailure === undefined || nowMs - recentFailure.atMs >= CURSOR_ACCOUNT_TTL_MS) &&
209 !isCursorCacheFresh(caches.get(credentialKey), nowMs)
210 ) {
211 const refresh = yield* startRefresh(credential, credentialKey, retentionStartMs);
212 if (awaitRefresh) yield* Deferred.await(refresh);
213 else refreshing = true;
214 }
215​
216 const cache = caches.get(credentialKey);
217 const failure = refreshing ? undefined : failures.get(credentialKey);
218 const failureMessage = failure === undefined ? undefined : failure.error;
219 if (failureMessage === null) return null;
220 if (cache === undefined) {
221 return {
222 dir: authPath,
223 // Never combine a local fallback with another server's account-wide history.
224 ...(refreshing
225 ? { files: [], refreshing: true }
226 : { files: null, message: failureMessage ?? CURSOR_ACCOUNT_READ_ERROR }),
227 } satisfies ProviderUsageScan;
228 }
229 // The same account includes CLI and desktop history from every machine.
230 // A stable remote fingerprint prevents connected environments counting it twice.
231 const source = `cursor-account:${cache.accountKey}`;
232 return {
233 dir: source,
234 hostId: "cursor.com",
235 volumeId: cache.accountKey,
236 files: [
237 {
238 path: source,
239 records: cache.records.filter((record) => record.timestampMs >= windowStartMs),
240 },
241 ],
242 ...(failureMessage === undefined
243 ? { status: "ok" }
244 : { status: "partial", message: failureMessage }),
245 ...(refreshing ? { refreshing: true } : {}),
246 } satisfies ProviderUsageScan;
247 });
248​
249 const scan: CursorUsageAccounts["Service"]["scan"] = Effect.fn("CursorUsageAccounts.scan")(
250 function* ({ keychainUsageEnabled, windowStartMs, retentionCutoffMs, awaitRefresh }) {
251 const home = yield* HostProcess.HomeDirectory;
252 const userHome =
253 (platform === "win32" ? hostEnvironment["USERPROFILE"] : hostEnvironment["HOME"]) || home;
254 const configHome = hostEnvironment["XDG_CONFIG_HOME"]?.trim();
255 const cursorHome =
256 platform === "darwin"
257 ? path.join(userHome, "Library", "Application Support")
258 : platform === "win32"
259 ? hostEnvironment["APPDATA"] || path.join(userHome, "AppData", "Roaming")
260 : configHome && path.isAbsolute(configHome)
261 ? configHome
262 : path.join(userHome, ".config");
263 const authPath =
264 platform === "darwin"
265 ? path.join(userHome, ".cursor", "auth.json")
266 : path.join(cursorHome, platform === "win32" ? "Cursor" : "cursor", "auth.json");
267 const credentialStore = hostEnvironment["AGENT_CLI_CREDENTIAL_STORE"];
268 const loginUnavailable =
269 Boolean(hostEnvironment["CURSOR_AUTH_TOKEN"]?.trim()) ||
270 Boolean(hostEnvironment["CURSOR_API_KEY"]?.trim()) ||
271 credentialStore === "memory";
272 const useKeychain = platform === "darwin" && credentialStore !== "file";
273 if (useKeychain && !loginUnavailable && !keychainUsageEnabled) {
274 return [
275 {
276 dir: authPath,
277 volumeId: "",
278 files: null,
279 message: "Cursor account usage is off on this environment.",
280 action: "enableCursorKeychain",
281 },
282 ];
283 }
284 if (loginUnavailable) {
285 return [
286 {
287 dir: authPath,
288 files: null,
289 message: "Cursor account history needs a Cursor CLI login on this server.",
290 },
291 ];
292 }
293 const source = yield* accountSource(
294 useKeychain ? { kind: "keychain" } : authPath,
295 authPath,
296 windowStartMs,
297 retentionCutoffMs,
298 awaitRefresh,
299 );
300 return source === null ? [] : [source];
301 },
302 );
303​
304 return CursorUsageAccounts.of({ scan, awaitPersisted });
305});
306​
307export const layer = Layer.effect(CursorUsageAccounts, make);