feat(usage): scan Cursor, Grok, and OpenCode alongside Claude and Codex #6057
Closedlawrence-millard(GitHub profile, opens in a new tab)wants to merge 7 commits into
main fromrefs/pull/6057/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/usage/UsageService.ts line 710Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -380,0 +631,21 @@631+ message: "Cursor is not signed in on this environment.",632+ });633+ continue;634+ }635+636+ const cacheKey = `${stateDbPath}:${auth.stateDbMtimeMs}:${input.sinceDay}:${input.untilDay}`;637+ const now = yield* Clock.currentTimeMillis;638+ let cursorResult = cursorCache;639+ if (640+ cursorResult === undefined ||641+ cursorResult.cacheKey !== cacheKey ||642+ now - cursorResult.fetchedAtMs >= CURSOR_USAGE_CACHE_TTL_MS643+ ) {644+ const fetched = yield* Effect.promise(() =>645+ fetchCursorUsageRecords({646+ auth,647+ sinceMs: windowStartMs,648+ untilMs: windowEndMs,649+ }),650+ );651+ cursorResult = {apps/server/src/usage/usageCursor.ts lines 184 to 196Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +174,21 @@174+ }175+ } else if (!/^\d+$/.test(normalized)) {176+ return null;177+ }178+ const value = Number(groups.join(""));179+ return Number.isFinite(value) ? value : null;180+}181+182+function parseCsvDateMs(raw: string): number | null {183+ const trimmed = raw.trim();184+ if (trimmed.length === 0) return null;185+ const parsed = Date.parse(trimmed);186+ if (!Number.isNaN(parsed)) return parsed;187+ // `yyyy-MM-dd HH:mm:ss` without timezone — treat as UTC.188+ const match = /^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}:\d{2})$/.exec(trimmed);189+ if (match) {190+ const iso = Date.parse(`${match[1]}T${match[2]}Z`);191+ return Number.isNaN(iso) ? null : iso;192+ }193+ return null;194+}apps/server/src/usage/usageCursor.ts line 524Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +469,21 @@469+ message: "Cursor session expired. Sign in via the Cursor app.",470+ };471+ }472+ if (!response.ok) {473+ return {474+ records: [],475+ status: "failed",476+ message: `Cursor usage export returned HTTP ${response.status}.`,477+ };478+ }479+480+ const text = await response.text();481+ if (!text.startsWith("Date,") && !text.startsWith("\uFEFFDate,")) {482+ return {483+ records: [],484+ status: "failed",485+ message: "Cursor usage export was not CSV.",486+ };487+ }488+489+ return {apps/server/src/usage/usageOpenCode.ts line 47Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +27,21 @@27+/** Resolves OpenCode's data directory the same way the CLI does. */28+export function resolveOpenCodeDataDir(29+ env: NodeJS.ProcessEnv = process.env,30+ homeDir: string = NodeOS.homedir(),31+): string {32+ const dataDir = env["OPENCODE_DATA_DIR"]?.trim();33+ if (dataDir && dataDir.length > 0) return expandHome(dataDir, homeDir);34+35+ const xdg = env["XDG_DATA_HOME"]?.trim();36+ if (xdg && xdg.length > 0) return NodePath.join(expandHome(xdg, homeDir), "opencode");37+38+ return NodePath.join(homeDir, ".local", "share", "opencode");39+}40+41+function expandHome(value: string, homeDir: string): string {42+ if (value === "~") return homeDir;43+ if (value.startsWith("~/")) return NodePath.join(homeDir, value.slice(2));44+ return value;45+}46+47+/** Lists `opencode*.db` files (stable + preview channels) under the data dir. */apps/server/src/usage/usageCursor.ts lines 480 to 481OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +461,21 @@461+ }462+ }463+ }464+465+ if (response.status === 401 || response.status === 403) {466+ return {467+ records: [],468+ status: "failed",469+ message: "Cursor session expired. Sign in via the Cursor app.",470+ };471+ }472+ if (!response.ok) {473+ return {474+ records: [],475+ status: "failed",476+ message: `Cursor usage export returned HTTP ${response.status}.`,477+ };478+ }479+480+ const text = await response.text();481+ if (!text.startsWith("Date,") && !text.startsWith("\uFEFFDate,")) {apps/server/src/usage/UsageService.ts line 389Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -289,3 +369,20 @@289369 return records;290370 });291371372+ const readOpenCodeCached = (373+ dbPath: string,374+ size: number,375+ mtimeMs: number,376+ ): Effect.Effect<readonly UsageRecord[]> =>377+ Effect.gen(function* () {378+ const cached = fileCache.get(dbPath);379+ if (380+ cached &&381+ cached.size === size &&382+ cached.mtimeMs === mtimeMs &&383+ cached.provider === "opencode"384+ ) {385+ return cached.records;386+ }387+388+ const parsed = yield* Effect.sync(() => readOpenCodeDatabaseRecords(dbPath));
- apps/server/src/usage/UsageService.ts line 466Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -313,3 +432,7 @@313432 });314433 }315434 const windowStartMs = DateTime.toEpochMillis(windowStart.value) - MTIME_SLACK_MS;435+ const windowEnd = DateTime.make(`${input.untilDay}T23:59:59.999Z`);436+ const windowEndMs = Option.isSome(windowEnd)437+ ? DateTime.toEpochMillis(windowEnd.value)438+ : startedAtMs;apps/server/src/usage/UsageService.ts line 658OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -380,0 +638,21 @@638+ let cursorResult = cursorCache;639+ if (640+ cursorResult === undefined ||641+ cursorResult.cacheKey !== cacheKey ||642+ now - cursorResult.fetchedAtMs >= CURSOR_USAGE_CACHE_TTL_MS643+ ) {644+ const fetched = yield* Effect.promise(() =>645+ fetchCursorUsageRecords({646+ auth,647+ sinceMs: windowStartMs,648+ untilMs: windowEndMs,649+ }),650+ );651+ cursorResult = {652+ cacheKey,653+ fetchedAtMs: now,654+ records: fetched.records,655+ status: fetched.status === "ok" ? "ok" : "failed",656+ message: fetched.message,657+ };658+ cursorCache = cursorResult;apps/server/src/usage/usageCursor.ts line 193OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +173,21 @@173+ if (group.length !== 3 || !/^\d+$/.test(group)) return null;174+ }175+ } else if (!/^\d+$/.test(normalized)) {176+ return null;177+ }178+ const value = Number(groups.join(""));179+ return Number.isFinite(value) ? value : null;180+}181+182+function parseCsvDateMs(raw: string): number | null {183+ const trimmed = raw.trim();184+ if (trimmed.length === 0) return null;185+ const parsed = Date.parse(trimmed);186+ if (!Number.isNaN(parsed)) return parsed;187+ // `yyyy-MM-dd HH:mm:ss` without timezone — treat as UTC.188+ const match = /^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}:\d{2})$/.exec(trimmed);189+ if (match) {190+ const iso = Date.parse(`${match[1]}T${match[2]}Z`);191+ return Number.isNaN(iso) ? null : iso;192+ }193+ return null;
- apps/server/src/usage/usageCursor.ts lines 392 to 410OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +390,21 @@390+}391+392+async function fetchCsvOnce(393+ sessionToken: string,394+ sinceMs: number,395+ untilMs: number,396+): Promise<Response> {397+ const url = new URL(EXPORT_CSV_URL);398+ url.searchParams.set("startDate", String(Math.trunc(sinceMs)));399+ url.searchParams.set("endDate", String(Math.trunc(untilMs)));400+ url.searchParams.set("strategy", "tokens");401+402+ return fetch(url, {403+ method: "GET",404+ headers: {405+ Cookie: `WorkosCursorSessionToken=${sessionToken}`,406+ Accept: "text/csv",407+ },408+ signal: AbortSignal.timeout(30_000),409+ });410+}
- apps/server/src/usage/usageCursor.ts line 510OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +490,21 @@490+ };491+ }492+ if (!response.ok) {493+ return {494+ records: [],495+ status: "failed",496+ message: `Cursor usage export returned HTTP ${response.status}.`,497+ };498+ }499+500+ let text: string;501+ try {502+ text = await response.text();503+ } catch {504+ return {505+ records: [],506+ status: "failed",507+ message: "Cursor usage export body transfer failed.",508+ };509+ }510+ if (!text.startsWith("Date,") && !text.startsWith("\uFEFFDate,")) {
- apps/server/src/usage/UsageService.ts line 483OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -332,0 +463,21 @@463+ fingerprint: { hostId, provider, resolvedHomePath: dir, volumeId },464+ status: "missing",465+ scannedFiles: 0,466+ skippedFiles: 0,467+ malformedRecords: 0,468+ distinctSessions: 0,469+ message: "No transcript directory on this environment.",470+ });471+ continue;472+ }473+474+ walkedRoots.push(dir);475+ const files = yield* Effect.promise(() => listTranscriptFiles(dir, windowStartMs));476+ let scannedFiles = 0;477+ let skippedFiles = 0;478+ const sessionIds = new Set<string>();479+480+ for (const file of files) {481+ livePaths.add(file.path);482+ const records = yield* readFileRecords(file.path, file.size, file.mtimeMs, provider);483+ if (records === null || records.length === 0) {apps/server/src/usage/UsageService.ts line 671Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -368,2 +614,21 @@614+ }615+ if (records.length === 0) {616+ skippedFiles += 1;617+ continue;368618 }619+ scannedFiles += 1;620+ ingestRecords(aggregator, records, sessionIds);369621 }622+623+ sources.push({624+ fingerprint: { hostId, provider, resolvedHomePath: dataDir, volumeId },625+ status: readFailed ? "failed" : "ok",626+ scannedFiles,627+ skippedFiles,628+ malformedRecords: 0,629+ distinctSessions: sessionIds.size,630+ message: readFailed631+ ? "OpenCode database could not be read."632+ : databases.length === 0633+ ? "No OpenCode database files found."634+ : null,
- apps/server/src/usage/usageCursor.ts line 441OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +421,21 @@421+});422+423+const fetchCsvOnce = Effect.fn("usageCursor.fetchCsvOnce")(function* (424+ sessionToken: string,425+ sinceMs: number,426+ untilMs: number,427+) {428+ const httpClient = yield* HttpClient.HttpClient;429+ const url = new URL(EXPORT_CSV_URL);430+ url.searchParams.set("startDate", String(Math.trunc(sinceMs)));431+ url.searchParams.set("endDate", String(Math.trunc(untilMs)));432+ url.searchParams.set("strategy", "tokens");433+434+ return yield* HttpClientRequest.get(url.toString()).pipe(435+ HttpClientRequest.setHeaders({436+ Cookie: `WorkosCursorSessionToken=${sessionToken}`,437+ Accept: "text/csv",438+ }),439+ httpClient.execute,440+ Effect.timeout(30_000),441+ );
Sign in to join this conversation.


Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
cd9eab12-0588-4d11-88d9-b8f056995938You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share