@tokscale/cli 1.4.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. package/dist/index.d.ts +3 -0
  2. package/dist/index.d.ts.map +1 -0
  3. package/dist/index.js +128 -0
  4. package/dist/index.js.map +1 -0
  5. package/package.json +19 -26
  6. package/dist/auth.d.ts +0 -17
  7. package/dist/auth.d.ts.map +0 -1
  8. package/dist/auth.js +0 -162
  9. package/dist/auth.js.map +0 -1
  10. package/dist/cli.d.ts +0 -9
  11. package/dist/cli.d.ts.map +0 -1
  12. package/dist/cli.js +0 -1523
  13. package/dist/cli.js.map +0 -1
  14. package/dist/credentials.d.ts +0 -50
  15. package/dist/credentials.d.ts.map +0 -1
  16. package/dist/credentials.js +0 -151
  17. package/dist/credentials.js.map +0 -1
  18. package/dist/cursor.d.ts +0 -167
  19. package/dist/cursor.d.ts.map +0 -1
  20. package/dist/cursor.js +0 -906
  21. package/dist/cursor.js.map +0 -1
  22. package/dist/date-utils.d.ts +0 -10
  23. package/dist/date-utils.d.ts.map +0 -1
  24. package/dist/date-utils.js +0 -47
  25. package/dist/date-utils.js.map +0 -1
  26. package/dist/graph-types.d.ts +0 -142
  27. package/dist/graph-types.d.ts.map +0 -1
  28. package/dist/graph-types.js +0 -6
  29. package/dist/graph-types.js.map +0 -1
  30. package/dist/native-runner.d.ts +0 -11
  31. package/dist/native-runner.d.ts.map +0 -1
  32. package/dist/native-runner.js +0 -77
  33. package/dist/native-runner.js.map +0 -1
  34. package/dist/native.d.ts +0 -105
  35. package/dist/native.d.ts.map +0 -1
  36. package/dist/native.js +0 -302
  37. package/dist/native.js.map +0 -1
  38. package/dist/sessions/types.d.ts +0 -28
  39. package/dist/sessions/types.d.ts.map +0 -1
  40. package/dist/sessions/types.js +0 -27
  41. package/dist/sessions/types.js.map +0 -1
  42. package/dist/spinner.d.ts +0 -75
  43. package/dist/spinner.d.ts.map +0 -1
  44. package/dist/spinner.js +0 -203
  45. package/dist/spinner.js.map +0 -1
  46. package/dist/submit.d.ts +0 -22
  47. package/dist/submit.d.ts.map +0 -1
  48. package/dist/submit.js +0 -292
  49. package/dist/submit.js.map +0 -1
  50. package/dist/table.d.ts +0 -42
  51. package/dist/table.d.ts.map +0 -1
  52. package/dist/table.js +0 -181
  53. package/dist/table.js.map +0 -1
  54. package/dist/tui/App.d.ts +0 -4
  55. package/dist/tui/App.d.ts.map +0 -1
  56. package/dist/tui/App.js +0 -350
  57. package/dist/tui/App.js.map +0 -1
  58. package/dist/tui/components/BarChart.d.ts +0 -17
  59. package/dist/tui/components/BarChart.d.ts.map +0 -1
  60. package/dist/tui/components/BarChart.js +0 -146
  61. package/dist/tui/components/BarChart.js.map +0 -1
  62. package/dist/tui/components/DailyView.d.ts +0 -13
  63. package/dist/tui/components/DailyView.d.ts.map +0 -1
  64. package/dist/tui/components/DailyView.js +0 -86
  65. package/dist/tui/components/DailyView.js.map +0 -1
  66. package/dist/tui/components/DateBreakdownPanel.d.ts +0 -7
  67. package/dist/tui/components/DateBreakdownPanel.d.ts.map +0 -1
  68. package/dist/tui/components/DateBreakdownPanel.js +0 -36
  69. package/dist/tui/components/DateBreakdownPanel.js.map +0 -1
  70. package/dist/tui/components/Footer.d.ts +0 -28
  71. package/dist/tui/components/Footer.d.ts.map +0 -1
  72. package/dist/tui/components/Footer.js +0 -130
  73. package/dist/tui/components/Footer.js.map +0 -1
  74. package/dist/tui/components/Header.d.ts +0 -9
  75. package/dist/tui/components/Header.d.ts.map +0 -1
  76. package/dist/tui/components/Header.js +0 -20
  77. package/dist/tui/components/Header.js.map +0 -1
  78. package/dist/tui/components/Legend.d.ts +0 -7
  79. package/dist/tui/components/Legend.d.ts.map +0 -1
  80. package/dist/tui/components/Legend.js +0 -16
  81. package/dist/tui/components/Legend.js.map +0 -1
  82. package/dist/tui/components/LoadingSpinner.d.ts +0 -8
  83. package/dist/tui/components/LoadingSpinner.d.ts.map +0 -1
  84. package/dist/tui/components/LoadingSpinner.js +0 -55
  85. package/dist/tui/components/LoadingSpinner.js.map +0 -1
  86. package/dist/tui/components/ModelRow.d.ts +0 -13
  87. package/dist/tui/components/ModelRow.d.ts.map +0 -1
  88. package/dist/tui/components/ModelRow.js +0 -15
  89. package/dist/tui/components/ModelRow.js.map +0 -1
  90. package/dist/tui/components/ModelView.d.ts +0 -13
  91. package/dist/tui/components/ModelView.d.ts.map +0 -1
  92. package/dist/tui/components/ModelView.js +0 -96
  93. package/dist/tui/components/ModelView.js.map +0 -1
  94. package/dist/tui/components/OverviewView.d.ts +0 -14
  95. package/dist/tui/components/OverviewView.d.ts.map +0 -1
  96. package/dist/tui/components/OverviewView.js +0 -65
  97. package/dist/tui/components/OverviewView.js.map +0 -1
  98. package/dist/tui/components/StatsView.d.ts +0 -14
  99. package/dist/tui/components/StatsView.d.ts.map +0 -1
  100. package/dist/tui/components/StatsView.js +0 -102
  101. package/dist/tui/components/StatsView.js.map +0 -1
  102. package/dist/tui/components/TokenBreakdown.d.ts +0 -14
  103. package/dist/tui/components/TokenBreakdown.d.ts.map +0 -1
  104. package/dist/tui/components/TokenBreakdown.js +0 -10
  105. package/dist/tui/components/TokenBreakdown.js.map +0 -1
  106. package/dist/tui/components/index.d.ts +0 -16
  107. package/dist/tui/components/index.d.ts.map +0 -1
  108. package/dist/tui/components/index.js +0 -13
  109. package/dist/tui/components/index.js.map +0 -1
  110. package/dist/tui/config/settings.d.ts +0 -15
  111. package/dist/tui/config/settings.d.ts.map +0 -1
  112. package/dist/tui/config/settings.js +0 -147
  113. package/dist/tui/config/settings.js.map +0 -1
  114. package/dist/tui/config/themes.d.ts +0 -15
  115. package/dist/tui/config/themes.d.ts.map +0 -1
  116. package/dist/tui/config/themes.js +0 -82
  117. package/dist/tui/config/themes.js.map +0 -1
  118. package/dist/tui/hooks/useData.d.ts +0 -19
  119. package/dist/tui/hooks/useData.d.ts.map +0 -1
  120. package/dist/tui/hooks/useData.js +0 -467
  121. package/dist/tui/hooks/useData.js.map +0 -1
  122. package/dist/tui/index.d.ts +0 -4
  123. package/dist/tui/index.d.ts.map +0 -1
  124. package/dist/tui/index.js +0 -36
  125. package/dist/tui/index.js.map +0 -1
  126. package/dist/tui/types/index.d.ts +0 -137
  127. package/dist/tui/types/index.d.ts.map +0 -1
  128. package/dist/tui/types/index.js +0 -25
  129. package/dist/tui/types/index.js.map +0 -1
  130. package/dist/tui/utils/cleanup.d.ts +0 -22
  131. package/dist/tui/utils/cleanup.d.ts.map +0 -1
  132. package/dist/tui/utils/cleanup.js +0 -59
  133. package/dist/tui/utils/cleanup.js.map +0 -1
  134. package/dist/tui/utils/colors.d.ts +0 -19
  135. package/dist/tui/utils/colors.d.ts.map +0 -1
  136. package/dist/tui/utils/colors.js +0 -68
  137. package/dist/tui/utils/colors.js.map +0 -1
  138. package/dist/tui/utils/format.d.ts +0 -7
  139. package/dist/tui/utils/format.d.ts.map +0 -1
  140. package/dist/tui/utils/format.js +0 -45
  141. package/dist/tui/utils/format.js.map +0 -1
  142. package/dist/tui/utils/responsive.d.ts +0 -5
  143. package/dist/tui/utils/responsive.d.ts.map +0 -1
  144. package/dist/tui/utils/responsive.js +0 -5
  145. package/dist/tui/utils/responsive.js.map +0 -1
  146. package/dist/wrapped.d.ts +0 -43
  147. package/dist/wrapped.d.ts.map +0 -1
  148. package/dist/wrapped.js +0 -716
  149. package/dist/wrapped.js.map +0 -1
  150. package/src/auth.ts +0 -211
  151. package/src/cli.ts +0 -1865
  152. package/src/credentials.ts +0 -176
  153. package/src/cursor.ts +0 -1044
  154. package/src/date-utils.ts +0 -51
  155. package/src/graph-types.ts +0 -175
  156. package/src/native-runner.js +0 -4
  157. package/src/native-runner.ts +0 -91
  158. package/src/native.ts +0 -631
  159. package/src/sessions/types.ts +0 -59
  160. package/src/spinner.ts +0 -283
  161. package/src/submit.ts +0 -358
  162. package/src/table.ts +0 -233
  163. package/src/tui/App.tsx +0 -443
  164. package/src/tui/components/BarChart.tsx +0 -205
  165. package/src/tui/components/DailyView.tsx +0 -132
  166. package/src/tui/components/DateBreakdownPanel.tsx +0 -79
  167. package/src/tui/components/Footer.tsx +0 -368
  168. package/src/tui/components/Header.tsx +0 -68
  169. package/src/tui/components/Legend.tsx +0 -39
  170. package/src/tui/components/LoadingSpinner.tsx +0 -81
  171. package/src/tui/components/ModelRow.tsx +0 -47
  172. package/src/tui/components/ModelView.tsx +0 -147
  173. package/src/tui/components/OverviewView.tsx +0 -121
  174. package/src/tui/components/StatsView.tsx +0 -249
  175. package/src/tui/components/TokenBreakdown.tsx +0 -46
  176. package/src/tui/components/index.ts +0 -15
  177. package/src/tui/config/settings.ts +0 -183
  178. package/src/tui/config/themes.ts +0 -115
  179. package/src/tui/hooks/useData.ts +0 -557
  180. package/src/tui/index.tsx +0 -44
  181. package/src/tui/opentui.d.ts +0 -166
  182. package/src/tui/types/index.ts +0 -172
  183. package/src/tui/utils/cleanup.ts +0 -65
  184. package/src/tui/utils/colors.ts +0 -76
  185. package/src/tui/utils/format.ts +0 -36
  186. package/src/tui/utils/responsive.ts +0 -8
  187. package/src/types.d.ts +0 -28
  188. package/src/wrapped.ts +0 -845
