@tokscale/cli 1.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 (211) hide show
  1. package/dist/auth.d.ts +17 -0
  2. package/dist/auth.d.ts.map +1 -0
  3. package/dist/auth.js +162 -0
  4. package/dist/auth.js.map +1 -0
  5. package/dist/claudecode.d.ts +39 -0
  6. package/dist/claudecode.d.ts.map +1 -0
  7. package/dist/claudecode.js +375 -0
  8. package/dist/claudecode.js.map +1 -0
  9. package/dist/cli.d.ts +9 -0
  10. package/dist/cli.d.ts.map +1 -0
  11. package/dist/cli.js +761 -0
  12. package/dist/cli.js.map +1 -0
  13. package/dist/credentials.d.ts +36 -0
  14. package/dist/credentials.d.ts.map +1 -0
  15. package/dist/credentials.js +109 -0
  16. package/dist/credentials.js.map +1 -0
  17. package/dist/cursor.d.ts +132 -0
  18. package/dist/cursor.d.ts.map +1 -0
  19. package/dist/cursor.js +432 -0
  20. package/dist/cursor.js.map +1 -0
  21. package/dist/gemini.d.ts +36 -0
  22. package/dist/gemini.d.ts.map +1 -0
  23. package/dist/gemini.js +125 -0
  24. package/dist/gemini.js.map +1 -0
  25. package/dist/graph-types.d.ts +152 -0
  26. package/dist/graph-types.d.ts.map +1 -0
  27. package/dist/graph-types.js +6 -0
  28. package/dist/graph-types.js.map +1 -0
  29. package/dist/graph.d.ts +29 -0
  30. package/dist/graph.d.ts.map +1 -0
  31. package/dist/graph.js +383 -0
  32. package/dist/graph.js.map +1 -0
  33. package/dist/native-runner.d.ts +12 -0
  34. package/dist/native-runner.d.ts.map +1 -0
  35. package/dist/native-runner.js +89 -0
  36. package/dist/native-runner.js.map +1 -0
  37. package/dist/native.d.ts +116 -0
  38. package/dist/native.d.ts.map +1 -0
  39. package/dist/native.js +359 -0
  40. package/dist/native.js.map +1 -0
  41. package/dist/opencode.d.ts +40 -0
  42. package/dist/opencode.d.ts.map +1 -0
  43. package/dist/opencode.js +69 -0
  44. package/dist/opencode.js.map +1 -0
  45. package/dist/pricing.d.ts +58 -0
  46. package/dist/pricing.d.ts.map +1 -0
  47. package/dist/pricing.js +232 -0
  48. package/dist/pricing.js.map +1 -0
  49. package/dist/sessions/claudecode.d.ts +8 -0
  50. package/dist/sessions/claudecode.d.ts.map +1 -0
  51. package/dist/sessions/claudecode.js +84 -0
  52. package/dist/sessions/claudecode.js.map +1 -0
  53. package/dist/sessions/codex.d.ts +8 -0
  54. package/dist/sessions/codex.d.ts.map +1 -0
  55. package/dist/sessions/codex.js +158 -0
  56. package/dist/sessions/codex.js.map +1 -0
  57. package/dist/sessions/gemini.d.ts +8 -0
  58. package/dist/sessions/gemini.d.ts.map +1 -0
  59. package/dist/sessions/gemini.js +66 -0
  60. package/dist/sessions/gemini.js.map +1 -0
  61. package/dist/sessions/index.d.ts +32 -0
  62. package/dist/sessions/index.d.ts.map +1 -0
  63. package/dist/sessions/index.js +96 -0
  64. package/dist/sessions/index.js.map +1 -0
  65. package/dist/sessions/opencode.d.ts +8 -0
  66. package/dist/sessions/opencode.d.ts.map +1 -0
  67. package/dist/sessions/opencode.js +54 -0
  68. package/dist/sessions/opencode.js.map +1 -0
  69. package/dist/sessions/reports.d.ts +58 -0
  70. package/dist/sessions/reports.d.ts.map +1 -0
  71. package/dist/sessions/reports.js +337 -0
  72. package/dist/sessions/reports.js.map +1 -0
  73. package/dist/sessions/types.d.ts +30 -0
  74. package/dist/sessions/types.d.ts.map +1 -0
  75. package/dist/sessions/types.js +29 -0
  76. package/dist/sessions/types.js.map +1 -0
  77. package/dist/spinner.d.ts +75 -0
  78. package/dist/spinner.d.ts.map +1 -0
  79. package/dist/spinner.js +203 -0
  80. package/dist/spinner.js.map +1 -0
  81. package/dist/submit.d.ts +21 -0
  82. package/dist/submit.d.ts.map +1 -0
  83. package/dist/submit.js +128 -0
  84. package/dist/submit.js.map +1 -0
  85. package/dist/table.d.ts +42 -0
  86. package/dist/table.d.ts.map +1 -0
  87. package/dist/table.js +181 -0
  88. package/dist/table.js.map +1 -0
  89. package/dist/test-selection.d.ts +2 -0
  90. package/dist/test-selection.d.ts.map +1 -0
  91. package/dist/test-selection.jsx +32 -0
  92. package/dist/test-selection.jsx.map +1 -0
  93. package/dist/tui/App.d.ts +4 -0
  94. package/dist/tui/App.d.ts.map +1 -0
  95. package/dist/tui/App.js +167 -0
  96. package/dist/tui/App.js.map +1 -0
  97. package/dist/tui/App.jsx +281 -0
  98. package/dist/tui/App.jsx.map +1 -0
  99. package/dist/tui/components/BarChart.d.ts +17 -0
  100. package/dist/tui/components/BarChart.d.ts.map +1 -0
  101. package/dist/tui/components/BarChart.js +63 -0
  102. package/dist/tui/components/BarChart.js.map +1 -0
  103. package/dist/tui/components/BarChart.jsx +163 -0
  104. package/dist/tui/components/BarChart.jsx.map +1 -0
  105. package/dist/tui/components/DailyView.d.ts +13 -0
  106. package/dist/tui/components/DailyView.d.ts.map +1 -0
  107. package/dist/tui/components/DailyView.js +32 -0
  108. package/dist/tui/components/DailyView.js.map +1 -0
  109. package/dist/tui/components/DailyView.jsx +84 -0
  110. package/dist/tui/components/DailyView.jsx.map +1 -0
  111. package/dist/tui/components/DateBreakdownPanel.d.ts +7 -0
  112. package/dist/tui/components/DateBreakdownPanel.d.ts.map +1 -0
  113. package/dist/tui/components/DateBreakdownPanel.jsx +61 -0
  114. package/dist/tui/components/DateBreakdownPanel.jsx.map +1 -0
  115. package/dist/tui/components/Footer.d.ts +26 -0
  116. package/dist/tui/components/Footer.d.ts.map +1 -0
  117. package/dist/tui/components/Footer.js +15 -0
  118. package/dist/tui/components/Footer.js.map +1 -0
  119. package/dist/tui/components/Footer.jsx +158 -0
  120. package/dist/tui/components/Footer.jsx.map +1 -0
  121. package/dist/tui/components/Header.d.ts +9 -0
  122. package/dist/tui/components/Header.d.ts.map +1 -0
  123. package/dist/tui/components/Header.js +12 -0
  124. package/dist/tui/components/Header.js.map +1 -0
  125. package/dist/tui/components/Header.jsx +38 -0
  126. package/dist/tui/components/Header.jsx.map +1 -0
  127. package/dist/tui/components/Legend.d.ts +7 -0
  128. package/dist/tui/components/Legend.d.ts.map +1 -0
  129. package/dist/tui/components/Legend.js +9 -0
  130. package/dist/tui/components/Legend.js.map +1 -0
  131. package/dist/tui/components/Legend.jsx +27 -0
  132. package/dist/tui/components/Legend.jsx.map +1 -0
  133. package/dist/tui/components/LoadingSpinner.d.ts +8 -0
  134. package/dist/tui/components/LoadingSpinner.d.ts.map +1 -0
  135. package/dist/tui/components/LoadingSpinner.jsx +62 -0
  136. package/dist/tui/components/LoadingSpinner.jsx.map +1 -0
  137. package/dist/tui/components/ModelListItem.d.ts +11 -0
  138. package/dist/tui/components/ModelListItem.d.ts.map +1 -0
  139. package/dist/tui/components/ModelListItem.js +18 -0
  140. package/dist/tui/components/ModelListItem.js.map +1 -0
  141. package/dist/tui/components/ModelListItem.jsx +17 -0
  142. package/dist/tui/components/ModelListItem.jsx.map +1 -0
  143. package/dist/tui/components/ModelRow.d.ts +13 -0
  144. package/dist/tui/components/ModelRow.d.ts.map +1 -0
  145. package/dist/tui/components/ModelRow.jsx +28 -0
  146. package/dist/tui/components/ModelRow.jsx.map +1 -0
  147. package/dist/tui/components/ModelView.d.ts +13 -0
  148. package/dist/tui/components/ModelView.d.ts.map +1 -0
  149. package/dist/tui/components/ModelView.js +34 -0
  150. package/dist/tui/components/ModelView.js.map +1 -0
  151. package/dist/tui/components/ModelView.jsx +111 -0
  152. package/dist/tui/components/ModelView.jsx.map +1 -0
  153. package/dist/tui/components/OverviewView.d.ts +14 -0
  154. package/dist/tui/components/OverviewView.d.ts.map +1 -0
  155. package/dist/tui/components/OverviewView.js +24 -0
  156. package/dist/tui/components/OverviewView.js.map +1 -0
  157. package/dist/tui/components/OverviewView.jsx +79 -0
  158. package/dist/tui/components/OverviewView.jsx.map +1 -0
  159. package/dist/tui/components/StatsView.d.ts +12 -0
  160. package/dist/tui/components/StatsView.d.ts.map +1 -0
  161. package/dist/tui/components/StatsView.js +43 -0
  162. package/dist/tui/components/StatsView.js.map +1 -0
  163. package/dist/tui/components/StatsView.jsx +180 -0
  164. package/dist/tui/components/StatsView.jsx.map +1 -0
  165. package/dist/tui/components/TokenBreakdown.d.ts +14 -0
  166. package/dist/tui/components/TokenBreakdown.d.ts.map +1 -0
  167. package/dist/tui/components/TokenBreakdown.jsx +27 -0
  168. package/dist/tui/components/TokenBreakdown.jsx.map +1 -0
  169. package/dist/tui/components/index.d.ts +16 -0
  170. package/dist/tui/components/index.d.ts.map +1 -0
  171. package/dist/tui/components/index.js +13 -0
  172. package/dist/tui/components/index.js.map +1 -0
  173. package/dist/tui/config/settings.d.ts +12 -0
  174. package/dist/tui/config/settings.d.ts.map +1 -0
  175. package/dist/tui/config/settings.js +105 -0
  176. package/dist/tui/config/settings.js.map +1 -0
  177. package/dist/tui/config/themes.d.ts +15 -0
  178. package/dist/tui/config/themes.d.ts.map +1 -0
  179. package/dist/tui/config/themes.js +82 -0
  180. package/dist/tui/config/themes.js.map +1 -0
  181. package/dist/tui/hooks/useData.d.ts +17 -0
  182. package/dist/tui/hooks/useData.d.ts.map +1 -0
  183. package/dist/tui/hooks/useData.js +430 -0
  184. package/dist/tui/hooks/useData.js.map +1 -0
  185. package/dist/tui/index.d.ts +4 -0
  186. package/dist/tui/index.d.ts.map +1 -0
  187. package/dist/tui/index.js +8 -0
  188. package/dist/tui/index.js.map +1 -0
  189. package/dist/tui/index.jsx +35 -0
  190. package/dist/tui/index.jsx.map +1 -0
  191. package/dist/tui/types/index.d.ts +133 -0
  192. package/dist/tui/types/index.d.ts.map +1 -0
  193. package/dist/tui/types/index.js +21 -0
  194. package/dist/tui/types/index.js.map +1 -0
  195. package/dist/tui/utils/cleanup.d.ts +22 -0
  196. package/dist/tui/utils/cleanup.d.ts.map +1 -0
  197. package/dist/tui/utils/cleanup.js +59 -0
  198. package/dist/tui/utils/cleanup.js.map +1 -0
  199. package/dist/tui/utils/colors.d.ts +18 -0
  200. package/dist/tui/utils/colors.d.ts.map +1 -0
  201. package/dist/tui/utils/colors.js +55 -0
  202. package/dist/tui/utils/colors.js.map +1 -0
  203. package/dist/tui/utils/format.d.ts +7 -0
  204. package/dist/tui/utils/format.d.ts.map +1 -0
  205. package/dist/tui/utils/format.js +45 -0
  206. package/dist/tui/utils/format.js.map +1 -0
  207. package/dist/tui/utils/responsive.d.ts +5 -0
  208. package/dist/tui/utils/responsive.d.ts.map +1 -0
  209. package/dist/tui/utils/responsive.js +5 -0
  210. package/dist/tui/utils/responsive.js.map +1 -0
  211. package/package.json +64 -0
