@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/cli.js DELETED
@@ -1,1523 +0,0 @@
1
- #!/usr/bin/env bun
2
- /**
3
- * Tokscale CLI
4
- * Display OpenCode, Claude Code, Codex, Gemini, and Cursor usage with dynamic width tables
5
- *
6
- * All heavy computation is done in the native Rust module.
7
- */
8
- import { Command, Option } from "commander";
9
- import { createRequire } from "module";
10
- const require = createRequire(import.meta.url);
11
- const pkg = require("../package.json");
12
- import pc from "picocolors";
13
- import { login, logout, whoami } from "./auth.js";
14
- import { submit } from "./submit.js";
15
- import { generateWrapped } from "./wrapped.js";
16
- import { ensureCursorMigration, loadCursorCredentials, saveCursorCredentials, clearCursorCredentialsAndCache, isCursorLoggedIn, hasCursorUsageCache, listCursorAccounts, setActiveCursorAccount, removeCursorAccount, validateCursorSession, readCursorUsage, getCursorCredentialsPath, syncCursorCache, } from "./cursor.js";
17
- import { createUsageTable, formatUsageRow, formatTotalsRow, formatNumber, formatCurrency, formatModelName, } from "./table.js";
18
- import { getNativeVersion, parseLocalSourcesAsync, finalizeReportAsync, finalizeMonthlyReportAsync, finalizeGraphAsync, } from "./native.js";
19
- import { createSpinner } from "./spinner.js";
20
- import { spawn } from "node:child_process";
21
- import { randomUUID } from "node:crypto";
22
- import * as fs from "node:fs";
23
- import * as os from "node:os";
24
- import * as path from "node:path";
25
- import { performance } from "node:perf_hooks";
26
- import { loadSettings } from "./tui/config/settings.js";
27
- import { parseDateStringToLocal, getStartOfDayTimestamp, getEndOfDayTimestamp, validateTimestampMs } from "./date-utils.js";
28
- let cachedTUILoader = null;
29
- let tuiLoadAttempted = false;
30
- async function tryLoadTUI() {
31
- if (tuiLoadAttempted)
32
- return cachedTUILoader;
33
- tuiLoadAttempted = true;
34
- const isBun = typeof globalThis.Bun !== "undefined";
35
- if (!isBun) {
36
- return null;
37
- }
38
- try {
39
- // Load OpenTUI preload to register Babel transform for TSX
40
- // This is needed for both dev mode (via bunfig.toml) and production
41
- // Use variable to prevent TypeScript from analyzing the module
42
- const preloadModule = "@opentui/solid/preload";
43
- await import(preloadModule);
44
- // Always load from source TSX - OpenTUI only works with Bun + preload
45
- // Calculate path to src/tui/index.tsx regardless of whether running from src or dist
46
- const currentPath = new URL(".", import.meta.url).pathname;
47
- const isFromDist = currentPath.includes("/dist/");
48
- const tuiPath = isFromDist
49
- ? new URL("../src/tui/index.tsx", import.meta.url).href
50
- : new URL("./tui/index.tsx", import.meta.url).href;
51
- const tuiModule = await import(tuiPath);
52
- cachedTUILoader = tuiModule.launchTUI;
53
- return cachedTUILoader;
54
- }
55
- catch (error) {
56
- if (process.env.DEBUG) {
57
- console.error("TUI load error:", error);
58
- }
59
- return null;
60
- }
61
- }
62
- function showTUIUnavailableMessage() {
63
- console.log(pc.yellow("\n TUI mode requires Bun runtime."));
64
- console.log(pc.gray(" OpenTUI's native modules are not compatible with Node.js."));
65
- console.log();
66
- console.log(pc.white(" Options:"));
67
- console.log(pc.gray(" • Use 'bunx tokscale' instead of 'npx tokscale'"));
68
- // console.log(pc.gray(" • Use '--light' flag for legacy CLI table output"));
69
- console.log(pc.gray(" • Use '--json' flag for JSON output"));
70
- console.log();
71
- }
72
- function getDateFilters(options) {
73
- const today = new Date();
74
- if (options.today) {
75
- let sinceTs = getStartOfDayTimestamp(today);
76
- let untilTs = getEndOfDayTimestamp(today);
77
- sinceTs = validateTimestampMs(sinceTs, '--today (since)');
78
- untilTs = validateTimestampMs(untilTs, '--today (until)');
79
- return {
80
- sinceTs,
81
- untilTs,
82
- };
83
- }
84
- if (options.week) {
85
- const weekAgo = new Date(today);
86
- weekAgo.setDate(weekAgo.getDate() - 6);
87
- let sinceTs = getStartOfDayTimestamp(weekAgo);
88
- let untilTs = getEndOfDayTimestamp(today);
89
- sinceTs = validateTimestampMs(sinceTs, '--week (since)');
90
- untilTs = validateTimestampMs(untilTs, '--week (until)');
91
- return {
92
- sinceTs,
93
- untilTs,
94
- };
95
- }
96
- if (options.month) {
97
- const startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
98
- let sinceTs = getStartOfDayTimestamp(startOfMonth);
99
- let untilTs = getEndOfDayTimestamp(today);
100
- sinceTs = validateTimestampMs(sinceTs, '--month (since)');
101
- untilTs = validateTimestampMs(untilTs, '--month (until)');
102
- return {
103
- sinceTs,
104
- untilTs,
105
- };
106
- }
107
- if (options.since || options.until) {
108
- let sinceTs;
109
- let untilTs;
110
- if (options.since) {
111
- const sinceDate = parseDateStringToLocal(options.since);
112
- if (!sinceDate) {
113
- console.error(pc.red(`\n Error: Invalid --since date '${options.since}'. Use YYYY-MM-DD format with valid date.\n`));
114
- process.exit(1);
115
- }
116
- sinceTs = getStartOfDayTimestamp(sinceDate);
117
- sinceTs = validateTimestampMs(sinceTs, '--since');
118
- }
119
- if (options.until) {
120
- const untilDate = parseDateStringToLocal(options.until);
121
- if (!untilDate) {
122
- console.error(pc.red(`\n Error: Invalid --until date '${options.until}'. Use YYYY-MM-DD format with valid date.\n`));
123
- process.exit(1);
124
- }
125
- untilTs = getEndOfDayTimestamp(untilDate);
126
- untilTs = validateTimestampMs(untilTs, '--until');
127
- }
128
- if (sinceTs !== undefined && untilTs !== undefined && sinceTs > untilTs) {
129
- console.error(pc.red(`\n Error: --since date must be before --until date.\n`));
130
- process.exit(1);
131
- }
132
- return {
133
- since: options.since,
134
- until: options.until,
135
- year: options.year,
136
- sinceTs,
137
- untilTs,
138
- };
139
- }
140
- return {
141
- year: options.year,
142
- };
143
- }
144
- function getDateRangeLabel(options) {
145
- if (options.today)
146
- return "Today";
147
- if (options.week)
148
- return "Last 7 days";
149
- if (options.month) {
150
- const today = new Date();
151
- return today.toLocaleString("en-US", { month: "long", year: "numeric" });
152
- }
153
- if (options.year)
154
- return options.year;
155
- if (options.since || options.until) {
156
- const parts = [];
157
- if (options.since)
158
- parts.push(`from ${options.since}`);
159
- if (options.until)
160
- parts.push(`to ${options.until}`);
161
- return parts.join(" ");
162
- }
163
- return null;
164
- }
165
- function getHeadlessRoots(homeDir) {
166
- const override = process.env.TOKSCALE_HEADLESS_DIR;
167
- if (override && override.trim()) {
168
- return [override];
169
- }
170
- const roots = [
171
- path.join(homeDir, ".config", "tokscale", "headless"),
172
- path.join(homeDir, "Library", "Application Support", "tokscale", "headless"),
173
- ];
174
- return Array.from(new Set(roots));
175
- }
176
- function describePath(targetPath) {
177
- return fs.existsSync(targetPath) ? targetPath : `${targetPath} (missing)`;
178
- }
179
- const HEADLESS_SOURCES = ["codex"];
180
- function normalizeHeadlessSource(source) {
181
- const normalized = source.toLowerCase();
182
- return HEADLESS_SOURCES.includes(normalized)
183
- ? normalized
184
- : null;
185
- }
186
- function resolveHeadlessFormat(source, args, override) {
187
- if (override === "json" || override === "jsonl") {
188
- return override;
189
- }
190
- return "jsonl";
191
- }
192
- function applyHeadlessDefaults(source, args, format, autoFlags) {
193
- if (!autoFlags)
194
- return args;
195
- const updated = [...args];
196
- if (source === "codex" && !updated.includes("--json")) {
197
- updated.push("--json");
198
- }
199
- return updated;
200
- }
201
- function buildHeadlessOutputPath(headlessRoots, source, format, outputPath) {
202
- if (outputPath) {
203
- fs.mkdirSync(path.dirname(outputPath), { recursive: true });
204
- return outputPath;
205
- }
206
- const root = headlessRoots[0] || path.join(os.homedir(), ".config", "tokscale", "headless");
207
- const dir = path.join(root, source);
208
- fs.mkdirSync(dir, { recursive: true });
209
- const stamp = new Date().toISOString().replace(/[:.]/g, "-");
210
- const id = randomUUID().replace(/-/g, "").slice(0, 8);
211
- const filename = `${source}-${stamp}-${id}.${format}`;
212
- return path.join(dir, filename);
213
- }
214
- function printHeadlessHelp() {
215
- console.log("\n Usage: tokscale headless codex [args...]");
216
- console.log(" Options:");
217
- console.log(" --format <json|jsonl> Override output format");
218
- console.log(" --output <file> Write captured output to file");
219
- console.log(" --no-auto-flags Do not auto-add JSON output flags");
220
- console.log("\n Examples:");
221
- console.log(" tokscale headless codex exec -m gpt-5");
222
- console.log();
223
- }
224
- async function runHeadlessCapture(argv) {
225
- const sourceArg = argv[1];
226
- if (!sourceArg || sourceArg === "--help" || sourceArg === "-h") {
227
- printHeadlessHelp();
228
- return;
229
- }
230
- const source = normalizeHeadlessSource(sourceArg);
231
- if (!source) {
232
- console.error(`\n Error: Unknown headless source '${sourceArg}'.`);
233
- printHeadlessHelp();
234
- process.exit(1);
235
- }
236
- const rawArgs = argv.slice(2);
237
- let outputPath;
238
- let formatOverride;
239
- let autoFlags = true;
240
- const cmdArgs = [];
241
- for (let i = 0; i < rawArgs.length; i += 1) {
242
- const arg = rawArgs[i];
243
- if (arg === "--")
244
- continue;
245
- if ((arg === "--help" || arg === "-h") && cmdArgs.length === 0) {
246
- printHeadlessHelp();
247
- return;
248
- }
249
- if (arg === "--output") {
250
- const value = rawArgs[i + 1];
251
- if (!value) {
252
- console.error("\n Error: --output requires a file path.");
253
- process.exit(1);
254
- }
255
- outputPath = value;
256
- i += 1;
257
- continue;
258
- }
259
- if (arg === "--format") {
260
- const format = rawArgs[i + 1];
261
- if (!format) {
262
- console.error("\n Error: --format requires a value (json or jsonl).");
263
- process.exit(1);
264
- }
265
- if (format !== "json" && format !== "jsonl") {
266
- console.error(`\n Error: Invalid format '${format}'. Use json or jsonl.`);
267
- process.exit(1);
268
- }
269
- formatOverride = format;
270
- i += 1;
271
- continue;
272
- }
273
- if (arg === "--no-auto-flags") {
274
- autoFlags = false;
275
- continue;
276
- }
277
- cmdArgs.push(arg);
278
- }
279
- if (cmdArgs.length === 0) {
280
- console.error("\n Error: Missing CLI arguments to execute.");
281
- printHeadlessHelp();
282
- process.exit(1);
283
- }
284
- const format = resolveHeadlessFormat(source, cmdArgs, formatOverride);
285
- const finalArgs = applyHeadlessDefaults(source, cmdArgs, format, autoFlags);
286
- const headlessRoots = getHeadlessRoots(os.homedir());
287
- const output = buildHeadlessOutputPath(headlessRoots, source, format, outputPath);
288
- console.log(pc.cyan("\n Headless capture"));
289
- console.log(pc.gray(` source: ${source}`));
290
- console.log(pc.gray(` output: ${output}`));
291
- console.log();
292
- const proc = spawn(source, finalArgs, {
293
- stdio: ["inherit", "pipe", "inherit"],
294
- });
295
- if (!proc.stdout) {
296
- console.error("\n Error: Failed to capture stdout from command.");
297
- process.exit(1);
298
- }
299
- const outputStream = fs.createWriteStream(output, { encoding: "utf-8" });
300
- const outputFinished = new Promise((resolve, reject) => {
301
- outputStream.on("finish", () => resolve());
302
- outputStream.on("error", reject);
303
- });
304
- proc.stdout.pipe(outputStream);
305
- let exitCode;
306
- try {
307
- exitCode = await new Promise((resolve, reject) => {
308
- proc.on("error", reject);
309
- proc.on("close", (code) => resolve(code ?? 1));
310
- });
311
- }
312
- catch (err) {
313
- outputStream.destroy();
314
- const message = err instanceof Error ? err.message : String(err);
315
- console.error(`\n Error: Failed to run '${source}': ${message}`);
316
- process.exit(1);
317
- }
318
- outputStream.end();
319
- try {
320
- await outputFinished;
321
- }
322
- catch (err) {
323
- const message = err instanceof Error ? err.message : String(err);
324
- console.error(`\n Error: Failed to write headless output: ${message}`);
325
- process.exit(1);
326
- }
327
- if (exitCode !== 0) {
328
- process.exit(exitCode);
329
- }
330
- console.log(pc.green(` Saved headless output to ${output}`));
331
- console.log();
332
- }
333
- function buildTUIOptions(options, initialTab) {
334
- const dateFilters = getDateFilters(options);
335
- const enabledSources = getEnabledSources(options);
336
- return {
337
- initialTab,
338
- enabledSources: enabledSources,
339
- since: dateFilters.since,
340
- until: dateFilters.until,
341
- year: dateFilters.year,
342
- sinceTs: dateFilters.sinceTs,
343
- untilTs: dateFilters.untilTs,
344
- };
345
- }
346
- async function main() {
347
- const program = new Command();
348
- program
349
- .name("tokscale")
350
- .description("Tokscale - Track AI coding costs across OpenCode, Claude Code, Codex, Gemini, Cursor, and Amp")
351
- .version(pkg.version);
352
- program
353
- .command("monthly")
354
- .description("Show monthly usage report (launches TUI by default)")
355
- .option("--light", "Use legacy CLI table output instead of TUI")
356
- .option("--json", "Output as JSON (for scripting)")
357
- .option("--opencode", "Show only OpenCode usage")
358
- .option("--claude", "Show only Claude Code usage")
359
- .option("--codex", "Show only Codex CLI usage")
360
- .option("--gemini", "Show only Gemini CLI usage")
361
- .option("--cursor", "Show only Cursor IDE usage")
362
- .option("--amp", "Show only Amp usage")
363
- .option("--droid", "Show only Factory Droid usage")
364
- .option("--openclaw", "Show only OpenClaw usage")
365
- .option("--pi", "Show only Pi usage")
366
- .option("--today", "Show only today's usage")
367
- .option("--week", "Show last 7 days")
368
- .option("--month", "Show current month")
369
- .option("--since <date>", "Start date (YYYY-MM-DD)")
370
- .option("--until <date>", "End date (YYYY-MM-DD)")
371
- .option("--year <year>", "Filter to specific year")
372
- .option("--benchmark", "Show processing time")
373
- .option("--no-spinner", "Disable spinner (for AI agents and scripts - keeps stdout clean)")
374
- .action(async (options) => {
375
- if (options.json) {
376
- await outputJsonReport("monthly", options);
377
- }
378
- else if (options.light) {
379
- await showMonthlyReport(options, { spinner: options.spinner });
380
- }
381
- else {
382
- const launchTUI = await tryLoadTUI();
383
- if (launchTUI) {
384
- await launchTUI(buildTUIOptions(options, "daily"));
385
- }
386
- else {
387
- showTUIUnavailableMessage();
388
- await showMonthlyReport(options, { spinner: options.spinner });
389
- }
390
- }
391
- });
392
- program
393
- .command("models")
394
- .description("Show usage breakdown by model (launches TUI by default)")
395
- .option("--light", "Use legacy CLI table output instead of TUI")
396
- .option("--json", "Output as JSON (for scripting)")
397
- .option("--opencode", "Show only OpenCode usage")
398
- .option("--claude", "Show only Claude Code usage")
399
- .option("--codex", "Show only Codex CLI usage")
400
- .option("--gemini", "Show only Gemini CLI usage")
401
- .option("--cursor", "Show only Cursor IDE usage")
402
- .option("--amp", "Show only Amp usage")
403
- .option("--droid", "Show only Factory Droid usage")
404
- .option("--openclaw", "Show only OpenClaw usage")
405
- .option("--pi", "Show only Pi usage")
406
- .option("--today", "Show only today's usage")
407
- .option("--week", "Show last 7 days")
408
- .option("--month", "Show current month")
409
- .option("--since <date>", "Start date (YYYY-MM-DD)")
410
- .option("--until <date>", "End date (YYYY-MM-DD)")
411
- .option("--year <year>", "Filter to specific year")
412
- .option("--benchmark", "Show processing time")
413
- .option("--no-spinner", "Disable spinner (for AI agents and scripts - keeps stdout clean)")
414
- .action(async (options) => {
415
- if (options.json) {
416
- await outputJsonReport("models", options);
417
- }
418
- else if (options.light) {
419
- await showModelReport(options, { spinner: options.spinner });
420
- }
421
- else {
422
- const launchTUI = await tryLoadTUI();
423
- if (launchTUI) {
424
- await launchTUI(buildTUIOptions(options, "model"));
425
- }
426
- else {
427
- showTUIUnavailableMessage();
428
- await showModelReport(options, { spinner: options.spinner });
429
- }
430
- }
431
- });
432
- program
433
- .command("sources")
434
- .description("Show local scan locations and session counts")
435
- .option("--json", "Output as JSON (for scripting)")
436
- .action(async (options) => {
437
- const homeDir = os.homedir();
438
- const headlessRoots = getHeadlessRoots(homeDir);
439
- // Define all session paths
440
- const opencodeSessions = path.join(homeDir, ".local", "share", "opencode", "storage", "message");
441
- const claudeSessions = path.join(homeDir, ".claude", "projects");
442
- const codexHome = process.env.CODEX_HOME || path.join(homeDir, ".codex");
443
- const codexSessions = path.join(codexHome, "sessions");
444
- const geminiSessions = path.join(homeDir, ".gemini", "tmp");
445
- const ampSessions = path.join(homeDir, ".local", "share", "amp", "threads");
446
- const droidSessions = path.join(homeDir, ".factory", "sessions");
447
- const openclawSessions = path.join(homeDir, ".openclaw", "agents");
448
- const openclawLegacyPaths = [
449
- path.join(homeDir, ".clawdbot", "agents"),
450
- path.join(homeDir, ".moltbot", "agents"),
451
- path.join(homeDir, ".moldbot", "agents"),
452
- ];
453
- const piSessions = path.join(homeDir, ".pi", "agent", "sessions");
454
- let localMessages = null;
455
- try {
456
- localMessages = await parseLocalSourcesAsync({
457
- homeDir,
458
- sources: ["opencode", "claude", "codex", "gemini", "amp", "droid", "openclaw", "pi"],
459
- });
460
- }
461
- catch (e) {
462
- console.error(`Error: ${e.message}`);
463
- process.exit(1);
464
- }
465
- const headlessCounts = {
466
- codex: 0,
467
- };
468
- for (const message of localMessages.messages) {
469
- if (message.agent === "headless" && message.source === "codex") {
470
- headlessCounts.codex += 1;
471
- }
472
- }
473
- const sourceRows = [
474
- {
475
- source: "opencode",
476
- label: "OpenCode",
477
- sessionsPath: opencodeSessions,
478
- messageCount: localMessages.opencodeCount,
479
- headlessSupported: false,
480
- headlessPaths: [],
481
- headlessMessageCount: 0,
482
- },
483
- {
484
- source: "claude",
485
- label: "Claude Code",
486
- sessionsPath: claudeSessions,
487
- messageCount: localMessages.claudeCount,
488
- headlessSupported: false,
489
- headlessPaths: [],
490
- headlessMessageCount: 0,
491
- },
492
- {
493
- source: "codex",
494
- label: "Codex CLI",
495
- sessionsPath: codexSessions,
496
- headlessPaths: headlessRoots.map((root) => path.join(root, "codex")),
497
- messageCount: localMessages.codexCount,
498
- headlessMessageCount: headlessCounts.codex,
499
- headlessSupported: true,
500
- },
501
- {
502
- source: "gemini",
503
- label: "Gemini CLI",
504
- sessionsPath: geminiSessions,
505
- messageCount: localMessages.geminiCount,
506
- headlessSupported: false,
507
- headlessPaths: [],
508
- headlessMessageCount: 0,
509
- },
510
- {
511
- source: "cursor",
512
- label: "Cursor IDE",
513
- sessionsPath: path.join(homeDir, ".config", "tokscale", "cursor-cache"),
514
- messageCount: 0, // Cursor uses API sync, not local sessions
515
- headlessSupported: false,
516
- headlessPaths: [],
517
- headlessMessageCount: 0,
518
- },
519
- {
520
- source: "amp",
521
- label: "Amp",
522
- sessionsPath: ampSessions,
523
- messageCount: localMessages.ampCount,
524
- headlessSupported: false,
525
- headlessPaths: [],
526
- headlessMessageCount: 0,
527
- },
528
- {
529
- source: "droid",
530
- label: "Droid",
531
- sessionsPath: droidSessions,
532
- messageCount: localMessages.droidCount,
533
- headlessSupported: false,
534
- headlessPaths: [],
535
- headlessMessageCount: 0,
536
- },
537
- {
538
- source: "openclaw",
539
- label: "OpenClaw",
540
- sessionsPath: openclawSessions,
541
- legacyPaths: openclawLegacyPaths,
542
- messageCount: localMessages.openclawCount,
543
- headlessSupported: false,
544
- headlessPaths: [],
545
- headlessMessageCount: 0,
546
- },
547
- {
548
- source: "pi",
549
- label: "Pi",
550
- sessionsPath: piSessions,
551
- messageCount: localMessages.piCount,
552
- headlessSupported: false,
553
- headlessPaths: [],
554
- headlessMessageCount: 0,
555
- },
556
- ];
557
- if (options.json) {
558
- const payload = {
559
- headlessRoots,
560
- sources: sourceRows.map((row) => ({
561
- source: row.source,
562
- label: row.label,
563
- sessionsPath: row.sessionsPath,
564
- sessionsPathExists: fs.existsSync(row.sessionsPath),
565
- legacyPaths: row.legacyPaths
566
- ? row.legacyPaths.map((legacyPath) => ({
567
- path: legacyPath,
568
- exists: fs.existsSync(legacyPath),
569
- }))
570
- : [],
571
- messageCount: row.messageCount,
572
- headlessSupported: row.headlessSupported,
573
- headlessPaths: row.headlessSupported
574
- ? row.headlessPaths.map((headlessPath) => ({
575
- path: headlessPath,
576
- exists: fs.existsSync(headlessPath),
577
- }))
578
- : [],
579
- headlessMessageCount: row.headlessSupported ? row.headlessMessageCount : 0,
580
- })),
581
- note: "Headless capture is supported for Codex CLI only.",
582
- };
583
- console.log(JSON.stringify(payload, null, 2));
584
- return;
585
- }
586
- console.log(pc.cyan("\n Local sources & session counts"));
587
- console.log(pc.gray(` Headless roots: ${headlessRoots.join(", ")}`));
588
- console.log();
589
- for (const row of sourceRows) {
590
- console.log(pc.white(` ${row.label}`));
591
- console.log(pc.gray(` sessions: ${describePath(row.sessionsPath)}`));
592
- if (row.legacyPaths && row.legacyPaths.length > 0) {
593
- console.log(pc.gray(` legacy: ${row.legacyPaths.map(describePath).join(", ")}`));
594
- }
595
- if (row.headlessSupported) {
596
- console.log(pc.gray(` headless: ${row.headlessPaths.map(describePath).join(", ")}`));
597
- console.log(pc.gray(` messages: ${formatNumber(row.messageCount)} (headless: ${formatNumber(row.headlessMessageCount)})`));
598
- }
599
- else {
600
- console.log(pc.gray(` messages: ${formatNumber(row.messageCount)}`));
601
- }
602
- console.log();
603
- }
604
- console.log(pc.gray(" Note: Headless capture is supported for Codex CLI only."));
605
- console.log();
606
- });
607
- program
608
- .command("headless")
609
- .description("Run a CLI in headless mode and capture stdout")
610
- .argument("<source>", "Source CLI to capture (currently only 'codex' is supported)")
611
- .argument("[args...]", "Arguments passed to the CLI");
612
- program
613
- .command("graph")
614
- .description("Export contribution graph data as JSON")
615
- .option("--output <file>", "Write to file instead of stdout")
616
- .option("--opencode", "Include only OpenCode data")
617
- .option("--claude", "Include only Claude Code data")
618
- .option("--codex", "Include only Codex CLI data")
619
- .option("--gemini", "Include only Gemini CLI data")
620
- .option("--cursor", "Include only Cursor IDE data")
621
- .option("--amp", "Include only Amp data")
622
- .option("--droid", "Include only Factory Droid data")
623
- .option("--openclaw", "Include only OpenClaw data")
624
- .option("--pi", "Include only Pi data")
625
- .option("--today", "Show only today's usage")
626
- .option("--week", "Show last 7 days")
627
- .option("--month", "Show current month")
628
- .option("--since <date>", "Start date (YYYY-MM-DD)")
629
- .option("--until <date>", "End date (YYYY-MM-DD)")
630
- .option("--year <year>", "Filter to specific year")
631
- .option("--benchmark", "Show processing time")
632
- .option("--no-spinner", "Disable spinner (for AI agents and scripts - keeps stdout clean)")
633
- .action(async (options) => {
634
- await handleGraphCommand(options);
635
- });
636
- program
637
- .command("wrapped")
638
- .description("Generate Wrapped shareable image")
639
- .option("--output <file>", "Output file path (default: tokscale-<year>-wrapped.png)")
640
- .option("--year <year>", "Year to generate (default: current year)")
641
- .option("--opencode", "Include only OpenCode data")
642
- .option("--claude", "Include only Claude Code data")
643
- .option("--codex", "Include only Codex CLI data")
644
- .option("--gemini", "Include only Gemini CLI data")
645
- .option("--cursor", "Include only Cursor IDE data")
646
- .option("--amp", "Include only Amp data")
647
- .option("--droid", "Include only Factory Droid data")
648
- .option("--openclaw", "Include only OpenClaw data")
649
- .option("--pi", "Include only Pi data")
650
- .option("--no-spinner", "Disable loading spinner (for scripting)")
651
- .option("--short", "Display total tokens in abbreviated format (e.g., 7.14B)")
652
- .addOption(new Option("--agents", "Show Top OpenCode Agents (default)").conflicts("clients"))
653
- .addOption(new Option("--clients", "Show Top Clients instead of Top OpenCode Agents").conflicts("agents"))
654
- .option("--disable-pinned", "Disable pinning of Sisyphus agents in rankings")
655
- .action(async (options) => {
656
- await handleWrappedCommand(options);
657
- });
658
- program
659
- .command("login")
660
- .description("Login to Tokscale (opens browser for GitHub auth)")
661
- .action(async () => {
662
- await login();
663
- });
664
- program
665
- .command("logout")
666
- .description("Logout from Tokscale")
667
- .action(async () => {
668
- await logout();
669
- });
670
- program
671
- .command("whoami")
672
- .description("Show current logged in user")
673
- .action(async () => {
674
- await whoami();
675
- });
676
- // =========================================================================
677
- // Submit Command
678
- // =========================================================================
679
- program
680
- .command("submit")
681
- .description("Submit your usage data to Tokscale")
682
- .option("--opencode", "Include only OpenCode data")
683
- .option("--claude", "Include only Claude Code data")
684
- .option("--codex", "Include only Codex CLI data")
685
- .option("--gemini", "Include only Gemini CLI data")
686
- .option("--cursor", "Include only Cursor IDE data")
687
- .option("--amp", "Include only Amp data")
688
- .option("--droid", "Include only Factory Droid data")
689
- .option("--openclaw", "Include only OpenClaw data")
690
- .option("--pi", "Include only Pi data")
691
- .option("--since <date>", "Start date (YYYY-MM-DD)")
692
- .option("--until <date>", "End date (YYYY-MM-DD)")
693
- .option("--year <year>", "Filter to specific year")
694
- .option("--dry-run", "Show what would be submitted without actually submitting")
695
- .action(async (options) => {
696
- await submit({
697
- opencode: options.opencode,
698
- claude: options.claude,
699
- codex: options.codex,
700
- gemini: options.gemini,
701
- cursor: options.cursor,
702
- amp: options.amp,
703
- droid: options.droid,
704
- openclaw: options.openclaw,
705
- pi: options.pi,
706
- since: options.since,
707
- until: options.until,
708
- year: options.year,
709
- dryRun: options.dryRun,
710
- });
711
- });
712
- // =========================================================================
713
- // Interactive TUI Command
714
- // =========================================================================
715
- program
716
- .command("tui")
717
- .description("Launch interactive terminal UI")
718
- .option("--opencode", "Show only OpenCode usage")
719
- .option("--claude", "Show only Claude Code usage")
720
- .option("--codex", "Show only Codex CLI usage")
721
- .option("--gemini", "Show only Gemini CLI usage")
722
- .option("--cursor", "Show only Cursor IDE usage")
723
- .option("--amp", "Show only Amp usage")
724
- .option("--droid", "Show only Factory Droid usage")
725
- .option("--openclaw", "Show only OpenClaw usage")
726
- .option("--pi", "Show only Pi usage")
727
- .option("--today", "Show only today's usage")
728
- .option("--week", "Show last 7 days")
729
- .option("--month", "Show current month")
730
- .option("--since <date>", "Start date (YYYY-MM-DD)")
731
- .option("--until <date>", "End date (YYYY-MM-DD)")
732
- .option("--year <year>", "Filter to specific year")
733
- .action(async (options) => {
734
- const launchTUI = await tryLoadTUI();
735
- if (launchTUI) {
736
- await launchTUI(buildTUIOptions(options));
737
- }
738
- else {
739
- showTUIUnavailableMessage();
740
- process.exit(1);
741
- }
742
- });
743
- program
744
- .command("pricing <model-id>")
745
- .description("Look up pricing for a model")
746
- .option("--json", "Output as JSON")
747
- .option("--provider <source>", "Force pricing source: 'litellm' or 'openrouter'")
748
- .option("--no-spinner", "Disable spinner (for AI agents and scripts - keeps stdout clean)")
749
- .action(async (modelId, options) => {
750
- await handlePricingCommand(modelId, options);
751
- });
752
- const cursorCommand = program
753
- .command("cursor")
754
- .description("Cursor IDE integration commands");
755
- cursorCommand
756
- .command("login")
757
- .description("Login to Cursor (paste your session token)")
758
- .option("--name <name>", "Label for this Cursor account (e.g., work, personal)")
759
- .action(async (options) => {
760
- ensureCursorMigration();
761
- await cursorLogin(options);
762
- });
763
- cursorCommand
764
- .command("logout")
765
- .description("Logout from a Cursor account")
766
- .option("--name <name>", "Account label or id")
767
- .option("--all", "Logout from all Cursor accounts")
768
- .option("--purge-cache", "Also delete cached Cursor usage for the logged-out account(s)")
769
- .action(async (options) => {
770
- ensureCursorMigration();
771
- await cursorLogout(options);
772
- });
773
- cursorCommand
774
- .command("status")
775
- .description("Check Cursor authentication status")
776
- .option("--name <name>", "Account label or id")
777
- .action(async (options) => {
778
- ensureCursorMigration();
779
- await cursorStatus(options);
780
- });
781
- cursorCommand
782
- .command("accounts")
783
- .description("List saved Cursor accounts")
784
- .option("--json", "Output as JSON")
785
- .action(async (options) => {
786
- ensureCursorMigration();
787
- const accounts = listCursorAccounts();
788
- if (options.json) {
789
- console.log(JSON.stringify({ accounts }, null, 2));
790
- return;
791
- }
792
- if (accounts.length === 0) {
793
- console.log(pc.yellow("\n No saved Cursor accounts.\n"));
794
- return;
795
- }
796
- console.log(pc.cyan("\n Cursor IDE - Accounts\n"));
797
- for (const acct of accounts) {
798
- const name = acct.label ? `${acct.label} ${pc.gray(`(${acct.id})`)}` : acct.id;
799
- console.log(` ${acct.isActive ? pc.green("*") : pc.gray("-")} ${name}`);
800
- }
801
- console.log();
802
- });
803
- cursorCommand
804
- .command("switch")
805
- .description("Switch active Cursor account")
806
- .argument("<name>", "Account label or id")
807
- .action(async (name) => {
808
- ensureCursorMigration();
809
- const result = setActiveCursorAccount(name);
810
- if (!result.ok) {
811
- console.log(pc.red(`\n Error: ${result.error}\n`));
812
- process.exit(1);
813
- }
814
- console.log(pc.green(`\n Active Cursor account set to ${pc.bold(name)}\n`));
815
- });
816
- // Check if a subcommand was provided
817
- const args = process.argv.slice(2);
818
- if (args[0] === "headless") {
819
- await runHeadlessCapture(args);
820
- return;
821
- }
822
- const firstArg = args[0] || '';
823
- // Global flags should go to main program
824
- const isGlobalFlag = ['--help', '-h', '--version', '-V'].includes(firstArg);
825
- const hasSubcommand = args.length > 0 && !firstArg.startsWith('-');
826
- const knownCommands = ['monthly', 'models', 'sources', 'headless', 'graph', 'wrapped', 'login', 'logout', 'whoami', 'submit', 'cursor', 'tui', 'pricing', 'help'];
827
- const isKnownCommand = hasSubcommand && knownCommands.includes(firstArg);
828
- if (isKnownCommand || isGlobalFlag) {
829
- // Run the specified subcommand or show full help/version
830
- await program.parseAsync();
831
- }
832
- else {
833
- // No subcommand - launch TUI by default, or legacy CLI with --light, or JSON with --json
834
- const defaultProgram = new Command();
835
- defaultProgram
836
- .option("--light", "Use legacy CLI table output instead of TUI")
837
- .option("--json", "Output as JSON (for scripting)")
838
- .option("--opencode", "Show only OpenCode usage")
839
- .option("--claude", "Show only Claude Code usage")
840
- .option("--codex", "Show only Codex CLI usage")
841
- .option("--gemini", "Show only Gemini CLI usage")
842
- .option("--cursor", "Show only Cursor IDE usage")
843
- .option("--amp", "Show only Amp usage")
844
- .option("--droid", "Show only Factory Droid usage")
845
- .option("--openclaw", "Show only OpenClaw usage")
846
- .option("--today", "Show only today's usage")
847
- .option("--week", "Show last 7 days")
848
- .option("--month", "Show current month")
849
- .option("--since <date>", "Start date (YYYY-MM-DD)")
850
- .option("--until <date>", "End date (YYYY-MM-DD)")
851
- .option("--year <year>", "Filter to specific year")
852
- .option("--benchmark", "Show processing time")
853
- .option("--no-spinner", "Disable spinner (for AI agents and scripts - keeps stdout clean)")
854
- .parse();
855
- const opts = defaultProgram.opts();
856
- if (opts.json) {
857
- await outputJsonReport("models", opts);
858
- }
859
- else if (opts.light) {
860
- await showModelReport(opts, { spinner: opts.spinner });
861
- }
862
- else {
863
- const launchTUI = await tryLoadTUI();
864
- if (launchTUI) {
865
- await launchTUI(buildTUIOptions(opts));
866
- }
867
- else {
868
- showTUIUnavailableMessage();
869
- await showModelReport(opts, { spinner: opts.spinner });
870
- }
871
- }
872
- }
873
- }
874
- function getEnabledSources(options) {
875
- const hasFilter = options.opencode || options.claude || options.codex || options.gemini || options.cursor || options.amp || options.droid || options.openclaw || options.pi;
876
- if (!hasFilter)
877
- return undefined; // All sources
878
- const sources = [];
879
- if (options.opencode)
880
- sources.push("opencode");
881
- if (options.claude)
882
- sources.push("claude");
883
- if (options.codex)
884
- sources.push("codex");
885
- if (options.gemini)
886
- sources.push("gemini");
887
- if (options.cursor)
888
- sources.push("cursor");
889
- if (options.amp)
890
- sources.push("amp");
891
- if (options.droid)
892
- sources.push("droid");
893
- if (options.openclaw)
894
- sources.push("openclaw");
895
- if (options.pi)
896
- sources.push("pi");
897
- return sources;
898
- }
899
- /**
900
- * Sync Cursor usage data from API to local cache.
901
- * Only attempts sync if user is authenticated with Cursor.
902
- */
903
- async function syncCursorData() {
904
- if (!isCursorLoggedIn()) {
905
- return { attempted: false, synced: false, rows: 0 };
906
- }
907
- const result = await syncCursorCache();
908
- return {
909
- attempted: true,
910
- synced: result.synced,
911
- rows: result.rows,
912
- error: result.error,
913
- };
914
- }
915
- async function loadDataSourcesParallel(localSources, dateFilters, onPhase) {
916
- const shouldParseLocal = localSources.length > 0;
917
- const [cursorResult, localResult] = await Promise.allSettled([
918
- syncCursorData(),
919
- shouldParseLocal
920
- ? parseLocalSourcesAsync({
921
- sources: localSources.filter(s => s !== 'cursor'),
922
- since: dateFilters.since,
923
- until: dateFilters.until,
924
- year: dateFilters.year,
925
- sinceTs: dateFilters.sinceTs,
926
- untilTs: dateFilters.untilTs,
927
- })
928
- : Promise.resolve(null),
929
- ]);
930
- const cursorSync = cursorResult.status === 'fulfilled'
931
- ? cursorResult.value
932
- : { attempted: true, synced: false, rows: 0, error: 'Cursor sync failed' };
933
- const localMessages = localResult.status === 'fulfilled'
934
- ? localResult.value
935
- : null;
936
- return { cursorSync, localMessages };
937
- }
938
- async function showModelReport(options, extraOptions) {
939
- const dateFilters = getDateFilters(options);
940
- const enabledSources = getEnabledSources(options);
941
- const onlyCursor = enabledSources?.length === 1 && enabledSources[0] === 'cursor';
942
- const includeCursor = !enabledSources || enabledSources.includes('cursor');
943
- // Check cursor auth early if cursor-only mode
944
- if (onlyCursor) {
945
- if (!isCursorLoggedIn() && !hasCursorUsageCache()) {
946
- console.log(pc.red("\n Error: Cursor authentication required."));
947
- console.log(pc.gray(" Run 'tokscale cursor login' to authenticate with Cursor.\n"));
948
- process.exit(1);
949
- }
950
- }
951
- const dateRange = getDateRangeLabel(options);
952
- const title = dateRange
953
- ? `Token Usage Report by Model (${dateRange})`
954
- : "Token Usage Report by Model";
955
- console.log(pc.cyan(`\n ${title}`));
956
- if (options.benchmark) {
957
- console.log(pc.gray(` Using: Rust native module v${getNativeVersion()}`));
958
- }
959
- console.log();
960
- const useSpinner = extraOptions?.spinner !== false;
961
- const spinner = useSpinner ? createSpinner({ color: "cyan" }) : null;
962
- const localSources = (enabledSources || ['opencode', 'claude', 'codex', 'gemini', 'cursor', 'amp', 'droid', 'openclaw', 'pi'])
963
- .filter(s => s !== 'cursor');
964
- spinner?.start(pc.gray("Scanning session data..."));
965
- const { cursorSync, localMessages } = await loadDataSourcesParallel(onlyCursor ? [] : localSources, dateFilters, (phase) => spinner?.update(phase));
966
- if (includeCursor && cursorSync.attempted && cursorSync.error) {
967
- // Don't block report generation; just warn about partial Cursor sync.
968
- console.log(pc.yellow(` Cursor sync warning: ${cursorSync.error}`));
969
- }
970
- if (!localMessages && !onlyCursor) {
971
- if (spinner) {
972
- spinner.error('Failed to parse local session files');
973
- }
974
- else {
975
- console.error('Failed to parse local session files');
976
- }
977
- process.exit(1);
978
- }
979
- spinner?.update(pc.gray("Finalizing report..."));
980
- const startTime = performance.now();
981
- let report;
982
- try {
983
- const emptyMessages = { messages: [], opencodeCount: 0, claudeCount: 0, codexCount: 0, geminiCount: 0, ampCount: 0, droidCount: 0, openclawCount: 0, piCount: 0, processingTimeMs: 0 };
984
- report = await finalizeReportAsync({
985
- localMessages: localMessages || emptyMessages,
986
- includeCursor: includeCursor && (cursorSync.synced || hasCursorUsageCache()),
987
- since: dateFilters.since,
988
- until: dateFilters.until,
989
- year: dateFilters.year,
990
- sinceTs: dateFilters.sinceTs,
991
- untilTs: dateFilters.untilTs,
992
- });
993
- }
994
- catch (e) {
995
- if (spinner) {
996
- spinner.error(`Error: ${e.message}`);
997
- }
998
- else {
999
- console.error(`Error: ${e.message}`);
1000
- }
1001
- process.exit(1);
1002
- }
1003
- const processingTime = performance.now() - startTime;
1004
- spinner?.stop();
1005
- if (report.entries.length === 0) {
1006
- if (onlyCursor && !cursorSync.synced) {
1007
- console.log(pc.yellow(" No Cursor data available."));
1008
- console.log(pc.gray(" Run 'tokscale cursor login' to authenticate with Cursor.\n"));
1009
- }
1010
- else {
1011
- console.log(pc.yellow(" No usage data found.\n"));
1012
- }
1013
- return;
1014
- }
1015
- // Create table
1016
- const table = createUsageTable("Source/Model");
1017
- const settings = loadSettings();
1018
- const filteredEntries = settings.includeUnusedModels
1019
- ? report.entries
1020
- : report.entries.filter(e => e.input + e.output + e.cacheRead + e.cacheWrite > 0);
1021
- for (const entry of filteredEntries) {
1022
- const sourceLabel = getSourceLabel(entry.source);
1023
- const modelDisplay = `${pc.dim(sourceLabel)} ${formatModelName(entry.model)}`;
1024
- table.push(formatUsageRow(modelDisplay, [entry.model], entry.input, entry.output, entry.cacheWrite, entry.cacheRead, entry.cost));
1025
- }
1026
- // Add totals row
1027
- table.push(formatTotalsRow(report.totalInput, report.totalOutput, report.totalCacheWrite, report.totalCacheRead, report.totalCost));
1028
- console.log(table.toString());
1029
- // Summary stats
1030
- console.log(pc.gray(`\n Total: ${formatNumber(report.totalMessages)} messages, ` +
1031
- `${formatNumber(report.totalInput + report.totalOutput + report.totalCacheRead + report.totalCacheWrite)} tokens, ` +
1032
- `${pc.green(formatCurrency(report.totalCost))}`));
1033
- if (options.benchmark) {
1034
- console.log(pc.gray(` Processing time: ${processingTime.toFixed(0)}ms (Rust) + ${report.processingTimeMs}ms (parsing)`));
1035
- if (cursorSync.attempted) {
1036
- if (cursorSync.synced) {
1037
- console.log(pc.gray(` Cursor: ${cursorSync.rows} usage events synced (full lifetime data)`));
1038
- }
1039
- else {
1040
- console.log(pc.yellow(` Cursor: sync failed - ${cursorSync.error}`));
1041
- }
1042
- }
1043
- }
1044
- console.log();
1045
- }
1046
- async function showMonthlyReport(options, extraOptions) {
1047
- const dateRange = getDateRangeLabel(options);
1048
- const title = dateRange
1049
- ? `Monthly Token Usage Report (${dateRange})`
1050
- : "Monthly Token Usage Report";
1051
- console.log(pc.cyan(`\n ${title}`));
1052
- if (options.benchmark) {
1053
- console.log(pc.gray(` Using: Rust native module v${getNativeVersion()}`));
1054
- }
1055
- console.log();
1056
- const useSpinner = extraOptions?.spinner !== false;
1057
- const spinner = useSpinner ? createSpinner({ color: "cyan" }) : null;
1058
- const dateFilters = getDateFilters(options);
1059
- const enabledSources = getEnabledSources(options);
1060
- const localSources = (enabledSources || ['opencode', 'claude', 'codex', 'gemini', 'cursor', 'amp', 'droid', 'openclaw', 'pi'])
1061
- .filter(s => s !== 'cursor');
1062
- const includeCursor = !enabledSources || enabledSources.includes('cursor');
1063
- spinner?.start(pc.gray("Scanning session data..."));
1064
- const { cursorSync, localMessages } = await loadDataSourcesParallel(localSources, dateFilters, (phase) => spinner?.update(phase));
1065
- if (!localMessages) {
1066
- if (spinner) {
1067
- spinner.error('Failed to parse local session files');
1068
- }
1069
- else {
1070
- console.error('Failed to parse local session files');
1071
- }
1072
- process.exit(1);
1073
- }
1074
- spinner?.update(pc.gray("Finalizing report..."));
1075
- const startTime = performance.now();
1076
- let report;
1077
- try {
1078
- report = await finalizeMonthlyReportAsync({
1079
- localMessages,
1080
- includeCursor: includeCursor && (cursorSync.synced || hasCursorUsageCache()),
1081
- since: dateFilters.since,
1082
- until: dateFilters.until,
1083
- year: dateFilters.year,
1084
- sinceTs: dateFilters.sinceTs,
1085
- untilTs: dateFilters.untilTs,
1086
- });
1087
- }
1088
- catch (e) {
1089
- if (spinner) {
1090
- spinner.error(`Error: ${e.message}`);
1091
- }
1092
- else {
1093
- console.error(`Error: ${e.message}`);
1094
- }
1095
- process.exit(1);
1096
- }
1097
- const processingTime = performance.now() - startTime;
1098
- spinner?.stop();
1099
- if (report.entries.length === 0) {
1100
- console.log(pc.yellow(" No usage data found.\n"));
1101
- return;
1102
- }
1103
- // Create table
1104
- const table = createUsageTable("Month");
1105
- const settings = loadSettings();
1106
- const filteredEntries = settings.includeUnusedModels
1107
- ? report.entries
1108
- : report.entries.filter(e => e.input + e.output + e.cacheRead + e.cacheWrite > 0);
1109
- for (const entry of filteredEntries) {
1110
- table.push(formatUsageRow(entry.month, entry.models, entry.input, entry.output, entry.cacheWrite, entry.cacheRead, entry.cost));
1111
- }
1112
- // Add totals row
1113
- const totalInput = report.entries.reduce((sum, e) => sum + e.input, 0);
1114
- const totalOutput = report.entries.reduce((sum, e) => sum + e.output, 0);
1115
- const totalCacheRead = report.entries.reduce((sum, e) => sum + e.cacheRead, 0);
1116
- const totalCacheWrite = report.entries.reduce((sum, e) => sum + e.cacheWrite, 0);
1117
- table.push(formatTotalsRow(totalInput, totalOutput, totalCacheWrite, totalCacheRead, report.totalCost));
1118
- console.log(table.toString());
1119
- console.log(pc.gray(`\n Total Cost: ${pc.green(formatCurrency(report.totalCost))}`));
1120
- if (options.benchmark) {
1121
- console.log(pc.gray(` Processing time: ${processingTime.toFixed(0)}ms (Rust) + ${report.processingTimeMs}ms (parsing)`));
1122
- if (cursorSync.attempted) {
1123
- if (cursorSync.synced) {
1124
- console.log(pc.gray(` Cursor: ${cursorSync.rows} usage events synced (full lifetime data)`));
1125
- }
1126
- else {
1127
- console.log(pc.yellow(` Cursor: sync failed - ${cursorSync.error}`));
1128
- }
1129
- }
1130
- }
1131
- console.log();
1132
- }
1133
- async function outputJsonReport(reportType, options) {
1134
- const dateFilters = getDateFilters(options);
1135
- const enabledSources = getEnabledSources(options);
1136
- const onlyCursor = enabledSources?.length === 1 && enabledSources[0] === 'cursor';
1137
- const includeCursor = !enabledSources || enabledSources.includes('cursor');
1138
- const localSources = (enabledSources || ['opencode', 'claude', 'codex', 'gemini', 'cursor', 'amp', 'droid', 'openclaw', 'pi'])
1139
- .filter(s => s !== 'cursor');
1140
- const { cursorSync, localMessages } = await loadDataSourcesParallel(onlyCursor ? [] : localSources, dateFilters);
1141
- if (!localMessages && !onlyCursor) {
1142
- console.error(JSON.stringify({ error: "Failed to parse local session files" }));
1143
- process.exit(1);
1144
- }
1145
- const emptyMessages = { messages: [], opencodeCount: 0, claudeCount: 0, codexCount: 0, geminiCount: 0, ampCount: 0, droidCount: 0, openclawCount: 0, piCount: 0, processingTimeMs: 0 };
1146
- if (reportType === "models") {
1147
- const report = await finalizeReportAsync({
1148
- localMessages: localMessages || emptyMessages,
1149
- includeCursor: includeCursor && (cursorSync.synced || hasCursorUsageCache()),
1150
- since: dateFilters.since,
1151
- until: dateFilters.until,
1152
- year: dateFilters.year,
1153
- sinceTs: dateFilters.sinceTs,
1154
- untilTs: dateFilters.untilTs,
1155
- });
1156
- console.log(JSON.stringify(report, null, 2));
1157
- }
1158
- else {
1159
- const report = await finalizeMonthlyReportAsync({
1160
- localMessages: localMessages || emptyMessages,
1161
- includeCursor: includeCursor && (cursorSync.synced || hasCursorUsageCache()),
1162
- since: dateFilters.since,
1163
- until: dateFilters.until,
1164
- year: dateFilters.year,
1165
- sinceTs: dateFilters.sinceTs,
1166
- untilTs: dateFilters.untilTs,
1167
- });
1168
- console.log(JSON.stringify(report, null, 2));
1169
- }
1170
- }
1171
- async function handleGraphCommand(options) {
1172
- const useSpinner = options.output && options.spinner !== false;
1173
- const spinner = useSpinner ? createSpinner({ color: "cyan" }) : null;
1174
- const dateFilters = getDateFilters(options);
1175
- const enabledSources = getEnabledSources(options);
1176
- const localSources = (enabledSources || ['opencode', 'claude', 'codex', 'gemini', 'cursor', 'amp', 'droid', 'openclaw', 'pi'])
1177
- .filter(s => s !== 'cursor');
1178
- const includeCursor = !enabledSources || enabledSources.includes('cursor');
1179
- spinner?.start(pc.gray("Scanning session data..."));
1180
- const { cursorSync, localMessages } = await loadDataSourcesParallel(localSources, dateFilters, (phase) => spinner?.update(phase));
1181
- if (!localMessages) {
1182
- spinner?.error('Failed to parse local session files');
1183
- process.exit(1);
1184
- }
1185
- spinner?.update(pc.gray("Generating graph data..."));
1186
- const startTime = performance.now();
1187
- const data = await finalizeGraphAsync({
1188
- localMessages,
1189
- includeCursor: includeCursor && (cursorSync.synced || hasCursorUsageCache()),
1190
- since: dateFilters.since,
1191
- until: dateFilters.until,
1192
- year: dateFilters.year,
1193
- sinceTs: dateFilters.sinceTs,
1194
- untilTs: dateFilters.untilTs,
1195
- });
1196
- const processingTime = performance.now() - startTime;
1197
- spinner?.stop();
1198
- const jsonOutput = JSON.stringify(data, null, 2);
1199
- // Output to file or stdout
1200
- if (options.output) {
1201
- fs.writeFileSync(options.output, jsonOutput, "utf-8");
1202
- console.error(pc.green(`✓ Graph data written to ${options.output}`));
1203
- console.error(pc.gray(` ${data.contributions.length} days, ${data.summary.sources.length} sources, ${data.summary.models.length} models`));
1204
- console.error(pc.gray(` Total: ${formatCurrency(data.summary.totalCost)}`));
1205
- if (options.benchmark) {
1206
- console.error(pc.gray(` Processing time: ${processingTime.toFixed(0)}ms (Rust native)`));
1207
- if (cursorSync.attempted) {
1208
- if (cursorSync.synced) {
1209
- console.error(pc.gray(` Cursor: ${cursorSync.rows} usage events synced (full lifetime data)`));
1210
- }
1211
- else {
1212
- console.error(pc.yellow(` Cursor: sync failed - ${cursorSync.error}`));
1213
- }
1214
- }
1215
- }
1216
- }
1217
- else {
1218
- console.log(jsonOutput);
1219
- }
1220
- }
1221
- async function handleWrappedCommand(options) {
1222
- const useSpinner = options.spinner !== false;
1223
- const spinner = useSpinner ? createSpinner({ color: "cyan" }) : null;
1224
- const currentYear = new Date().getFullYear().toString();
1225
- const year = options.year || currentYear;
1226
- spinner?.start(pc.gray(`Generating your ${year} Wrapped...`));
1227
- try {
1228
- const enabledSources = getEnabledSources(options);
1229
- const outputPath = await generateWrapped({
1230
- output: options.output,
1231
- year,
1232
- sources: enabledSources,
1233
- short: options.short,
1234
- includeAgents: !options.clients,
1235
- pinSisyphus: !options.disablePinned,
1236
- });
1237
- spinner?.stop();
1238
- console.log(pc.green(`\n ✓ Your Tokscale Wrapped image is ready!`));
1239
- console.log(pc.white(` ${outputPath}`));
1240
- console.log();
1241
- console.log(pc.gray(" Share it on Twitter/X with #TokscaleWrapped"));
1242
- console.log();
1243
- }
1244
- catch (error) {
1245
- if (spinner) {
1246
- spinner.error(`Failed to generate wrapped: ${error.message}`);
1247
- }
1248
- else {
1249
- console.error(pc.red(`Failed to generate wrapped: ${error.message}`));
1250
- }
1251
- process.exit(1);
1252
- }
1253
- }
1254
- async function handlePricingCommand(modelId, options) {
1255
- const validProviders = ["litellm", "openrouter"];
1256
- if (options.provider && !validProviders.includes(options.provider.toLowerCase())) {
1257
- console.log(pc.red(`\n Invalid provider: ${options.provider}`));
1258
- console.log(pc.gray(` Valid providers: ${validProviders.join(", ")}\n`));
1259
- process.exit(1);
1260
- }
1261
- const useSpinner = options.spinner !== false;
1262
- const spinner = useSpinner ? createSpinner({ color: "cyan" }) : null;
1263
- const providerLabel = options.provider ? ` from ${options.provider}` : "";
1264
- spinner?.start(pc.gray(`Fetching pricing data${providerLabel}...`));
1265
- let core;
1266
- try {
1267
- const mod = await import("@tokscale/core");
1268
- core = (mod.default ?? mod);
1269
- }
1270
- catch (importErr) {
1271
- spinner?.stop();
1272
- const errorMsg = importErr.message || "Unknown error";
1273
- if (options.json) {
1274
- console.log(JSON.stringify({ error: "Native module not available", details: errorMsg }, null, 2));
1275
- }
1276
- else {
1277
- console.log(pc.red(`\n Native module not available: ${errorMsg}`));
1278
- console.log(pc.gray(" Run 'bun run build:core' to build the native module.\n"));
1279
- }
1280
- process.exit(1);
1281
- }
1282
- try {
1283
- const provider = options.provider?.toLowerCase() || undefined;
1284
- const nativeResult = await core.lookupPricing(modelId, provider);
1285
- spinner?.stop();
1286
- const result = {
1287
- matchedKey: nativeResult.matchedKey,
1288
- source: nativeResult.source,
1289
- pricing: {
1290
- input_cost_per_token: nativeResult.pricing.inputCostPerToken,
1291
- output_cost_per_token: nativeResult.pricing.outputCostPerToken,
1292
- cache_read_input_token_cost: nativeResult.pricing.cacheReadInputTokenCost,
1293
- cache_creation_input_token_cost: nativeResult.pricing.cacheCreationInputTokenCost,
1294
- },
1295
- };
1296
- if (options.json) {
1297
- console.log(JSON.stringify({
1298
- modelId,
1299
- matchedKey: result.matchedKey,
1300
- source: result.source,
1301
- pricing: {
1302
- inputCostPerToken: result.pricing.input_cost_per_token ?? 0,
1303
- outputCostPerToken: result.pricing.output_cost_per_token ?? 0,
1304
- cacheReadInputTokenCost: result.pricing.cache_read_input_token_cost,
1305
- cacheCreationInputTokenCost: result.pricing.cache_creation_input_token_cost,
1306
- },
1307
- }, null, 2));
1308
- }
1309
- else {
1310
- const sourceLower = result.source.toLowerCase();
1311
- const sourceLabel = sourceLower === "litellm" ? pc.blue("LiteLLM") : sourceLower === "cursor" ? pc.yellow("Cursor") : pc.magenta("OpenRouter");
1312
- const inputCost = result.pricing.input_cost_per_token ?? 0;
1313
- const outputCost = result.pricing.output_cost_per_token ?? 0;
1314
- const cacheReadCost = result.pricing.cache_read_input_token_cost;
1315
- const cacheWriteCost = result.pricing.cache_creation_input_token_cost;
1316
- console.log(pc.cyan(`\n Pricing for: ${pc.white(modelId)}`));
1317
- console.log(pc.gray(` Matched key: ${result.matchedKey}`));
1318
- console.log(pc.gray(` Source: `) + sourceLabel);
1319
- console.log();
1320
- console.log(pc.white(` Input: `) + formatPricePerMillion(inputCost));
1321
- console.log(pc.white(` Output: `) + formatPricePerMillion(outputCost));
1322
- if (cacheReadCost !== undefined) {
1323
- console.log(pc.white(` Cache Read: `) + formatPricePerMillion(cacheReadCost));
1324
- }
1325
- if (cacheWriteCost !== undefined) {
1326
- console.log(pc.white(` Cache Write: `) + formatPricePerMillion(cacheWriteCost));
1327
- }
1328
- console.log();
1329
- }
1330
- }
1331
- catch (err) {
1332
- spinner?.stop();
1333
- const errorMsg = err.message || "Unknown error";
1334
- // Check if this is a "model not found" error from Rust or a different error
1335
- const isModelNotFound = errorMsg.toLowerCase().includes("not found") ||
1336
- errorMsg.toLowerCase().includes("no pricing");
1337
- if (options.json) {
1338
- if (isModelNotFound) {
1339
- console.log(JSON.stringify({ error: "Model not found", modelId }, null, 2));
1340
- }
1341
- else {
1342
- console.log(JSON.stringify({ error: errorMsg, modelId }, null, 2));
1343
- }
1344
- }
1345
- else {
1346
- if (isModelNotFound) {
1347
- console.log(pc.red(`\n Model not found: ${modelId}\n`));
1348
- }
1349
- else {
1350
- console.log(pc.red(`\n Error looking up pricing: ${errorMsg}\n`));
1351
- }
1352
- }
1353
- process.exit(1);
1354
- }
1355
- }
1356
- function formatPricePerMillion(costPerToken) {
1357
- const perMillion = costPerToken * 1_000_000;
1358
- return pc.green(`$${perMillion.toFixed(2)}`) + pc.gray(" / 1M tokens");
1359
- }
1360
- function getSourceLabel(source) {
1361
- switch (source) {
1362
- case "opencode":
1363
- return "OpenCode";
1364
- case "claude":
1365
- return "Claude";
1366
- case "codex":
1367
- return "Codex";
1368
- case "gemini":
1369
- return "Gemini";
1370
- case "cursor":
1371
- return "Cursor";
1372
- case "amp":
1373
- return "Amp";
1374
- case "droid":
1375
- return "Droid";
1376
- default:
1377
- return source;
1378
- }
1379
- }
1380
- // =============================================================================
1381
- // Cursor IDE Authentication
1382
- // =============================================================================
1383
- async function cursorLogin(options = {}) {
1384
- console.log(pc.cyan("\n Cursor IDE - Login\n"));
1385
- console.log(pc.white(" To get your session token:"));
1386
- console.log(pc.gray(" 1. Open https://www.cursor.com/settings in your browser"));
1387
- console.log(pc.gray(" 2. Open Developer Tools (F12) > Network tab"));
1388
- console.log(pc.gray(" 3. Find any request to cursor.com/api"));
1389
- console.log(pc.gray(" 4. Copy the 'WorkosCursorSessionToken' cookie value"));
1390
- console.log();
1391
- // Read token from stdin
1392
- const readline = await import("node:readline");
1393
- const rl = readline.createInterface({
1394
- input: process.stdin,
1395
- output: process.stdout,
1396
- });
1397
- const token = await new Promise((resolve) => {
1398
- rl.question(pc.white(" Paste your session token: "), (answer) => {
1399
- rl.close();
1400
- resolve(answer.trim());
1401
- });
1402
- });
1403
- if (!token) {
1404
- console.log(pc.red("\n No token provided. Login cancelled.\n"));
1405
- return;
1406
- }
1407
- // Validate the token
1408
- console.log(pc.gray("\n Validating token..."));
1409
- const validation = await validateCursorSession(token);
1410
- if (!validation.valid) {
1411
- console.log(pc.red(`\n Invalid token: ${validation.error}`));
1412
- console.log(pc.gray(" Please try again with a valid session token.\n"));
1413
- return;
1414
- }
1415
- // Save credentials (multi-account)
1416
- let savedAccountId;
1417
- try {
1418
- const saved = saveCursorCredentials({
1419
- sessionToken: token,
1420
- createdAt: new Date().toISOString(),
1421
- }, { label: options.name });
1422
- savedAccountId = saved.accountId;
1423
- }
1424
- catch (e) {
1425
- console.log(pc.red(`\n Failed to save credentials: ${e.message}\n`));
1426
- return;
1427
- }
1428
- console.log(pc.green("\n Success! Logged in to Cursor."));
1429
- if (options.name) {
1430
- console.log(pc.gray(` Account: ${options.name} (${savedAccountId})`));
1431
- }
1432
- else {
1433
- console.log(pc.gray(` Account ID: ${savedAccountId}`));
1434
- }
1435
- if (validation.membershipType) {
1436
- console.log(pc.gray(` Membership: ${validation.membershipType}`));
1437
- }
1438
- console.log(pc.gray(" Your usage data will now be included in reports.\n"));
1439
- }
1440
- async function cursorLogout(options = {}) {
1441
- if (!isCursorLoggedIn()) {
1442
- console.log(pc.yellow("\n Not logged in to Cursor.\n"));
1443
- return;
1444
- }
1445
- if (options.all) {
1446
- const cleared = options.purgeCache ? clearCursorCredentialsAndCache({ purgeCache: true }) : clearCursorCredentialsAndCache();
1447
- if (cleared) {
1448
- console.log(pc.green("\n Logged out from all Cursor accounts.\n"));
1449
- return;
1450
- }
1451
- console.error(pc.red("\n Failed to clear Cursor credentials.\n"));
1452
- process.exit(1);
1453
- }
1454
- const target = options.name || listCursorAccounts().find((a) => a.isActive)?.id;
1455
- if (!target) {
1456
- console.log(pc.yellow("\n No saved Cursor accounts.\n"));
1457
- return;
1458
- }
1459
- const removed = removeCursorAccount(target, { purgeCache: options.purgeCache });
1460
- if (!removed.removed) {
1461
- console.error(pc.red(`\n Failed to log out: ${removed.error}\n`));
1462
- process.exit(1);
1463
- }
1464
- if (options.purgeCache) {
1465
- console.log(pc.green(`\n Logged out from Cursor account (cache purged): ${pc.bold(target)}\n`));
1466
- }
1467
- else {
1468
- console.log(pc.green(`\n Logged out from Cursor account (history archived): ${pc.bold(target)}\n`));
1469
- }
1470
- }
1471
- async function cursorStatus(options = {}) {
1472
- if (!isCursorLoggedIn()) {
1473
- console.log(pc.yellow("\n Not logged in to Cursor."));
1474
- console.log(pc.gray(" Run 'tokscale cursor login' to authenticate.\n"));
1475
- return;
1476
- }
1477
- const accounts = listCursorAccounts();
1478
- const target = options.name
1479
- ? options.name
1480
- : accounts.find((a) => a.isActive)?.id;
1481
- const credentials = target ? loadCursorCredentials(target) : null;
1482
- if (!credentials) {
1483
- console.log(pc.red("\n Error: Cursor account not found."));
1484
- console.log(pc.gray(" Run 'tokscale cursor accounts' to list saved accounts.\n"));
1485
- process.exit(1);
1486
- }
1487
- console.log(pc.cyan("\n Cursor IDE - Status\n"));
1488
- if (accounts.length > 0) {
1489
- console.log(pc.white(" Accounts:"));
1490
- for (const acct of accounts) {
1491
- const name = acct.label ? `${acct.label} ${pc.gray(`(${acct.id})`)}` : acct.id;
1492
- console.log(` ${acct.isActive ? pc.green("*") : pc.gray("-")} ${name}`);
1493
- }
1494
- console.log();
1495
- }
1496
- console.log(pc.gray(" Checking session validity..."));
1497
- const validation = await validateCursorSession(credentials.sessionToken);
1498
- if (validation.valid) {
1499
- console.log(pc.green(" ✓ Session is valid"));
1500
- if (validation.membershipType) {
1501
- console.log(pc.white(` Membership: ${validation.membershipType}`));
1502
- }
1503
- console.log(pc.gray(` Logged in: ${new Date(credentials.createdAt).toLocaleDateString()}`));
1504
- // Try to fetch usage to show summary
1505
- try {
1506
- const usage = await readCursorUsage(target);
1507
- const totalCost = usage.byModel.reduce((sum, m) => sum + m.cost, 0);
1508
- console.log(pc.gray(` Models used: ${usage.byModel.length}`));
1509
- console.log(pc.gray(` Total usage events: ${usage.rows.length}`));
1510
- console.log(pc.gray(` Total cost: $${totalCost.toFixed(2)}`));
1511
- }
1512
- catch (e) {
1513
- // Ignore fetch errors for status check
1514
- }
1515
- }
1516
- else {
1517
- console.log(pc.red(` ✗ Session invalid: ${validation.error}`));
1518
- console.log(pc.gray(" Run 'tokscale cursor login' to re-authenticate."));
1519
- }
1520
- console.log(pc.gray(`\n Credentials: ${getCursorCredentialsPath()}\n`));
1521
- }
1522
- main().catch(console.error);
1523
- //# sourceMappingURL=cli.js.map