package/dist/cursor.js DELETED
@@ -1,906 +0,0 @@
1
- /**
2
- * Cursor IDE API Client
3
- * Fetches usage data from Cursor's dashboard API via CSV export
4
- *
5
- * API Endpoint: https://cursor.com/api/dashboard/export-usage-events-csv?strategy=tokens
6
- * Authentication: WorkosCursorSessionToken cookie
7
- *
8
- * CSV Format:
9
- * Date,Model,Input (w/ Cache Write),Input (w/o Cache Write),Cache Read,Output Tokens,Total Tokens,Cost,Cost to you
10
- */
11
- import * as fs from "node:fs";
12
- import * as path from "node:path";
13
- import * as os from "node:os";
14
- import { createHash } from "node:crypto";
15
- import { parse as parseCsv } from "csv-parse/sync";
16
- // ============================================================================
17
- // Credential Management
18
- // ============================================================================
19
- const OLD_CONFIG_DIR = path.join(os.homedir(), ".tokscale");
20
- const CONFIG_DIR = path.join(os.homedir(), ".config", "tokscale");
21
- const OLD_CURSOR_CREDENTIALS_FILE = path.join(OLD_CONFIG_DIR, "cursor-credentials.json");
22
- const CURSOR_CREDENTIALS_FILE = path.join(CONFIG_DIR, "cursor-credentials.json");
23
- function ensureConfigDir() {
24
- if (!fs.existsSync(CONFIG_DIR)) {
25
- fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
26
- }
27
- }
28
- /**
29
- * Migrate Cursor credentials and cache from old path to new XDG path
30
- */
31
- function migrateCursorFromOldPath() {
32
- try {
33
- // Migrate cursor credentials
34
- if (!fs.existsSync(CURSOR_CREDENTIALS_FILE) && fs.existsSync(OLD_CURSOR_CREDENTIALS_FILE)) {
35
- ensureConfigDir();
36
- fs.copyFileSync(OLD_CURSOR_CREDENTIALS_FILE, CURSOR_CREDENTIALS_FILE);
37
- fs.chmodSync(CURSOR_CREDENTIALS_FILE, 0o600);
38
- fs.unlinkSync(OLD_CURSOR_CREDENTIALS_FILE);
39
- }
40
- // Migrate cache directory (handled after CURSOR_CACHE_DIR is defined)
41
- // Cache migration happens in migrateCursorCacheFromOldPath()
42
- // Try to remove old config directory if empty
43
- try {
44
- fs.rmdirSync(OLD_CONFIG_DIR);
45
- }
46
- catch {
47
- // Directory not empty - ignore
48
- }
49
- }
50
- catch {
51
- // Migration failed - continue with normal operation
52
- }
53
- }
54
- export function ensureCursorMigration() {
55
- // Best-effort: never throw
56
- try {
57
- migrateCursorFromOldPath();
58
- }
59
- catch { }
60
- try {
61
- migrateCursorCacheFromOldPath();
62
- }
63
- catch { }
64
- try {
65
- // Triggers legacy schema -> v1 store migration if needed
66
- loadCursorCredentialsStoreInternal();
67
- }
68
- catch { }
69
- }
70
- function isStoreV1(data) {
71
- if (!data || typeof data !== "object")
72
- return false;
73
- const obj = data;
74
- return obj.version === 1 && typeof obj.activeAccountId === "string" && typeof obj.accounts === "object" && obj.accounts !== null;
75
- }
76
- function extractUserIdFromSessionToken(sessionToken) {
77
- if (!sessionToken)
78
- return null;
79
- const token = sessionToken.trim();
80
- if (token.includes("%3A%3A")) {
81
- const userId = token.split("%3A%3A")[0]?.trim();
82
- return userId ? userId : null;
83
- }
84
- if (token.includes("::")) {
85
- const userId = token.split("::")[0]?.trim();
86
- return userId ? userId : null;
87
- }
88
- return null;
89
- }
90
- function sanitizeAccountIdForFilename(accountId) {
91
- return accountId
92
- .trim()
93
- .toLowerCase()
94
- .replace(/[^a-z0-9._-]+/g, "-")
95
- .replace(/^-+|-+$/g, "")
96
- .slice(0, 80) || "account";
97
- }
98
- function isCursorUsageCsvFilename(fileName) {
99
- if (fileName === "usage.csv")
100
- return true;
101
- if (!fileName.startsWith("usage."))
102
- return false;
103
- if (!fileName.endsWith(".csv"))
104
- return false;
105
- // Exclude legacy backups (were previously written as usage.backup-<ts>.csv)
106
- if (fileName.startsWith("usage.backup"))
107
- return false;
108
- const stem = fileName.slice("usage.".length, -".csv".length);
109
- if (!stem)
110
- return false;
111
- return /^[a-z0-9._-]+$/i.test(stem);
112
- }
113
- function deriveAccountId(sessionToken) {
114
- const userId = extractUserIdFromSessionToken(sessionToken);
115
- if (userId)
116
- return userId;
117
- const hash = createHash("sha256").update(sessionToken).digest("hex").slice(0, 12);
118
- return `anon-${hash}`;
119
- }
120
- function atomicWriteFile(filePath, data, mode) {
121
- const dir = path.dirname(filePath);
122
- const base = path.basename(filePath);
123
- const tmp = path.join(dir, `.${base}.tmp-${process.pid}`);
124
- fs.writeFileSync(tmp, data, { encoding: "utf-8", mode });
125
- try {
126
- fs.renameSync(tmp, filePath);
127
- }
128
- catch {
129
- // Best-effort for platforms where rename over an existing file can fail.
130
- try {
131
- if (fs.existsSync(filePath))
132
- fs.rmSync(filePath);
133
- }
134
- catch {
135
- // ignore
136
- }
137
- fs.renameSync(tmp, filePath);
138
- }
139
- }
140
- function loadCursorCredentialsStoreInternal() {
141
- migrateCursorFromOldPath();
142
- try {
143
- if (!fs.existsSync(CURSOR_CREDENTIALS_FILE))
144
- return null;
145
- const data = fs.readFileSync(CURSOR_CREDENTIALS_FILE, "utf-8");
146
- const parsed = JSON.parse(data);
147
- if (isStoreV1(parsed)) {
148
- const store = parsed;
149
- if (!store.activeAccountId || !store.accounts[store.activeAccountId]) {
150
- const firstId = Object.keys(store.accounts)[0];
151
- if (!firstId)
152
- return null;
153
- store.activeAccountId = firstId;
154
- ensureConfigDir();
155
- atomicWriteFile(CURSOR_CREDENTIALS_FILE, JSON.stringify(store, null, 2), 0o600);
156
- }
157
- return store;
158
- }
159
- // Legacy single-account schema: { sessionToken, createdAt, ... }
160
- if (parsed && typeof parsed === "object") {
161
- const obj = parsed;
162
- const sessionToken = typeof obj.sessionToken === "string" ? obj.sessionToken : "";
163
- if (!sessionToken)
164
- return null;
165
- const accountId = deriveAccountId(sessionToken);
166
- const migrated = {
167
- version: 1,
168
- activeAccountId: accountId,
169
- accounts: {
170
- [accountId]: {
171
- sessionToken,
172
- userId: typeof obj.userId === "string" ? obj.userId : extractUserIdFromSessionToken(sessionToken) || undefined,
173
- createdAt: typeof obj.createdAt === "string" ? obj.createdAt : new Date().toISOString(),
174
- expiresAt: typeof obj.expiresAt === "string" ? obj.expiresAt : undefined,
175
- label: typeof obj.label === "string" ? obj.label : undefined,
176
- },
177
- },
178
- };
179
- ensureConfigDir();
180
- atomicWriteFile(CURSOR_CREDENTIALS_FILE, JSON.stringify(migrated, null, 2), 0o600);
181
- return migrated;
182
- }
183
- return null;
184
- }
185
- catch {
186
- return null;
187
- }
188
- }
189
- function saveCursorCredentialsStoreInternal(store) {
190
- ensureConfigDir();
191
- atomicWriteFile(CURSOR_CREDENTIALS_FILE, JSON.stringify(store, null, 2), 0o600);
192
- }
193
- function resolveAccountId(store, nameOrId) {
194
- const needle = nameOrId.trim();
195
- if (!needle)
196
- return null;
197
- if (store.accounts[needle])
198
- return needle;
199
- const needleLower = needle.toLowerCase();
200
- for (const [id, acct] of Object.entries(store.accounts)) {
201
- if (acct.label && acct.label.toLowerCase() === needleLower)
202
- return id;
203
- }
204
- return null;
205
- }
206
- export function listCursorAccounts() {
207
- const store = loadCursorCredentialsStoreInternal();
208
- if (!store)
209
- return [];
210
- const accounts = Object.entries(store.accounts).map(([id, acct]) => ({
211
- id,
212
- label: acct.label,
213
- userId: acct.userId,
214
- createdAt: acct.createdAt,
215
- isActive: id === store.activeAccountId,
216
- }));
217
- accounts.sort((a, b) => {
218
- if (a.isActive !== b.isActive)
219
- return a.isActive ? -1 : 1;
220
- const la = (a.label || a.id).toLowerCase();
221
- const lb = (b.label || b.id).toLowerCase();
222
- return la.localeCompare(lb);
223
- });
224
- return accounts;
225
- }
226
- export function setActiveCursorAccount(nameOrId) {
227
- const store = loadCursorCredentialsStoreInternal();
228
- if (!store)
229
- return { ok: false, error: "Not authenticated" };
230
- const resolved = resolveAccountId(store, nameOrId);
231
- if (!resolved)
232
- return { ok: false, error: `Account not found: ${nameOrId}` };
233
- const prev = store.activeAccountId;
234
- store.activeAccountId = resolved;
235
- saveCursorCredentialsStoreInternal(store);
236
- // Best-effort cache reconcile (avoid double-counting)
237
- try {
238
- migrateCursorCacheFromOldPath();
239
- ensureCacheDir();
240
- const archiveDir = path.join(CURSOR_CACHE_DIR, "archive");
241
- const ensureArchiveDir = () => {
242
- ensureCacheDir();
243
- if (!fs.existsSync(archiveDir)) {
244
- fs.mkdirSync(archiveDir, { recursive: true, mode: 0o700 });
245
- }
246
- };
247
- const archiveFile = (filePath, label) => {
248
- ensureArchiveDir();
249
- const safeLabel = sanitizeAccountIdForFilename(label);
250
- const ts = new Date().toISOString().replace(/[:.]/g, "-");
251
- const dest = path.join(archiveDir, `${safeLabel}-${ts}.csv`);
252
- fs.renameSync(filePath, dest);
253
- };
254
- // Move current active cache to previous account file (preserve any existing file by archiving).
255
- if (prev && fs.existsSync(CURSOR_CACHE_FILE)) {
256
- const prevFile = getCursorCacheFilePathForAccount(prev, false);
257
- if (fs.existsSync(prevFile)) {
258
- try {
259
- archiveFile(prevFile, `usage.${prev}.previous`);
260
- }
261
- catch {
262
- // ignore
263
- }
264
- }
265
- try {
266
- fs.renameSync(CURSOR_CACHE_FILE, prevFile);
267
- }
268
- catch {
269
- // ignore
270
- }
271
- }
272
- // Promote next account cache file into usage.csv.
273
- const nextFile = getCursorCacheFilePathForAccount(resolved, false);
274
- if (fs.existsSync(nextFile)) {
275
- if (fs.existsSync(CURSOR_CACHE_FILE)) {
276
- try {
277
- archiveFile(CURSOR_CACHE_FILE, `usage.active.pre-switch`);
278
- }
279
- catch {
280
- // ignore
281
- }
282
- }
283
- try {
284
- fs.renameSync(nextFile, CURSOR_CACHE_FILE);
285
- }
286
- catch {
287
- // ignore
288
- }
289
- }
290
- // If a per-account cache exists, it was promoted into usage.csv above.
291
- }
292
- catch {
293
- // ignore cache reconcile errors
294
- }
295
- return { ok: true };
296
- }
297
- export function saveCursorCredentials(credentials, options) {
298
- const sessionToken = credentials.sessionToken;
299
- const accountId = deriveAccountId(sessionToken);
300
- const store = loadCursorCredentialsStoreInternal() || {
301
- version: 1,
302
- activeAccountId: accountId,
303
- accounts: {},
304
- };
305
- if (options?.label) {
306
- const needle = options.label.trim().toLowerCase();
307
- if (needle) {
308
- for (const [id, acct] of Object.entries(store.accounts)) {
309
- if (id === accountId)
310
- continue;
311
- if (acct.label && acct.label.trim().toLowerCase() === needle) {
312
- throw new Error(`Cursor account label already exists: ${options.label}`);
313
- }
314
- }
315
- }
316
- }
317
- const next = {
318
- ...credentials,
319
- userId: credentials.userId || extractUserIdFromSessionToken(sessionToken) || undefined,
320
- label: options?.label ?? credentials.label,
321
- };
322
- store.accounts[accountId] = next;
323
- if (options?.setActive !== false) {
324
- store.activeAccountId = accountId;
325
- }
326
- saveCursorCredentialsStoreInternal(store);
327
- return { accountId };
328
- }
329
- export function loadCursorCredentials(nameOrId) {
330
- const store = loadCursorCredentialsStoreInternal();
331
- if (!store)
332
- return null;
333
- if (nameOrId) {
334
- const resolved = resolveAccountId(store, nameOrId);
335
- return resolved ? store.accounts[resolved] : null;
336
- }
337
- return store.accounts[store.activeAccountId] || null;
338
- }
339
- export function loadCursorCredentialsStore() {
340
- return loadCursorCredentialsStoreInternal();
341
- }
342
- // NOTE: implementation moved below to support cache archiving by default.
343
- export function removeCursorAccount(nameOrId, options) {
344
- const store = loadCursorCredentialsStoreInternal();
345
- if (!store)
346
- return { removed: false, error: "Not authenticated" };
347
- const resolved = resolveAccountId(store, nameOrId);
348
- if (!resolved)
349
- return { removed: false, error: `Account not found: ${nameOrId}` };
350
- const wasActive = resolved === store.activeAccountId;
351
- // Cache behavior:
352
- // - Default: keep history but remove from aggregation by archiving out of cursor-cache/.
353
- // - purgeCache: delete cache files.
354
- const CURSOR_CACHE_ARCHIVE_DIR = path.join(CURSOR_CACHE_DIR, "archive");
355
- const ensureCacheArchiveDir = () => {
356
- ensureCacheDir();
357
- if (!fs.existsSync(CURSOR_CACHE_ARCHIVE_DIR)) {
358
- fs.mkdirSync(CURSOR_CACHE_ARCHIVE_DIR, { recursive: true, mode: 0o700 });
359
- }
360
- };
361
- const archiveFile = (filePath, label) => {
362
- ensureCacheArchiveDir();
363
- const safeLabel = sanitizeAccountIdForFilename(label);
364
- const ts = new Date().toISOString().replace(/[:.]/g, "-");
365
- const dest = path.join(CURSOR_CACHE_ARCHIVE_DIR, `${safeLabel}-${ts}.csv`);
366
- fs.renameSync(filePath, dest);
367
- };
368
- try {
369
- migrateCursorCacheFromOldPath();
370
- if (fs.existsSync(CURSOR_CACHE_DIR)) {
371
- const perAccount = getCursorCacheFilePathForAccount(resolved, false);
372
- if (fs.existsSync(perAccount)) {
373
- if (options?.purgeCache) {
374
- fs.rmSync(perAccount);
375
- }
376
- else {
377
- archiveFile(perAccount, `usage.${resolved}`);
378
- }
379
- }
380
- if (wasActive && fs.existsSync(CURSOR_CACHE_FILE)) {
381
- if (options?.purgeCache) {
382
- fs.rmSync(CURSOR_CACHE_FILE);
383
- }
384
- else {
385
- archiveFile(CURSOR_CACHE_FILE, `usage.active.${resolved}`);
386
- }
387
- }
388
- }
389
- }
390
- catch {
391
- // ignore
392
- }
393
- delete store.accounts[resolved];
394
- const remaining = Object.keys(store.accounts);
395
- if (remaining.length === 0) {
396
- try {
397
- fs.unlinkSync(CURSOR_CREDENTIALS_FILE);
398
- }
399
- catch { }
400
- return { removed: true };
401
- }
402
- if (wasActive) {
403
- store.activeAccountId = remaining[0];
404
- }
405
- saveCursorCredentialsStoreInternal(store);
406
- if (wasActive) {
407
- // Best-effort: reconcile usage.csv for the new active account.
408
- try {
409
- migrateCursorCacheFromOldPath();
410
- ensureCacheDir();
411
- const nextId = store.activeAccountId;
412
- const nextFile = getCursorCacheFilePathForAccount(nextId, false);
413
- if (fs.existsSync(nextFile)) {
414
- if (fs.existsSync(CURSOR_CACHE_FILE)) {
415
- try {
416
- fs.rmSync(CURSOR_CACHE_FILE);
417
- }
418
- catch { }
419
- }
420
- fs.renameSync(nextFile, CURSOR_CACHE_FILE);
421
- }
422
- // If nextFile existed, it was promoted into usage.csv above.
423
- }
424
- catch {
425
- // ignore
426
- }
427
- }
428
- return { removed: true };
429
- }
430
- export function clearCursorCredentials() {
431
- // Backward compatible: clears ALL accounts
432
- try {
433
- if (fs.existsSync(CURSOR_CREDENTIALS_FILE)) {
434
- fs.unlinkSync(CURSOR_CREDENTIALS_FILE);
435
- return true;
436
- }
437
- return false;
438
- }
439
- catch {
440
- return false;
441
- }
442
- }
443
- export function clearCursorCredentialsAndCache(options) {
444
- const cleared = clearCursorCredentials();
445
- if (!cleared)
446
- return false;
447
- try {
448
- migrateCursorCacheFromOldPath();
449
- if (!fs.existsSync(CURSOR_CACHE_DIR))
450
- return true;
451
- const archiveDir = path.join(CURSOR_CACHE_DIR, "archive");
452
- const ensureArchiveDir = () => {
453
- ensureCacheDir();
454
- if (!fs.existsSync(archiveDir)) {
455
- fs.mkdirSync(archiveDir, { recursive: true, mode: 0o700 });
456
- }
457
- };
458
- const archiveFile = (filePath, label) => {
459
- ensureArchiveDir();
460
- const safeLabel = sanitizeAccountIdForFilename(label);
461
- const ts = new Date().toISOString().replace(/[:.]/g, "-");
462
- const dest = path.join(archiveDir, `${safeLabel}-${ts}.csv`);
463
- fs.renameSync(filePath, dest);
464
- };
465
- for (const f of fs.readdirSync(CURSOR_CACHE_DIR)) {
466
- if (!f.startsWith("usage") || !f.endsWith(".csv"))
467
- continue;
468
- const filePath = path.join(CURSOR_CACHE_DIR, f);
469
- try {
470
- if (options?.purgeCache) {
471
- fs.rmSync(filePath);
472
- }
473
- else {
474
- archiveFile(filePath, `usage.all.${f}`);
475
- }
476
- }
477
- catch { }
478
- }
479
- }
480
- catch {
481
- // ignore
482
- }
483
- return true;
484
- }
485
- export function isCursorLoggedIn() {
486
- const store = loadCursorCredentialsStoreInternal();
487
- return !!store && Object.keys(store.accounts).length > 0;
488
- }
489
- // ============================================================================
490
- // API Client
491
- // ============================================================================
492
- const CURSOR_API_BASE = "https://cursor.com";
493
- const USAGE_CSV_ENDPOINT = `${CURSOR_API_BASE}/api/dashboard/export-usage-events-csv?strategy=tokens`;
494
- const USAGE_SUMMARY_ENDPOINT = `${CURSOR_API_BASE}/api/usage-summary`;
495
- /**
496
- * Build HTTP headers for Cursor API requests
497
- */
498
- function buildCursorHeaders(sessionToken) {
499
- return {
500
- Accept: "*/*",
501
- "Accept-Language": "en-US,en;q=0.9",
502
- Cookie: `WorkosCursorSessionToken=${sessionToken}`,
503
- Referer: "https://www.cursor.com/settings",
504
- "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
505
- };
506
- }
507
- /**
508
- * Validate Cursor session token by hitting the usage-summary endpoint
509
- */
510
- export async function validateCursorSession(sessionToken) {
511
- try {
512
- const response = await fetch(USAGE_SUMMARY_ENDPOINT, {
513
- method: "GET",
514
- headers: buildCursorHeaders(sessionToken),
515
- });
516
- if (response.status === 401 || response.status === 403) {
517
- return { valid: false, error: "Session token expired or invalid" };
518
- }
519
- if (!response.ok) {
520
- return { valid: false, error: `API returned status ${response.status}` };
521
- }
522
- const data = await response.json();
523
- // Check for required fields that indicate valid auth
524
- if (data.billingCycleStart && data.billingCycleEnd) {
525
- return { valid: true, membershipType: data.membershipType };
526
- }
527
- return { valid: false, error: "Invalid response format" };
528
- }
529
- catch (error) {
530
- return { valid: false, error: error.message };
531
- }
532
- }
533
- /**
534
- * Fetch usage CSV from Cursor API
535
- */
536
- export async function fetchCursorUsageCsv(sessionToken) {
537
- const response = await fetch(USAGE_CSV_ENDPOINT, {
538
- method: "GET",
539
- headers: buildCursorHeaders(sessionToken),
540
- });
541
- if (response.status === 401 || response.status === 403) {
542
- throw new Error("Cursor session expired. Please run 'tokscale cursor login' to re-authenticate.");
543
- }
544
- if (!response.ok) {
545
- throw new Error(`Cursor API returned status ${response.status}`);
546
- }
547
- const text = await response.text();
548
- // Validate it's actually CSV (handle both old and new formats)
549
- // Old: "Date,Model,..."
550
- // New: "Date,Kind,Model,..."
551
- if (!text.startsWith("Date,")) {
552
- throw new Error("Invalid response from Cursor API - expected CSV format");
553
- }
554
- return text;
555
- }
556
- // ============================================================================
557
- // CSV Parsing
558
- // ============================================================================
559
- /**
560
- * Parse cost string (e.g., "$0.50" or "0.50") to number
561
- */
562
- function parseCost(costStr) {
563
- if (!costStr)
564
- return 0;
565
- const cleaned = costStr.replace(/[$,]/g, "").trim();
566
- const value = parseFloat(cleaned);
567
- return isNaN(value) ? 0 : value;
568
- }
569
- /**
570
- * Infer provider from model name
571
- */
572
- function inferProvider(model) {
573
- const lowerModel = model.toLowerCase();
574
- if (lowerModel.includes("claude") || lowerModel.includes("sonnet") || lowerModel.includes("opus") || lowerModel.includes("haiku")) {
575
- return "anthropic";
576
- }
577
- if (lowerModel.includes("gpt") || lowerModel.includes("o1") || lowerModel.includes("o3")) {
578
- return "openai";
579
- }
580
- if (lowerModel.includes("gemini")) {
581
- return "google";
582
- }
583
- if (lowerModel.includes("deepseek")) {
584
- return "deepseek";
585
- }
586
- if (lowerModel.includes("llama") || lowerModel.includes("mixtral")) {
587
- return "meta";
588
- }
589
- return "cursor"; // Default provider
590
- }
591
- /**
592
- * Parse Cursor usage CSV into structured rows
593
- */
594
- export function parseCursorCsv(csvText) {
595
- try {
596
- const records = parseCsv(csvText, {
597
- columns: true,
598
- skip_empty_lines: true,
599
- trim: true,
600
- relax_column_count: true,
601
- });
602
- return records
603
- .filter((record) => record["Date"] && record["Model"])
604
- .map((record) => {
605
- const dateStr = record["Date"] || "";
606
- const date = new Date(dateStr);
607
- const isValidDate = !isNaN(date.getTime());
608
- const dateOnly = isValidDate
609
- ? date.toISOString().slice(0, 10)
610
- : dateStr.length >= 10
611
- ? dateStr.slice(0, 10)
612
- : dateStr;
613
- return {
614
- date: dateOnly,
615
- timestamp: isValidDate ? date.getTime() : 0,
616
- model: (record["Model"] || "").trim(),
617
- inputWithCacheWrite: parseInt(record["Input (w/ Cache Write)"] || "0", 10),
618
- inputWithoutCacheWrite: parseInt(record["Input (w/o Cache Write)"] || "0", 10),
619
- cacheRead: parseInt(record["Cache Read"] || "0", 10),
620
- outputTokens: parseInt(record["Output Tokens"] || "0", 10),
621
- totalTokens: parseInt(record["Total Tokens"] || "0", 10),
622
- apiCost: parseCost(record["Cost"] || record["API Cost"] || "0"),
623
- costToYou: parseCost(record["Cost to you"] || "0"),
624
- };
625
- });
626
- }
627
- catch (error) {
628
- throw new Error(`Failed to parse Cursor CSV: ${error.message}`);
629
- }
630
- }
631
- // ============================================================================
632
- // Data Aggregation (for table display)
633
- // ============================================================================
634
- /**
635
- * Aggregate Cursor usage by model
636
- */
637
- export function aggregateCursorByModel(rows) {
638
- const modelMap = new Map();
639
- for (const row of rows) {
640
- const key = row.model;
641
- const existing = modelMap.get(key);
642
- // Cache write = inputWithCacheWrite - inputWithoutCacheWrite (tokens written to cache)
643
- const cacheWrite = Math.max(0, row.inputWithCacheWrite - row.inputWithoutCacheWrite);
644
- // Input tokens (without cache) = inputWithoutCacheWrite
645
- const input = row.inputWithoutCacheWrite;
646
- if (existing) {
647
- existing.messageCount += 1;
648
- existing.input += input;
649
- existing.output += row.outputTokens;
650
- existing.cacheRead += row.cacheRead;
651
- existing.cacheWrite += cacheWrite;
652
- existing.cost += row.costToYou || row.apiCost;
653
- }
654
- else {
655
- modelMap.set(key, {
656
- source: "cursor",
657
- model: row.model,
658
- providerId: inferProvider(row.model),
659
- messageCount: 1,
660
- input,
661
- output: row.outputTokens,
662
- cacheRead: row.cacheRead,
663
- cacheWrite,
664
- reasoning: 0, // Cursor doesn't expose reasoning tokens
665
- cost: row.costToYou || row.apiCost,
666
- });
667
- }
668
- }
669
- return Array.from(modelMap.values()).sort((a, b) => b.cost - a.cost);
670
- }
671
- // ============================================================================
672
- // Data Conversion (for graph/native module)
673
- // ============================================================================
674
- /**
675
- * Convert Cursor CSV rows to timestamped messages for graph generation
676
- */
677
- export function cursorRowsToMessages(rows) {
678
- return rows.map((row) => {
679
- const cacheWrite = Math.max(0, row.inputWithCacheWrite - row.inputWithoutCacheWrite);
680
- const input = row.inputWithoutCacheWrite;
681
- return {
682
- source: "cursor",
683
- model: row.model,
684
- providerId: inferProvider(row.model),
685
- timestamp: row.timestamp,
686
- input,
687
- output: row.outputTokens,
688
- cacheRead: row.cacheRead,
689
- cacheWrite,
690
- reasoning: 0,
691
- cost: row.costToYou || row.apiCost,
692
- };
693
- });
694
- }
695
- // ============================================================================
696
- // High-Level API
697
- // ============================================================================
698
- /**
699
- * Fetch and parse Cursor usage data
700
- * Requires valid credentials to be stored
701
- */
702
- export async function readCursorUsage(nameOrId) {
703
- const credentials = loadCursorCredentials(nameOrId);
704
- if (!credentials) {
705
- throw new Error("Cursor not authenticated. Run 'tokscale cursor login' first.");
706
- }
707
- const csvText = await fetchCursorUsageCsv(credentials.sessionToken);
708
- const rows = parseCursorCsv(csvText);
709
- const byModel = aggregateCursorByModel(rows);
710
- const messages = cursorRowsToMessages(rows);
711
- return { rows, byModel, messages };
712
- }
713
- /**
714
- * Get Cursor credentials file path (for debugging)
715
- */
716
- export function getCursorCredentialsPath() {
717
- return CURSOR_CREDENTIALS_FILE;
718
- }
719
- // ============================================================================
720
- // Cache Management (for Rust integration)
721
- // ============================================================================
722
- const OLD_CURSOR_CACHE_DIR = path.join(os.homedir(), ".tokscale", "cursor-cache");
723
- const CURSOR_CACHE_DIR = path.join(CONFIG_DIR, "cursor-cache");
724
- const CURSOR_CACHE_FILE = path.join(CURSOR_CACHE_DIR, "usage.csv");
725
- function getCursorCacheFilePathForAccount(accountId, isActive) {
726
- if (isActive)
727
- return CURSOR_CACHE_FILE;
728
- const safe = sanitizeAccountIdForFilename(accountId);
729
- return path.join(CURSOR_CACHE_DIR, `usage.${safe}.csv`);
730
- }
731
- function ensureCacheDir() {
732
- if (!fs.existsSync(CURSOR_CACHE_DIR)) {
733
- fs.mkdirSync(CURSOR_CACHE_DIR, { recursive: true, mode: 0o700 });
734
- }
735
- }
736
- /**
737
- * Migrate cursor cache from old path to new XDG path
738
- */
739
- function migrateCursorCacheFromOldPath() {
740
- try {
741
- if (!fs.existsSync(CURSOR_CACHE_DIR) && fs.existsSync(OLD_CURSOR_CACHE_DIR)) {
742
- ensureCacheDir();
743
- fs.cpSync(OLD_CURSOR_CACHE_DIR, CURSOR_CACHE_DIR, { recursive: true });
744
- fs.rmSync(OLD_CURSOR_CACHE_DIR, { recursive: true });
745
- }
746
- // Try to remove old config directory if empty
747
- try {
748
- fs.rmdirSync(OLD_CONFIG_DIR);
749
- }
750
- catch {
751
- // Directory not empty - ignore
752
- }
753
- }
754
- catch {
755
- // Migration failed - continue with normal operation
756
- }
757
- }
758
- /**
759
- * Sync Cursor usage data from API to local cache
760
- * This downloads the CSV and saves it for the Rust module to parse
761
- */
762
- export async function syncCursorCache() {
763
- migrateCursorCacheFromOldPath();
764
- const store = loadCursorCredentialsStoreInternal();
765
- if (!store)
766
- return { synced: false, rows: 0, error: "Not authenticated" };
767
- const accounts = Object.entries(store.accounts);
768
- if (accounts.length === 0)
769
- return { synced: false, rows: 0, error: "Not authenticated" };
770
- try {
771
- ensureCacheDir();
772
- // Ensure we don't double-count active account (usage.csv + usage.<active>.csv)
773
- const activeId = store.activeAccountId;
774
- if (activeId) {
775
- const dup = getCursorCacheFilePathForAccount(activeId, false);
776
- if (fs.existsSync(dup)) {
777
- try {
778
- fs.rmSync(dup);
779
- }
780
- catch { }
781
- }
782
- }
783
- let totalRows = 0;
784
- let successCount = 0;
785
- const errors = [];
786
- for (const [accountId, credentials] of accounts) {
787
- const isActive = accountId === store.activeAccountId;
788
- try {
789
- const csvText = await fetchCursorUsageCsv(credentials.sessionToken);
790
- const filePath = getCursorCacheFilePathForAccount(accountId, isActive);
791
- atomicWriteFile(filePath, csvText, 0o600);
792
- totalRows += parseCursorCsv(csvText).length;
793
- successCount += 1;
794
- }
795
- catch (e) {
796
- errors.push(`${accountId}: ${e.message}`);
797
- }
798
- }
799
- if (successCount === 0) {
800
- return { synced: false, rows: 0, error: errors[0] || "Cursor sync failed" };
801
- }
802
- return {
803
- synced: true,
804
- rows: totalRows,
805
- error: errors.length > 0 ? `Some accounts failed to sync (${errors.length}/${accounts.length})` : undefined,
806
- };
807
- }
808
- catch (error) {
809
- return { synced: false, rows: 0, error: error.message };
810
- }
811
- }
812
- /**
813
- * Get the cache file path
814
- */
815
- export function getCursorCachePath() {
816
- // Ensure legacy cache is migrated before reporting paths
817
- migrateCursorCacheFromOldPath();
818
- return CURSOR_CACHE_FILE;
819
- }
820
- /**
821
- * Check if cache exists and when it was last updated
822
- */
823
- export function getCursorCacheStatus() {
824
- migrateCursorCacheFromOldPath();
825
- const exists = fs.existsSync(CURSOR_CACHE_FILE);
826
- let lastModified;
827
- if (exists) {
828
- try {
829
- const stats = fs.statSync(CURSOR_CACHE_FILE);
830
- lastModified = stats.mtime;
831
- }
832
- catch {
833
- // Ignore stat errors
834
- }
835
- }
836
- return { exists, lastModified, path: CURSOR_CACHE_FILE };
837
- }
838
- export function hasCursorUsageCache() {
839
- migrateCursorCacheFromOldPath();
840
- try {
841
- if (!fs.existsSync(CURSOR_CACHE_DIR))
842
- return false;
843
- const files = fs.readdirSync(CURSOR_CACHE_DIR);
844
- return files.some((f) => isCursorUsageCsvFilename(f));
845
- }
846
- catch {
847
- return false;
848
- }
849
- }
850
- export function readCursorMessagesFromCache() {
851
- migrateCursorCacheFromOldPath();
852
- if (!fs.existsSync(CURSOR_CACHE_DIR)) {
853
- return [];
854
- }
855
- let files;
856
- try {
857
- files = fs
858
- .readdirSync(CURSOR_CACHE_DIR)
859
- .filter((f) => isCursorUsageCsvFilename(f));
860
- }
861
- catch {
862
- return [];
863
- }
864
- const store = loadCursorCredentialsStoreInternal();
865
- const activeId = store?.activeAccountId;
866
- const all = [];
867
- for (const file of files) {
868
- const filePath = path.join(CURSOR_CACHE_DIR, file);
869
- let accountId = "unknown";
870
- if (file === "usage.csv") {
871
- accountId = activeId || "active";
872
- }
873
- else if (file.startsWith("usage.") && file.endsWith(".csv")) {
874
- accountId = file.slice("usage.".length, -".csv".length);
875
- }
876
- try {
877
- const csvText = fs.readFileSync(filePath, "utf-8");
878
- const rows = parseCursorCsv(csvText);
879
- for (const row of rows) {
880
- const cacheWrite = Math.max(0, row.inputWithCacheWrite - row.inputWithoutCacheWrite);
881
- const input = row.inputWithoutCacheWrite;
882
- all.push({
883
- source: "cursor",
884
- modelId: row.model,
885
- providerId: inferProvider(row.model),
886
- sessionId: `cursor-${accountId}-${row.date}-${row.model}`,
887
- timestamp: row.timestamp,
888
- date: row.date,
889
- tokens: {
890
- input,
891
- output: row.outputTokens,
892
- cacheRead: row.cacheRead,
893
- cacheWrite,
894
- reasoning: 0,
895
- },
896
- cost: row.costToYou || row.apiCost,
897
- });
898
- }
899
- }
900
- catch {
901
- // ignore file
902
- }
903
- }
904
- return all;
905
- }
906
- //# sourceMappingURL=cursor.js.map