package/dist/cli.js ADDED
@@ -0,0 +1,761 @@
1
+ #!/usr/bin/env node
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 } from "commander";
9
+ import pc from "picocolors";
10
+ import { login, logout, whoami } from "./auth.js";
11
+ import { submit } from "./submit.js";
12
+ import { PricingFetcher } from "./pricing.js";
13
+ import { loadCursorCredentials, saveCursorCredentials, clearCursorCredentials, validateCursorSession, readCursorUsage, getCursorCredentialsPath, syncCursorCache, } from "./cursor.js";
14
+ import { createUsageTable, formatUsageRow, formatTotalsRow, formatNumber, formatCurrency, formatModelName, } from "./table.js";
15
+ import { isNativeAvailable, getNativeVersion, parseLocalSourcesAsync, finalizeReportAsync, finalizeMonthlyReportAsync, finalizeGraphAsync, } from "./native.js";
16
+ import { createSpinner } from "./spinner.js";
17
+ import * as fs from "node:fs";
18
+ import { performance } from "node:perf_hooks";
19
+ // =============================================================================
20
+ // Date Helpers
21
+ // =============================================================================
22
+ function formatDate(date) {
23
+ return date.toISOString().split("T")[0];
24
+ }
25
+ function getDateFilters(options) {
26
+ const today = new Date();
27
+ // --today: just today
28
+ if (options.today) {
29
+ const todayStr = formatDate(today);
30
+ return { since: todayStr, until: todayStr };
31
+ }
32
+ // --week: last 7 days
33
+ if (options.week) {
34
+ const weekAgo = new Date(today);
35
+ weekAgo.setDate(weekAgo.getDate() - 6); // Include today = 7 days
36
+ return { since: formatDate(weekAgo), until: formatDate(today) };
37
+ }
38
+ // --month: current calendar month
39
+ if (options.month) {
40
+ const startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
41
+ return { since: formatDate(startOfMonth), until: formatDate(today) };
42
+ }
43
+ // Explicit filters
44
+ return {
45
+ since: options.since,
46
+ until: options.until,
47
+ year: options.year,
48
+ };
49
+ }
50
+ function getDateRangeLabel(options) {
51
+ if (options.today)
52
+ return "Today";
53
+ if (options.week)
54
+ return "Last 7 days";
55
+ if (options.month) {
56
+ const today = new Date();
57
+ return today.toLocaleString("en-US", { month: "long", year: "numeric" });
58
+ }
59
+ if (options.year)
60
+ return options.year;
61
+ if (options.since || options.until) {
62
+ const parts = [];
63
+ if (options.since)
64
+ parts.push(`from ${options.since}`);
65
+ if (options.until)
66
+ parts.push(`to ${options.until}`);
67
+ return parts.join(" ");
68
+ }
69
+ return null;
70
+ }
71
+ function buildTUIOptions(options, initialTab) {
72
+ const dateFilters = getDateFilters(options);
73
+ const enabledSources = getEnabledSources(options);
74
+ return {
75
+ initialTab,
76
+ enabledSources: enabledSources,
77
+ since: dateFilters.since,
78
+ until: dateFilters.until,
79
+ year: dateFilters.year,
80
+ };
81
+ }
82
+ async function main() {
83
+ const program = new Command();
84
+ program
85
+ .name("tokscale")
86
+ .description("Token Usage Leaderboard CLI - Track AI coding costs across OpenCode, Claude Code, Codex, Gemini, and Cursor")
87
+ .version("1.0.2");
88
+ program
89
+ .command("monthly")
90
+ .description("Show monthly usage report (launches TUI by default)")
91
+ .option("--light", "Use legacy CLI table output instead of TUI")
92
+ .option("--json", "Output as JSON (for scripting)")
93
+ .option("--opencode", "Show only OpenCode usage")
94
+ .option("--claude", "Show only Claude Code usage")
95
+ .option("--codex", "Show only Codex CLI usage")
96
+ .option("--gemini", "Show only Gemini CLI usage")
97
+ .option("--cursor", "Show only Cursor IDE usage")
98
+ .option("--today", "Show only today's usage")
99
+ .option("--week", "Show last 7 days")
100
+ .option("--month", "Show current month")
101
+ .option("--since <date>", "Start date (YYYY-MM-DD)")
102
+ .option("--until <date>", "End date (YYYY-MM-DD)")
103
+ .option("--year <year>", "Filter to specific year")
104
+ .option("--benchmark", "Show processing time")
105
+ .action(async (options) => {
106
+ if (options.json) {
107
+ await outputJsonReport("monthly", options);
108
+ }
109
+ else if (options.light) {
110
+ await showMonthlyReport(options);
111
+ }
112
+ else {
113
+ const { launchTUI } = await import("./tui/index.js");
114
+ await launchTUI(buildTUIOptions(options, "daily"));
115
+ }
116
+ });
117
+ program
118
+ .command("models")
119
+ .description("Show usage breakdown by model (launches TUI by default)")
120
+ .option("--light", "Use legacy CLI table output instead of TUI")
121
+ .option("--json", "Output as JSON (for scripting)")
122
+ .option("--opencode", "Show only OpenCode usage")
123
+ .option("--claude", "Show only Claude Code usage")
124
+ .option("--codex", "Show only Codex CLI usage")
125
+ .option("--gemini", "Show only Gemini CLI usage")
126
+ .option("--cursor", "Show only Cursor IDE usage")
127
+ .option("--today", "Show only today's usage")
128
+ .option("--week", "Show last 7 days")
129
+ .option("--month", "Show current month")
130
+ .option("--since <date>", "Start date (YYYY-MM-DD)")
131
+ .option("--until <date>", "End date (YYYY-MM-DD)")
132
+ .option("--year <year>", "Filter to specific year")
133
+ .option("--benchmark", "Show processing time")
134
+ .action(async (options) => {
135
+ if (options.json) {
136
+ await outputJsonReport("models", options);
137
+ }
138
+ else if (options.light) {
139
+ await showModelReport(options);
140
+ }
141
+ else {
142
+ const { launchTUI } = await import("./tui/index.js");
143
+ await launchTUI(buildTUIOptions(options, "model"));
144
+ }
145
+ });
146
+ program
147
+ .command("graph")
148
+ .description("Export contribution graph data as JSON")
149
+ .option("--output <file>", "Write to file instead of stdout")
150
+ .option("--opencode", "Include only OpenCode data")
151
+ .option("--claude", "Include only Claude Code data")
152
+ .option("--codex", "Include only Codex CLI data")
153
+ .option("--gemini", "Include only Gemini CLI data")
154
+ .option("--cursor", "Include only Cursor IDE data")
155
+ .option("--today", "Show only today's usage")
156
+ .option("--week", "Show last 7 days")
157
+ .option("--month", "Show current month")
158
+ .option("--since <date>", "Start date (YYYY-MM-DD)")
159
+ .option("--until <date>", "End date (YYYY-MM-DD)")
160
+ .option("--year <year>", "Filter to specific year")
161
+ .option("--benchmark", "Show processing time")
162
+ .action(async (options) => {
163
+ await handleGraphCommand(options);
164
+ });
165
+ // =========================================================================
166
+ // Authentication Commands
167
+ // =========================================================================
168
+ program
169
+ .command("login")
170
+ .description("Login to Tokscale (opens browser for GitHub auth)")
171
+ .action(async () => {
172
+ await login();
173
+ });
174
+ program
175
+ .command("logout")
176
+ .description("Logout from Tokscale")
177
+ .action(async () => {
178
+ await logout();
179
+ });
180
+ program
181
+ .command("whoami")
182
+ .description("Show current logged in user")
183
+ .action(async () => {
184
+ await whoami();
185
+ });
186
+ // =========================================================================
187
+ // Submit Command
188
+ // =========================================================================
189
+ program
190
+ .command("submit")
191
+ .description("Submit your usage data to Tokscale")
192
+ .option("--opencode", "Include only OpenCode data")
193
+ .option("--claude", "Include only Claude Code data")
194
+ .option("--codex", "Include only Codex CLI data")
195
+ .option("--gemini", "Include only Gemini CLI data")
196
+ .option("--cursor", "Include only Cursor IDE data")
197
+ .option("--since <date>", "Start date (YYYY-MM-DD)")
198
+ .option("--until <date>", "End date (YYYY-MM-DD)")
199
+ .option("--year <year>", "Filter to specific year")
200
+ .option("--dry-run", "Show what would be submitted without actually submitting")
201
+ .action(async (options) => {
202
+ await submit({
203
+ opencode: options.opencode,
204
+ claude: options.claude,
205
+ codex: options.codex,
206
+ gemini: options.gemini,
207
+ cursor: options.cursor,
208
+ since: options.since,
209
+ until: options.until,
210
+ year: options.year,
211
+ dryRun: options.dryRun,
212
+ });
213
+ });
214
+ // =========================================================================
215
+ // Interactive TUI Command
216
+ // =========================================================================
217
+ program
218
+ .command("tui")
219
+ .description("Launch interactive terminal UI")
220
+ .option("--opencode", "Show only OpenCode usage")
221
+ .option("--claude", "Show only Claude Code usage")
222
+ .option("--codex", "Show only Codex CLI usage")
223
+ .option("--gemini", "Show only Gemini CLI usage")
224
+ .option("--cursor", "Show only Cursor IDE usage")
225
+ .option("--today", "Show only today's usage")
226
+ .option("--week", "Show last 7 days")
227
+ .option("--month", "Show current month")
228
+ .option("--since <date>", "Start date (YYYY-MM-DD)")
229
+ .option("--until <date>", "End date (YYYY-MM-DD)")
230
+ .option("--year <year>", "Filter to specific year")
231
+ .action(async (options) => {
232
+ const { launchTUI } = await import("./tui/index.js");
233
+ await launchTUI(buildTUIOptions(options));
234
+ });
235
+ // =========================================================================
236
+ // Cursor IDE Authentication Commands
237
+ // =========================================================================
238
+ const cursorCommand = program
239
+ .command("cursor")
240
+ .description("Cursor IDE integration commands");
241
+ cursorCommand
242
+ .command("login")
243
+ .description("Login to Cursor (paste your session token)")
244
+ .action(async () => {
245
+ await cursorLogin();
246
+ });
247
+ cursorCommand
248
+ .command("logout")
249
+ .description("Logout from Cursor")
250
+ .action(async () => {
251
+ await cursorLogout();
252
+ });
253
+ cursorCommand
254
+ .command("status")
255
+ .description("Check Cursor authentication status")
256
+ .action(async () => {
257
+ await cursorStatus();
258
+ });
259
+ // Check if a subcommand was provided
260
+ const args = process.argv.slice(2);
261
+ const firstArg = args[0] || '';
262
+ // Global flags should go to main program
263
+ const isGlobalFlag = ['--help', '-h', '--version', '-V'].includes(firstArg);
264
+ const hasSubcommand = args.length > 0 && !firstArg.startsWith('-');
265
+ const knownCommands = ['monthly', 'models', 'graph', 'login', 'logout', 'whoami', 'submit', 'cursor', 'tui', 'help'];
266
+ const isKnownCommand = hasSubcommand && knownCommands.includes(firstArg);
267
+ if (isKnownCommand || isGlobalFlag) {
268
+ // Run the specified subcommand or show full help/version
269
+ await program.parseAsync();
270
+ }
271
+ else {
272
+ // No subcommand - launch TUI by default, or legacy CLI with --light, or JSON with --json
273
+ const defaultProgram = new Command();
274
+ defaultProgram
275
+ .option("--light", "Use legacy CLI table output instead of TUI")
276
+ .option("--json", "Output as JSON (for scripting)")
277
+ .option("--opencode", "Show only OpenCode usage")
278
+ .option("--claude", "Show only Claude Code usage")
279
+ .option("--codex", "Show only Codex CLI usage")
280
+ .option("--gemini", "Show only Gemini CLI usage")
281
+ .option("--cursor", "Show only Cursor IDE usage")
282
+ .option("--today", "Show only today's usage")
283
+ .option("--week", "Show last 7 days")
284
+ .option("--month", "Show current month")
285
+ .option("--since <date>", "Start date (YYYY-MM-DD)")
286
+ .option("--until <date>", "End date (YYYY-MM-DD)")
287
+ .option("--year <year>", "Filter to specific year")
288
+ .option("--benchmark", "Show processing time")
289
+ .parse();
290
+ const opts = defaultProgram.opts();
291
+ if (opts.json) {
292
+ await outputJsonReport("models", opts);
293
+ }
294
+ else if (opts.light) {
295
+ await showModelReport(opts);
296
+ }
297
+ else {
298
+ const { launchTUI } = await import("./tui/index.js");
299
+ await launchTUI(buildTUIOptions(opts));
300
+ }
301
+ }
302
+ }
303
+ function getEnabledSources(options) {
304
+ const hasFilter = options.opencode || options.claude || options.codex || options.gemini || options.cursor;
305
+ if (!hasFilter)
306
+ return undefined; // All sources
307
+ const sources = [];
308
+ if (options.opencode)
309
+ sources.push("opencode");
310
+ if (options.claude)
311
+ sources.push("claude");
312
+ if (options.codex)
313
+ sources.push("codex");
314
+ if (options.gemini)
315
+ sources.push("gemini");
316
+ if (options.cursor)
317
+ sources.push("cursor");
318
+ return sources;
319
+ }
320
+ function logNativeStatus() {
321
+ if (!isNativeAvailable()) {
322
+ console.log(pc.yellow(" Note: Using TypeScript fallback (native module not available)"));
323
+ console.log(pc.gray(" Run 'bun run build:core' for ~10x faster processing.\n"));
324
+ }
325
+ }
326
+ async function fetchPricingData() {
327
+ const fetcher = new PricingFetcher();
328
+ await fetcher.fetchPricing();
329
+ return fetcher;
330
+ }
331
+ /**
332
+ * Sync Cursor usage data from API to local cache.
333
+ * Only attempts sync if user is authenticated with Cursor.
334
+ */
335
+ async function syncCursorData() {
336
+ const credentials = loadCursorCredentials();
337
+ if (!credentials) {
338
+ return { attempted: false, synced: false, rows: 0 };
339
+ }
340
+ const result = await syncCursorCache();
341
+ return {
342
+ attempted: true,
343
+ synced: result.synced,
344
+ rows: result.rows,
345
+ error: result.error,
346
+ };
347
+ }
348
+ /**
349
+ * Load all data sources in parallel (two-phase optimization):
350
+ * - Cursor API sync (network)
351
+ * - Pricing fetch (network)
352
+ * - Local file parsing (CPU/IO) - OpenCode, Claude, Codex, Gemini
353
+ *
354
+ * This overlaps network I/O with local file parsing for better performance.
355
+ */
356
+ async function loadDataSourcesParallel(localSources, dateFilters) {
357
+ // Skip local parsing if no local sources requested (e.g., cursor-only mode)
358
+ const shouldParseLocal = localSources.length > 0;
359
+ // Use Promise.allSettled for graceful degradation
360
+ const [cursorResult, pricingResult, localResult] = await Promise.allSettled([
361
+ syncCursorData(),
362
+ fetchPricingData(),
363
+ // Parse local sources in parallel (excludes Cursor) - skip if empty
364
+ shouldParseLocal
365
+ ? parseLocalSourcesAsync({
366
+ sources: localSources.filter(s => s !== 'cursor'),
367
+ since: dateFilters.since,
368
+ until: dateFilters.until,
369
+ year: dateFilters.year,
370
+ })
371
+ : Promise.resolve(null),
372
+ ]);
373
+ // Handle partial failures gracefully
374
+ const cursorSync = cursorResult.status === 'fulfilled'
375
+ ? cursorResult.value
376
+ : { attempted: true, synced: false, rows: 0, error: 'Cursor sync failed' };
377
+ const fetcher = pricingResult.status === 'fulfilled'
378
+ ? pricingResult.value
379
+ : new PricingFetcher(); // Empty pricing → costs = 0
380
+ const localMessages = localResult.status === 'fulfilled'
381
+ ? localResult.value
382
+ : null;
383
+ return { fetcher, cursorSync, localMessages };
384
+ }
385
+ async function showModelReport(options) {
386
+ logNativeStatus();
387
+ const dateFilters = getDateFilters(options);
388
+ const enabledSources = getEnabledSources(options);
389
+ const onlyCursor = enabledSources?.length === 1 && enabledSources[0] === 'cursor';
390
+ const includeCursor = !enabledSources || enabledSources.includes('cursor');
391
+ // Check cursor auth early if cursor-only mode
392
+ if (onlyCursor) {
393
+ const credentials = loadCursorCredentials();
394
+ if (!credentials) {
395
+ console.log(pc.red("\n Error: Cursor authentication required."));
396
+ console.log(pc.gray(" Run 'tokscale cursor login' to authenticate with Cursor.\n"));
397
+ process.exit(1);
398
+ }
399
+ }
400
+ const dateRange = getDateRangeLabel(options);
401
+ const title = dateRange
402
+ ? `Token Usage Report by Model (${dateRange})`
403
+ : "Token Usage Report by Model";
404
+ console.log(pc.cyan(`\n ${title}`));
405
+ if (options.benchmark) {
406
+ console.log(pc.gray(` Using: Rust native module v${getNativeVersion()}`));
407
+ }
408
+ console.log();
409
+ // Start spinner for loading phase
410
+ const spinner = createSpinner({ color: "cyan" });
411
+ spinner.start(pc.gray("Loading data sources..."));
412
+ // Filter out cursor for local parsing (it's synced separately via network)
413
+ const localSources = (enabledSources || ['opencode', 'claude', 'codex', 'gemini', 'cursor'])
414
+ .filter(s => s !== 'cursor');
415
+ // Two-phase parallel loading: network (Cursor + pricing) overlaps with local file parsing
416
+ // If cursor-only, skip local parsing entirely
417
+ const { fetcher, cursorSync, localMessages } = await loadDataSourcesParallel(onlyCursor ? [] : localSources, dateFilters);
418
+ if (!localMessages && !onlyCursor) {
419
+ spinner.error('Failed to parse local session files');
420
+ process.exit(1);
421
+ }
422
+ spinner.update(pc.gray("Finalizing report..."));
423
+ const startTime = performance.now();
424
+ let report;
425
+ try {
426
+ const emptyMessages = { messages: [], opencodeCount: 0, claudeCount: 0, codexCount: 0, geminiCount: 0, processingTimeMs: 0 };
427
+ report = await finalizeReportAsync({
428
+ localMessages: localMessages || emptyMessages,
429
+ pricing: fetcher.toPricingEntries(),
430
+ includeCursor: includeCursor && cursorSync.synced,
431
+ since: dateFilters.since,
432
+ until: dateFilters.until,
433
+ year: dateFilters.year,
434
+ });
435
+ }
436
+ catch (e) {
437
+ spinner.error(`Error: ${e.message}`);
438
+ process.exit(1);
439
+ }
440
+ const processingTime = performance.now() - startTime;
441
+ spinner.stop();
442
+ if (report.entries.length === 0) {
443
+ if (onlyCursor && !cursorSync.synced) {
444
+ console.log(pc.yellow(" No Cursor data available."));
445
+ console.log(pc.gray(" Run 'tokscale cursor login' to authenticate with Cursor.\n"));
446
+ }
447
+ else {
448
+ console.log(pc.yellow(" No usage data found.\n"));
449
+ }
450
+ return;
451
+ }
452
+ // Create table
453
+ const table = createUsageTable("Source/Model");
454
+ for (const entry of report.entries) {
455
+ const sourceLabel = getSourceLabel(entry.source);
456
+ const modelDisplay = `${pc.dim(sourceLabel)} ${formatModelName(entry.model)}`;
457
+ table.push(formatUsageRow(modelDisplay, [entry.model], entry.input, entry.output, entry.cacheWrite, entry.cacheRead, entry.cost));
458
+ }
459
+ // Add totals row
460
+ table.push(formatTotalsRow(report.totalInput, report.totalOutput, report.totalCacheWrite, report.totalCacheRead, report.totalCost));
461
+ console.log(table.toString());
462
+ // Summary stats
463
+ console.log(pc.gray(`\n Total: ${formatNumber(report.totalMessages)} messages, ` +
464
+ `${formatNumber(report.totalInput + report.totalOutput + report.totalCacheRead + report.totalCacheWrite)} tokens, ` +
465
+ `${pc.green(formatCurrency(report.totalCost))}`));
466
+ if (options.benchmark) {
467
+ console.log(pc.gray(` Processing time: ${processingTime.toFixed(0)}ms (Rust) + ${report.processingTimeMs}ms (parsing)`));
468
+ if (cursorSync.attempted) {
469
+ if (cursorSync.synced) {
470
+ console.log(pc.gray(` Cursor: ${cursorSync.rows} usage events synced (full lifetime data)`));
471
+ }
472
+ else {
473
+ console.log(pc.yellow(` Cursor: sync failed - ${cursorSync.error}`));
474
+ }
475
+ }
476
+ }
477
+ console.log();
478
+ }
479
+ async function showMonthlyReport(options) {
480
+ logNativeStatus();
481
+ const dateRange = getDateRangeLabel(options);
482
+ const title = dateRange
483
+ ? `Monthly Token Usage Report (${dateRange})`
484
+ : "Monthly Token Usage Report";
485
+ console.log(pc.cyan(`\n ${title}`));
486
+ if (options.benchmark) {
487
+ console.log(pc.gray(` Using: Rust native module v${getNativeVersion()}`));
488
+ }
489
+ console.log();
490
+ // Start spinner for loading phase
491
+ const spinner = createSpinner({ color: "cyan" });
492
+ spinner.start(pc.gray("Loading data sources..."));
493
+ const dateFilters = getDateFilters(options);
494
+ const enabledSources = getEnabledSources(options);
495
+ // Filter out cursor for local parsing (it's synced separately via network)
496
+ const localSources = (enabledSources || ['opencode', 'claude', 'codex', 'gemini', 'cursor'])
497
+ .filter(s => s !== 'cursor');
498
+ const includeCursor = !enabledSources || enabledSources.includes('cursor');
499
+ // Two-phase parallel loading: network (Cursor + pricing) overlaps with local file parsing
500
+ const { fetcher, cursorSync, localMessages } = await loadDataSourcesParallel(localSources, dateFilters);
501
+ if (!localMessages) {
502
+ spinner.error('Failed to parse local session files');
503
+ process.exit(1);
504
+ }
505
+ spinner.update(pc.gray("Finalizing report..."));
506
+ const startTime = performance.now();
507
+ let report;
508
+ try {
509
+ report = await finalizeMonthlyReportAsync({
510
+ localMessages,
511
+ pricing: fetcher.toPricingEntries(),
512
+ includeCursor: includeCursor && cursorSync.synced,
513
+ since: dateFilters.since,
514
+ until: dateFilters.until,
515
+ year: dateFilters.year,
516
+ });
517
+ }
518
+ catch (e) {
519
+ spinner.error(`Error: ${e.message}`);
520
+ process.exit(1);
521
+ }
522
+ const processingTime = performance.now() - startTime;
523
+ spinner.stop();
524
+ if (report.entries.length === 0) {
525
+ console.log(pc.yellow(" No usage data found.\n"));
526
+ return;
527
+ }
528
+ // Create table
529
+ const table = createUsageTable("Month");
530
+ for (const entry of report.entries) {
531
+ table.push(formatUsageRow(entry.month, entry.models, entry.input, entry.output, entry.cacheWrite, entry.cacheRead, entry.cost));
532
+ }
533
+ // Add totals row
534
+ const totalInput = report.entries.reduce((sum, e) => sum + e.input, 0);
535
+ const totalOutput = report.entries.reduce((sum, e) => sum + e.output, 0);
536
+ const totalCacheRead = report.entries.reduce((sum, e) => sum + e.cacheRead, 0);
537
+ const totalCacheWrite = report.entries.reduce((sum, e) => sum + e.cacheWrite, 0);
538
+ table.push(formatTotalsRow(totalInput, totalOutput, totalCacheWrite, totalCacheRead, report.totalCost));
539
+ console.log(table.toString());
540
+ console.log(pc.gray(`\n Total Cost: ${pc.green(formatCurrency(report.totalCost))}`));
541
+ if (options.benchmark) {
542
+ console.log(pc.gray(` Processing time: ${processingTime.toFixed(0)}ms (Rust) + ${report.processingTimeMs}ms (parsing)`));
543
+ if (cursorSync.attempted) {
544
+ if (cursorSync.synced) {
545
+ console.log(pc.gray(` Cursor: ${cursorSync.rows} usage events synced (full lifetime data)`));
546
+ }
547
+ else {
548
+ console.log(pc.yellow(` Cursor: sync failed - ${cursorSync.error}`));
549
+ }
550
+ }
551
+ }
552
+ console.log();
553
+ }
554
+ async function outputJsonReport(reportType, options) {
555
+ logNativeStatus();
556
+ const dateFilters = getDateFilters(options);
557
+ const enabledSources = getEnabledSources(options);
558
+ const onlyCursor = enabledSources?.length === 1 && enabledSources[0] === 'cursor';
559
+ const includeCursor = !enabledSources || enabledSources.includes('cursor');
560
+ const localSources = (enabledSources || ['opencode', 'claude', 'codex', 'gemini', 'cursor'])
561
+ .filter(s => s !== 'cursor');
562
+ const { fetcher, cursorSync, localMessages } = await loadDataSourcesParallel(onlyCursor ? [] : localSources, dateFilters);
563
+ if (!localMessages && !onlyCursor) {
564
+ console.error(JSON.stringify({ error: "Failed to parse local session files" }));
565
+ process.exit(1);
566
+ }
567
+ const emptyMessages = { messages: [], opencodeCount: 0, claudeCount: 0, codexCount: 0, geminiCount: 0, processingTimeMs: 0 };
568
+ if (reportType === "models") {
569
+ const report = await finalizeReportAsync({
570
+ localMessages: localMessages || emptyMessages,
571
+ pricing: fetcher.toPricingEntries(),
572
+ includeCursor: includeCursor && cursorSync.synced,
573
+ since: dateFilters.since,
574
+ until: dateFilters.until,
575
+ year: dateFilters.year,
576
+ });
577
+ console.log(JSON.stringify(report, null, 2));
578
+ }
579
+ else {
580
+ const report = await finalizeMonthlyReportAsync({
581
+ localMessages: localMessages || emptyMessages,
582
+ pricing: fetcher.toPricingEntries(),
583
+ includeCursor: includeCursor && cursorSync.synced,
584
+ since: dateFilters.since,
585
+ until: dateFilters.until,
586
+ year: dateFilters.year,
587
+ });
588
+ console.log(JSON.stringify(report, null, 2));
589
+ }
590
+ }
591
+ async function handleGraphCommand(options) {
592
+ logNativeStatus();
593
+ // Start spinner for loading phase (only if outputting to file, not stdout)
594
+ const spinner = options.output ? createSpinner({ color: "cyan" }) : null;
595
+ spinner?.start(pc.gray("Loading data sources..."));
596
+ const dateFilters = getDateFilters(options);
597
+ const enabledSources = getEnabledSources(options);
598
+ // Filter out cursor for local parsing (it's synced separately via network)
599
+ const localSources = (enabledSources || ['opencode', 'claude', 'codex', 'gemini', 'cursor'])
600
+ .filter(s => s !== 'cursor');
601
+ const includeCursor = !enabledSources || enabledSources.includes('cursor');
602
+ // Two-phase parallel loading: network (Cursor + pricing) overlaps with local file parsing
603
+ const { fetcher, cursorSync, localMessages } = await loadDataSourcesParallel(localSources, dateFilters);
604
+ if (!localMessages) {
605
+ spinner?.error('Failed to parse local session files');
606
+ process.exit(1);
607
+ }
608
+ spinner?.update(pc.gray("Generating graph data..."));
609
+ const startTime = performance.now();
610
+ const data = await finalizeGraphAsync({
611
+ localMessages,
612
+ pricing: fetcher.toPricingEntries(),
613
+ includeCursor: includeCursor && cursorSync.synced,
614
+ since: dateFilters.since,
615
+ until: dateFilters.until,
616
+ year: dateFilters.year,
617
+ });
618
+ const processingTime = performance.now() - startTime;
619
+ spinner?.stop();
620
+ const jsonOutput = JSON.stringify(data, null, 2);
621
+ // Output to file or stdout
622
+ if (options.output) {
623
+ fs.writeFileSync(options.output, jsonOutput, "utf-8");
624
+ console.error(pc.green(`✓ Graph data written to ${options.output}`));
625
+ console.error(pc.gray(` ${data.contributions.length} days, ${data.summary.sources.length} sources, ${data.summary.models.length} models`));
626
+ console.error(pc.gray(` Total: ${formatCurrency(data.summary.totalCost)}`));
627
+ if (options.benchmark) {
628
+ console.error(pc.gray(` Processing time: ${processingTime.toFixed(0)}ms (Rust native)`));
629
+ if (cursorSync.attempted) {
630
+ if (cursorSync.synced) {
631
+ console.error(pc.gray(` Cursor: ${cursorSync.rows} usage events synced (full lifetime data)`));
632
+ }
633
+ else {
634
+ console.error(pc.yellow(` Cursor: sync failed - ${cursorSync.error}`));
635
+ }
636
+ }
637
+ }
638
+ }
639
+ else {
640
+ console.log(jsonOutput);
641
+ }
642
+ }
643
+ function getSourceLabel(source) {
644
+ switch (source) {
645
+ case "opencode":
646
+ return "OpenCode";
647
+ case "claude":
648
+ return "Claude";
649
+ case "codex":
650
+ return "Codex";
651
+ case "gemini":
652
+ return "Gemini";
653
+ case "cursor":
654
+ return "Cursor";
655
+ default:
656
+ return source;
657
+ }
658
+ }
659
+ // =============================================================================
660
+ // Cursor IDE Authentication
661
+ // =============================================================================
662
+ async function cursorLogin() {
663
+ const credentials = loadCursorCredentials();
664
+ if (credentials) {
665
+ console.log(pc.yellow("\n Already logged in to Cursor."));
666
+ console.log(pc.gray(" Run 'tokscale cursor logout' to sign out first.\n"));
667
+ return;
668
+ }
669
+ console.log(pc.cyan("\n Cursor IDE - Login\n"));
670
+ console.log(pc.white(" To get your session token:"));
671
+ console.log(pc.gray(" 1. Open https://www.cursor.com/settings in your browser"));
672
+ console.log(pc.gray(" 2. Open Developer Tools (F12) > Network tab"));
673
+ console.log(pc.gray(" 3. Find any request to cursor.com/api"));
674
+ console.log(pc.gray(" 4. Copy the 'WorkosCursorSessionToken' cookie value"));
675
+ console.log();
676
+ // Read token from stdin
677
+ const readline = await import("node:readline");
678
+ const rl = readline.createInterface({
679
+ input: process.stdin,
680
+ output: process.stdout,
681
+ });
682
+ const token = await new Promise((resolve) => {
683
+ rl.question(pc.white(" Paste your session token: "), (answer) => {
684
+ rl.close();
685
+ resolve(answer.trim());
686
+ });
687
+ });
688
+ if (!token) {
689
+ console.log(pc.red("\n No token provided. Login cancelled.\n"));
690
+ return;
691
+ }
692
+ // Validate the token
693
+ console.log(pc.gray("\n Validating token..."));
694
+ const validation = await validateCursorSession(token);
695
+ if (!validation.valid) {
696
+ console.log(pc.red(`\n Invalid token: ${validation.error}`));
697
+ console.log(pc.gray(" Please try again with a valid session token.\n"));
698
+ return;
699
+ }
700
+ // Save credentials
701
+ saveCursorCredentials({
702
+ sessionToken: token,
703
+ createdAt: new Date().toISOString(),
704
+ });
705
+ console.log(pc.green("\n Success! Logged in to Cursor."));
706
+ if (validation.membershipType) {
707
+ console.log(pc.gray(` Membership: ${validation.membershipType}`));
708
+ }
709
+ console.log(pc.gray(" Your usage data will now be included in reports.\n"));
710
+ }
711
+ async function cursorLogout() {
712
+ const credentials = loadCursorCredentials();
713
+ if (!credentials) {
714
+ console.log(pc.yellow("\n Not logged in to Cursor.\n"));
715
+ return;
716
+ }
717
+ const cleared = clearCursorCredentials();
718
+ if (cleared) {
719
+ console.log(pc.green("\n Logged out from Cursor.\n"));
720
+ }
721
+ else {
722
+ console.error(pc.red("\n Failed to clear Cursor credentials.\n"));
723
+ process.exit(1);
724
+ }
725
+ }
726
+ async function cursorStatus() {
727
+ const credentials = loadCursorCredentials();
728
+ if (!credentials) {
729
+ console.log(pc.yellow("\n Not logged in to Cursor."));
730
+ console.log(pc.gray(" Run 'tokscale cursor login' to authenticate.\n"));
731
+ return;
732
+ }
733
+ console.log(pc.cyan("\n Cursor IDE - Status\n"));
734
+ console.log(pc.gray(" Checking session validity..."));
735
+ const validation = await validateCursorSession(credentials.sessionToken);
736
+ if (validation.valid) {
737
+ console.log(pc.green(" ✓ Session is valid"));
738
+ if (validation.membershipType) {
739
+ console.log(pc.white(` Membership: ${validation.membershipType}`));
740
+ }
741
+ console.log(pc.gray(` Logged in: ${new Date(credentials.createdAt).toLocaleDateString()}`));
742
+ // Try to fetch usage to show summary
743
+ try {
744
+ const usage = await readCursorUsage();
745
+ const totalCost = usage.byModel.reduce((sum, m) => sum + m.cost, 0);
746
+ console.log(pc.gray(` Models used: ${usage.byModel.length}`));
747
+ console.log(pc.gray(` Total usage events: ${usage.rows.length}`));
748
+ console.log(pc.gray(` Total cost: $${totalCost.toFixed(2)}`));
749
+ }
750
+ catch (e) {
751
+ // Ignore fetch errors for status check
752
+ }
753
+ }
754
+ else {
755
+ console.log(pc.red(` ✗ Session invalid: ${validation.error}`));
756
+ console.log(pc.gray(" Run 'tokscale cursor login' to re-authenticate."));
757
+ }
758
+ console.log(pc.gray(`\n Credentials: ${getCursorCredentialsPath()}\n`));
759
+ }
760
+ main().catch(console.error);
761
+ //# sourceMappingURL=cli.js.map