@tokscale/cli 1.0.6 → 1.0.8

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.
package/src/cli.ts ADDED
@@ -0,0 +1,1042 @@
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
+
9
+ import { Command } from "commander";
10
+ import { createRequire } from "module";
11
+ const require = createRequire(import.meta.url);
12
+ const pkg = require("../package.json") as { version: string };
13
+ import pc from "picocolors";
14
+ import { login, logout, whoami } from "./auth.js";
15
+ import { submit } from "./submit.js";
16
+ import { PricingFetcher } from "./pricing.js";
17
+ import {
18
+ loadCursorCredentials,
19
+ saveCursorCredentials,
20
+ clearCursorCredentials,
21
+ validateCursorSession,
22
+ readCursorUsage,
23
+ getCursorCredentialsPath,
24
+ syncCursorCache,
25
+ } from "./cursor.js";
26
+ import {
27
+ createUsageTable,
28
+ formatUsageRow,
29
+ formatTotalsRow,
30
+ formatNumber,
31
+ formatCurrency,
32
+ formatModelName,
33
+ } from "./table.js";
34
+ import {
35
+ isNativeAvailable,
36
+ getNativeVersion,
37
+ parseLocalSourcesAsync,
38
+ finalizeReportAsync,
39
+ finalizeMonthlyReportAsync,
40
+ finalizeGraphAsync,
41
+ type ModelReport,
42
+ type MonthlyReport,
43
+ type ParsedMessages,
44
+ } from "./native.js";
45
+ import { createSpinner } from "./spinner.js";
46
+ import * as fs from "node:fs";
47
+ import { performance } from "node:perf_hooks";
48
+ import type { SourceType } from "./graph-types.js";
49
+ import type { TUIOptions, TabType } from "./tui/types/index.js";
50
+
51
+ type LaunchTUIFunction = (options?: TUIOptions) => Promise<void>;
52
+
53
+ let cachedTUILoader: LaunchTUIFunction | null = null;
54
+ let tuiLoadAttempted = false;
55
+
56
+ async function tryLoadTUI(): Promise<LaunchTUIFunction | null> {
57
+ if (tuiLoadAttempted) return cachedTUILoader;
58
+ tuiLoadAttempted = true;
59
+
60
+ const isBun = typeof (globalThis as Record<string, unknown>).Bun !== "undefined";
61
+
62
+ if (!isBun) {
63
+ return null;
64
+ }
65
+
66
+ const currentDir = new URL(".", import.meta.url).pathname;
67
+ const isDevMode = currentDir.includes("/src/");
68
+ // In dev mode: load TSX directly (bunfig.toml preloads Solid plugin)
69
+ // In prod mode: load pre-compiled JS from dist/tui/ (no preload needed)
70
+ const tuiPath = isDevMode
71
+ ? new URL("./tui/index.tsx", import.meta.url).href
72
+ : new URL("./tui/index.js", import.meta.url).href;
73
+
74
+ try {
75
+ const tuiModule = await import(tuiPath) as { launchTUI: LaunchTUIFunction };
76
+ cachedTUILoader = tuiModule.launchTUI;
77
+ return cachedTUILoader;
78
+ } catch (error) {
79
+ if (process.env.DEBUG) {
80
+ console.error("TUI load error:", error);
81
+ }
82
+ return null;
83
+ }
84
+ }
85
+
86
+ function showTUIUnavailableMessage(): void {
87
+ console.log(pc.yellow("\n TUI mode requires Bun runtime."));
88
+ console.log(pc.gray(" OpenTUI's native modules are not compatible with Node.js."));
89
+ console.log();
90
+ console.log(pc.white(" Options:"));
91
+ console.log(pc.gray(" • Use 'bunx tokscale' instead of 'npx tokscale'"));
92
+ // console.log(pc.gray(" • Use '--light' flag for legacy CLI table output"));
93
+ console.log(pc.gray(" • Use '--json' flag for JSON output"));
94
+ console.log();
95
+ }
96
+
97
+ interface FilterOptions {
98
+ opencode?: boolean;
99
+ claude?: boolean;
100
+ codex?: boolean;
101
+ gemini?: boolean;
102
+ cursor?: boolean;
103
+ }
104
+
105
+ interface DateFilterOptions {
106
+ since?: string;
107
+ until?: string;
108
+ year?: string;
109
+ today?: boolean;
110
+ week?: boolean;
111
+ month?: boolean;
112
+ }
113
+
114
+ interface CursorSyncResult {
115
+ /** Whether a sync was attempted (true if credentials exist) */
116
+ attempted: boolean;
117
+ /** Whether the sync succeeded */
118
+ synced: boolean;
119
+ /** Number of usage events fetched */
120
+ rows: number;
121
+ /** Error message if sync failed */
122
+ error?: string;
123
+ }
124
+
125
+ // =============================================================================
126
+ // Date Helpers
127
+ // =============================================================================
128
+
129
+ function formatDate(date: Date): string {
130
+ return date.toISOString().split("T")[0];
131
+ }
132
+
133
+ function getDateFilters(options: DateFilterOptions): { since?: string; until?: string; year?: string } {
134
+ const today = new Date();
135
+
136
+ // --today: just today
137
+ if (options.today) {
138
+ const todayStr = formatDate(today);
139
+ return { since: todayStr, until: todayStr };
140
+ }
141
+
142
+ // --week: last 7 days
143
+ if (options.week) {
144
+ const weekAgo = new Date(today);
145
+ weekAgo.setDate(weekAgo.getDate() - 6); // Include today = 7 days
146
+ return { since: formatDate(weekAgo), until: formatDate(today) };
147
+ }
148
+
149
+ // --month: current calendar month
150
+ if (options.month) {
151
+ const startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
152
+ return { since: formatDate(startOfMonth), until: formatDate(today) };
153
+ }
154
+
155
+ // Explicit filters
156
+ return {
157
+ since: options.since,
158
+ until: options.until,
159
+ year: options.year,
160
+ };
161
+ }
162
+
163
+ function getDateRangeLabel(options: DateFilterOptions): string | null {
164
+ if (options.today) return "Today";
165
+ if (options.week) return "Last 7 days";
166
+ if (options.month) {
167
+ const today = new Date();
168
+ return today.toLocaleString("en-US", { month: "long", year: "numeric" } as Intl.DateTimeFormatOptions);
169
+ }
170
+ if (options.year) return options.year;
171
+ if (options.since || options.until) {
172
+ const parts: string[] = [];
173
+ if (options.since) parts.push(`from ${options.since}`);
174
+ if (options.until) parts.push(`to ${options.until}`);
175
+ return parts.join(" ");
176
+ }
177
+ return null;
178
+ }
179
+
180
+ function buildTUIOptions(
181
+ options: FilterOptions & DateFilterOptions,
182
+ initialTab?: TabType
183
+ ): TUIOptions {
184
+ const dateFilters = getDateFilters(options);
185
+ const enabledSources = getEnabledSources(options);
186
+
187
+ return {
188
+ initialTab,
189
+ enabledSources: enabledSources as TUIOptions["enabledSources"],
190
+ since: dateFilters.since,
191
+ until: dateFilters.until,
192
+ year: dateFilters.year,
193
+ };
194
+ }
195
+
196
+ async function main() {
197
+ const program = new Command();
198
+
199
+ program
200
+ .name("tokscale")
201
+ .description("Token Usage Leaderboard CLI - Track AI coding costs across OpenCode, Claude Code, Codex, Gemini, and Cursor")
202
+ .version(pkg.version);
203
+
204
+ program
205
+ .command("monthly")
206
+ .description("Show monthly usage report (launches TUI by default)")
207
+ .option("--light", "Use legacy CLI table output instead of TUI")
208
+ .option("--json", "Output as JSON (for scripting)")
209
+ .option("--opencode", "Show only OpenCode usage")
210
+ .option("--claude", "Show only Claude Code usage")
211
+ .option("--codex", "Show only Codex CLI usage")
212
+ .option("--gemini", "Show only Gemini CLI usage")
213
+ .option("--cursor", "Show only Cursor IDE usage")
214
+ .option("--today", "Show only today's usage")
215
+ .option("--week", "Show last 7 days")
216
+ .option("--month", "Show current month")
217
+ .option("--since <date>", "Start date (YYYY-MM-DD)")
218
+ .option("--until <date>", "End date (YYYY-MM-DD)")
219
+ .option("--year <year>", "Filter to specific year")
220
+ .option("--benchmark", "Show processing time")
221
+ .action(async (options) => {
222
+ if (options.json) {
223
+ await outputJsonReport("monthly", options);
224
+ } else if (options.light) {
225
+ await showMonthlyReport(options);
226
+ } else {
227
+ const launchTUI = await tryLoadTUI();
228
+ if (launchTUI) {
229
+ await launchTUI(buildTUIOptions(options, "daily"));
230
+ } else {
231
+ showTUIUnavailableMessage();
232
+ await showMonthlyReport(options);
233
+ }
234
+ }
235
+ });
236
+
237
+ program
238
+ .command("models")
239
+ .description("Show usage breakdown by model (launches TUI by default)")
240
+ .option("--light", "Use legacy CLI table output instead of TUI")
241
+ .option("--json", "Output as JSON (for scripting)")
242
+ .option("--opencode", "Show only OpenCode usage")
243
+ .option("--claude", "Show only Claude Code usage")
244
+ .option("--codex", "Show only Codex CLI usage")
245
+ .option("--gemini", "Show only Gemini CLI usage")
246
+ .option("--cursor", "Show only Cursor IDE usage")
247
+ .option("--today", "Show only today's usage")
248
+ .option("--week", "Show last 7 days")
249
+ .option("--month", "Show current month")
250
+ .option("--since <date>", "Start date (YYYY-MM-DD)")
251
+ .option("--until <date>", "End date (YYYY-MM-DD)")
252
+ .option("--year <year>", "Filter to specific year")
253
+ .option("--benchmark", "Show processing time")
254
+ .action(async (options) => {
255
+ if (options.json) {
256
+ await outputJsonReport("models", options);
257
+ } else if (options.light) {
258
+ await showModelReport(options);
259
+ } else {
260
+ const launchTUI = await tryLoadTUI();
261
+ if (launchTUI) {
262
+ await launchTUI(buildTUIOptions(options, "model"));
263
+ } else {
264
+ showTUIUnavailableMessage();
265
+ await showModelReport(options);
266
+ }
267
+ }
268
+ });
269
+
270
+ program
271
+ .command("graph")
272
+ .description("Export contribution graph data as JSON")
273
+ .option("--output <file>", "Write to file instead of stdout")
274
+ .option("--opencode", "Include only OpenCode data")
275
+ .option("--claude", "Include only Claude Code data")
276
+ .option("--codex", "Include only Codex CLI data")
277
+ .option("--gemini", "Include only Gemini CLI data")
278
+ .option("--cursor", "Include only Cursor IDE data")
279
+ .option("--today", "Show only today's usage")
280
+ .option("--week", "Show last 7 days")
281
+ .option("--month", "Show current month")
282
+ .option("--since <date>", "Start date (YYYY-MM-DD)")
283
+ .option("--until <date>", "End date (YYYY-MM-DD)")
284
+ .option("--year <year>", "Filter to specific year")
285
+ .option("--benchmark", "Show processing time")
286
+ .action(async (options) => {
287
+ await handleGraphCommand(options);
288
+ });
289
+
290
+ // =========================================================================
291
+ // Authentication Commands
292
+ // =========================================================================
293
+
294
+ program
295
+ .command("login")
296
+ .description("Login to Tokscale (opens browser for GitHub auth)")
297
+ .action(async () => {
298
+ await login();
299
+ });
300
+
301
+ program
302
+ .command("logout")
303
+ .description("Logout from Tokscale")
304
+ .action(async () => {
305
+ await logout();
306
+ });
307
+
308
+ program
309
+ .command("whoami")
310
+ .description("Show current logged in user")
311
+ .action(async () => {
312
+ await whoami();
313
+ });
314
+
315
+ // =========================================================================
316
+ // Submit Command
317
+ // =========================================================================
318
+
319
+ program
320
+ .command("submit")
321
+ .description("Submit your usage data to Tokscale")
322
+ .option("--opencode", "Include only OpenCode data")
323
+ .option("--claude", "Include only Claude Code data")
324
+ .option("--codex", "Include only Codex CLI data")
325
+ .option("--gemini", "Include only Gemini CLI data")
326
+ .option("--cursor", "Include only Cursor IDE data")
327
+ .option("--since <date>", "Start date (YYYY-MM-DD)")
328
+ .option("--until <date>", "End date (YYYY-MM-DD)")
329
+ .option("--year <year>", "Filter to specific year")
330
+ .option("--dry-run", "Show what would be submitted without actually submitting")
331
+ .action(async (options) => {
332
+ await submit({
333
+ opencode: options.opencode,
334
+ claude: options.claude,
335
+ codex: options.codex,
336
+ gemini: options.gemini,
337
+ cursor: options.cursor,
338
+ since: options.since,
339
+ until: options.until,
340
+ year: options.year,
341
+ dryRun: options.dryRun,
342
+ });
343
+ });
344
+
345
+ // =========================================================================
346
+ // Interactive TUI Command
347
+ // =========================================================================
348
+
349
+ program
350
+ .command("tui")
351
+ .description("Launch interactive terminal UI")
352
+ .option("--opencode", "Show only OpenCode usage")
353
+ .option("--claude", "Show only Claude Code usage")
354
+ .option("--codex", "Show only Codex CLI usage")
355
+ .option("--gemini", "Show only Gemini CLI usage")
356
+ .option("--cursor", "Show only Cursor IDE usage")
357
+ .option("--today", "Show only today's usage")
358
+ .option("--week", "Show last 7 days")
359
+ .option("--month", "Show current month")
360
+ .option("--since <date>", "Start date (YYYY-MM-DD)")
361
+ .option("--until <date>", "End date (YYYY-MM-DD)")
362
+ .option("--year <year>", "Filter to specific year")
363
+ .action(async (options) => {
364
+ const launchTUI = await tryLoadTUI();
365
+ if (launchTUI) {
366
+ await launchTUI(buildTUIOptions(options));
367
+ } else {
368
+ showTUIUnavailableMessage();
369
+ process.exit(1);
370
+ }
371
+ });
372
+
373
+ // =========================================================================
374
+ // Cursor IDE Authentication Commands
375
+ // =========================================================================
376
+
377
+ const cursorCommand = program
378
+ .command("cursor")
379
+ .description("Cursor IDE integration commands");
380
+
381
+ cursorCommand
382
+ .command("login")
383
+ .description("Login to Cursor (paste your session token)")
384
+ .action(async () => {
385
+ await cursorLogin();
386
+ });
387
+
388
+ cursorCommand
389
+ .command("logout")
390
+ .description("Logout from Cursor")
391
+ .action(async () => {
392
+ await cursorLogout();
393
+ });
394
+
395
+ cursorCommand
396
+ .command("status")
397
+ .description("Check Cursor authentication status")
398
+ .action(async () => {
399
+ await cursorStatus();
400
+ });
401
+
402
+ // Check if a subcommand was provided
403
+ const args = process.argv.slice(2);
404
+ const firstArg = args[0] || '';
405
+ // Global flags should go to main program
406
+ const isGlobalFlag = ['--help', '-h', '--version', '-V'].includes(firstArg);
407
+ const hasSubcommand = args.length > 0 && !firstArg.startsWith('-');
408
+ const knownCommands = ['monthly', 'models', 'graph', 'login', 'logout', 'whoami', 'submit', 'cursor', 'tui', 'help'];
409
+ const isKnownCommand = hasSubcommand && knownCommands.includes(firstArg);
410
+
411
+ if (isKnownCommand || isGlobalFlag) {
412
+ // Run the specified subcommand or show full help/version
413
+ await program.parseAsync();
414
+ } else {
415
+ // No subcommand - launch TUI by default, or legacy CLI with --light, or JSON with --json
416
+ const defaultProgram = new Command();
417
+ defaultProgram
418
+ .option("--light", "Use legacy CLI table output instead of TUI")
419
+ .option("--json", "Output as JSON (for scripting)")
420
+ .option("--opencode", "Show only OpenCode usage")
421
+ .option("--claude", "Show only Claude Code usage")
422
+ .option("--codex", "Show only Codex CLI usage")
423
+ .option("--gemini", "Show only Gemini CLI usage")
424
+ .option("--cursor", "Show only Cursor IDE usage")
425
+ .option("--today", "Show only today's usage")
426
+ .option("--week", "Show last 7 days")
427
+ .option("--month", "Show current month")
428
+ .option("--since <date>", "Start date (YYYY-MM-DD)")
429
+ .option("--until <date>", "End date (YYYY-MM-DD)")
430
+ .option("--year <year>", "Filter to specific year")
431
+ .option("--benchmark", "Show processing time")
432
+ .parse();
433
+
434
+ const opts = defaultProgram.opts();
435
+ if (opts.json) {
436
+ await outputJsonReport("models", opts);
437
+ } else if (opts.light) {
438
+ await showModelReport(opts);
439
+ } else {
440
+ const launchTUI = await tryLoadTUI();
441
+ if (launchTUI) {
442
+ await launchTUI(buildTUIOptions(opts));
443
+ } else {
444
+ showTUIUnavailableMessage();
445
+ await showModelReport(opts);
446
+ }
447
+ }
448
+ }
449
+ }
450
+
451
+ function getEnabledSources(options: FilterOptions): SourceType[] | undefined {
452
+ const hasFilter = options.opencode || options.claude || options.codex || options.gemini || options.cursor;
453
+ if (!hasFilter) return undefined; // All sources
454
+
455
+ const sources: SourceType[] = [];
456
+ if (options.opencode) sources.push("opencode");
457
+ if (options.claude) sources.push("claude");
458
+ if (options.codex) sources.push("codex");
459
+ if (options.gemini) sources.push("gemini");
460
+ if (options.cursor) sources.push("cursor");
461
+ return sources;
462
+ }
463
+
464
+ function logNativeStatus(): void {
465
+ if (!isNativeAvailable()) {
466
+ console.log(pc.yellow(" Note: Using TypeScript fallback (native module not available)"));
467
+ console.log(pc.gray(" Run 'bun run build:core' for ~10x faster processing.\n"));
468
+ }
469
+ }
470
+
471
+ async function fetchPricingData(): Promise<PricingFetcher> {
472
+ const fetcher = new PricingFetcher();
473
+ await fetcher.fetchPricing();
474
+ return fetcher;
475
+ }
476
+
477
+ /**
478
+ * Sync Cursor usage data from API to local cache.
479
+ * Only attempts sync if user is authenticated with Cursor.
480
+ */
481
+ async function syncCursorData(): Promise<CursorSyncResult> {
482
+ const credentials = loadCursorCredentials();
483
+ if (!credentials) {
484
+ return { attempted: false, synced: false, rows: 0 };
485
+ }
486
+
487
+ const result = await syncCursorCache();
488
+ return {
489
+ attempted: true,
490
+ synced: result.synced,
491
+ rows: result.rows,
492
+ error: result.error,
493
+ };
494
+ }
495
+
496
+ interface LoadedDataSources {
497
+ fetcher: PricingFetcher;
498
+ cursorSync: CursorSyncResult;
499
+ localMessages: ParsedMessages | null;
500
+ }
501
+
502
+ /**
503
+ * Load all data sources in parallel (two-phase optimization):
504
+ * - Cursor API sync (network)
505
+ * - Pricing fetch (network)
506
+ * - Local file parsing (CPU/IO) - OpenCode, Claude, Codex, Gemini
507
+ *
508
+ * This overlaps network I/O with local file parsing for better performance.
509
+ */
510
+ async function loadDataSourcesParallel(
511
+ localSources: SourceType[],
512
+ dateFilters: { since?: string; until?: string; year?: string }
513
+ ): Promise<LoadedDataSources> {
514
+ // Skip local parsing if no local sources requested (e.g., cursor-only mode)
515
+ const shouldParseLocal = localSources.length > 0;
516
+
517
+ // Use Promise.allSettled for graceful degradation
518
+ const [cursorResult, pricingResult, localResult] = await Promise.allSettled([
519
+ syncCursorData(),
520
+ fetchPricingData(),
521
+ // Parse local sources in parallel (excludes Cursor) - skip if empty
522
+ shouldParseLocal
523
+ ? parseLocalSourcesAsync({
524
+ sources: localSources.filter(s => s !== 'cursor'),
525
+ since: dateFilters.since,
526
+ until: dateFilters.until,
527
+ year: dateFilters.year,
528
+ })
529
+ : Promise.resolve(null),
530
+ ]);
531
+
532
+ // Handle partial failures gracefully
533
+ const cursorSync: CursorSyncResult = cursorResult.status === 'fulfilled'
534
+ ? cursorResult.value
535
+ : { attempted: true, synced: false, rows: 0, error: 'Cursor sync failed' };
536
+
537
+ const fetcher: PricingFetcher = pricingResult.status === 'fulfilled'
538
+ ? pricingResult.value
539
+ : new PricingFetcher(); // Empty pricing → costs = 0
540
+
541
+ const localMessages: ParsedMessages | null = localResult.status === 'fulfilled'
542
+ ? localResult.value
543
+ : null;
544
+
545
+ return { fetcher, cursorSync, localMessages };
546
+ }
547
+
548
+ async function showModelReport(options: FilterOptions & DateFilterOptions & { benchmark?: boolean }) {
549
+ logNativeStatus();
550
+
551
+ const dateFilters = getDateFilters(options);
552
+ const enabledSources = getEnabledSources(options);
553
+ const onlyCursor = enabledSources?.length === 1 && enabledSources[0] === 'cursor';
554
+ const includeCursor = !enabledSources || enabledSources.includes('cursor');
555
+
556
+ // Check cursor auth early if cursor-only mode
557
+ if (onlyCursor) {
558
+ const credentials = loadCursorCredentials();
559
+ if (!credentials) {
560
+ console.log(pc.red("\n Error: Cursor authentication required."));
561
+ console.log(pc.gray(" Run 'tokscale cursor login' to authenticate with Cursor.\n"));
562
+ process.exit(1);
563
+ }
564
+ }
565
+
566
+ const dateRange = getDateRangeLabel(options);
567
+ const title = dateRange
568
+ ? `Token Usage Report by Model (${dateRange})`
569
+ : "Token Usage Report by Model";
570
+
571
+ console.log(pc.cyan(`\n ${title}`));
572
+ if (options.benchmark) {
573
+ console.log(pc.gray(` Using: Rust native module v${getNativeVersion()}`));
574
+ }
575
+ console.log();
576
+
577
+ // Start spinner for loading phase
578
+ const spinner = createSpinner({ color: "cyan" });
579
+ spinner.start(pc.gray("Loading data sources..."));
580
+
581
+ // Filter out cursor for local parsing (it's synced separately via network)
582
+ const localSources: SourceType[] = (enabledSources || ['opencode', 'claude', 'codex', 'gemini', 'cursor'])
583
+ .filter(s => s !== 'cursor');
584
+
585
+ // Two-phase parallel loading: network (Cursor + pricing) overlaps with local file parsing
586
+ // If cursor-only, skip local parsing entirely
587
+ const { fetcher, cursorSync, localMessages } = await loadDataSourcesParallel(
588
+ onlyCursor ? [] : localSources,
589
+ dateFilters
590
+ );
591
+
592
+ if (!localMessages && !onlyCursor) {
593
+ spinner.error('Failed to parse local session files');
594
+ process.exit(1);
595
+ }
596
+
597
+ spinner.update(pc.gray("Finalizing report..."));
598
+ const startTime = performance.now();
599
+
600
+ let report: ModelReport;
601
+ try {
602
+ const emptyMessages: ParsedMessages = { messages: [], opencodeCount: 0, claudeCount: 0, codexCount: 0, geminiCount: 0, processingTimeMs: 0 };
603
+ report = await finalizeReportAsync({
604
+ localMessages: localMessages || emptyMessages,
605
+ pricing: fetcher.toPricingEntries(),
606
+ includeCursor: includeCursor && cursorSync.synced,
607
+ since: dateFilters.since,
608
+ until: dateFilters.until,
609
+ year: dateFilters.year,
610
+ });
611
+ } catch (e) {
612
+ spinner.error(`Error: ${(e as Error).message}`);
613
+ process.exit(1);
614
+ }
615
+
616
+ const processingTime = performance.now() - startTime;
617
+ spinner.stop();
618
+
619
+ if (report.entries.length === 0) {
620
+ if (onlyCursor && !cursorSync.synced) {
621
+ console.log(pc.yellow(" No Cursor data available."));
622
+ console.log(pc.gray(" Run 'tokscale cursor login' to authenticate with Cursor.\n"));
623
+ } else {
624
+ console.log(pc.yellow(" No usage data found.\n"));
625
+ }
626
+ return;
627
+ }
628
+
629
+ // Create table
630
+ const table = createUsageTable("Source/Model");
631
+
632
+ for (const entry of report.entries) {
633
+ const sourceLabel = getSourceLabel(entry.source);
634
+ const modelDisplay = `${pc.dim(sourceLabel)} ${formatModelName(entry.model)}`;
635
+ table.push(
636
+ formatUsageRow(
637
+ modelDisplay,
638
+ [entry.model],
639
+ entry.input,
640
+ entry.output,
641
+ entry.cacheWrite,
642
+ entry.cacheRead,
643
+ entry.cost
644
+ )
645
+ );
646
+ }
647
+
648
+ // Add totals row
649
+ table.push(
650
+ formatTotalsRow(
651
+ report.totalInput,
652
+ report.totalOutput,
653
+ report.totalCacheWrite,
654
+ report.totalCacheRead,
655
+ report.totalCost
656
+ )
657
+ );
658
+
659
+ console.log(table.toString());
660
+
661
+ // Summary stats
662
+ console.log(
663
+ pc.gray(
664
+ `\n Total: ${formatNumber(report.totalMessages)} messages, ` +
665
+ `${formatNumber(report.totalInput + report.totalOutput + report.totalCacheRead + report.totalCacheWrite)} tokens, ` +
666
+ `${pc.green(formatCurrency(report.totalCost))}`
667
+ )
668
+ );
669
+
670
+ if (options.benchmark) {
671
+ console.log(pc.gray(` Processing time: ${processingTime.toFixed(0)}ms (Rust) + ${report.processingTimeMs}ms (parsing)`));
672
+ if (cursorSync.attempted) {
673
+ if (cursorSync.synced) {
674
+ console.log(pc.gray(` Cursor: ${cursorSync.rows} usage events synced (full lifetime data)`));
675
+ } else {
676
+ console.log(pc.yellow(` Cursor: sync failed - ${cursorSync.error}`));
677
+ }
678
+ }
679
+ }
680
+
681
+ console.log();
682
+ }
683
+
684
+ async function showMonthlyReport(options: FilterOptions & DateFilterOptions & { benchmark?: boolean }) {
685
+ logNativeStatus();
686
+
687
+ const dateRange = getDateRangeLabel(options);
688
+ const title = dateRange
689
+ ? `Monthly Token Usage Report (${dateRange})`
690
+ : "Monthly Token Usage Report";
691
+
692
+ console.log(pc.cyan(`\n ${title}`));
693
+ if (options.benchmark) {
694
+ console.log(pc.gray(` Using: Rust native module v${getNativeVersion()}`));
695
+ }
696
+ console.log();
697
+
698
+ // Start spinner for loading phase
699
+ const spinner = createSpinner({ color: "cyan" });
700
+ spinner.start(pc.gray("Loading data sources..."));
701
+
702
+ const dateFilters = getDateFilters(options);
703
+ const enabledSources = getEnabledSources(options);
704
+ // Filter out cursor for local parsing (it's synced separately via network)
705
+ const localSources: SourceType[] = (enabledSources || ['opencode', 'claude', 'codex', 'gemini', 'cursor'])
706
+ .filter(s => s !== 'cursor');
707
+ const includeCursor = !enabledSources || enabledSources.includes('cursor');
708
+
709
+ // Two-phase parallel loading: network (Cursor + pricing) overlaps with local file parsing
710
+ const { fetcher, cursorSync, localMessages } = await loadDataSourcesParallel(localSources, dateFilters);
711
+
712
+ if (!localMessages) {
713
+ spinner.error('Failed to parse local session files');
714
+ process.exit(1);
715
+ }
716
+
717
+ spinner.update(pc.gray("Finalizing report..."));
718
+ const startTime = performance.now();
719
+
720
+ let report: MonthlyReport;
721
+ try {
722
+ report = await finalizeMonthlyReportAsync({
723
+ localMessages,
724
+ pricing: fetcher.toPricingEntries(),
725
+ includeCursor: includeCursor && cursorSync.synced,
726
+ since: dateFilters.since,
727
+ until: dateFilters.until,
728
+ year: dateFilters.year,
729
+ });
730
+ } catch (e) {
731
+ spinner.error(`Error: ${(e as Error).message}`);
732
+ process.exit(1);
733
+ }
734
+
735
+ const processingTime = performance.now() - startTime;
736
+ spinner.stop();
737
+
738
+ if (report.entries.length === 0) {
739
+ console.log(pc.yellow(" No usage data found.\n"));
740
+ return;
741
+ }
742
+
743
+ // Create table
744
+ const table = createUsageTable("Month");
745
+
746
+ for (const entry of report.entries) {
747
+ table.push(
748
+ formatUsageRow(
749
+ entry.month,
750
+ entry.models,
751
+ entry.input,
752
+ entry.output,
753
+ entry.cacheWrite,
754
+ entry.cacheRead,
755
+ entry.cost
756
+ )
757
+ );
758
+ }
759
+
760
+ // Add totals row
761
+ const totalInput = report.entries.reduce((sum, e) => sum + e.input, 0);
762
+ const totalOutput = report.entries.reduce((sum, e) => sum + e.output, 0);
763
+ const totalCacheRead = report.entries.reduce((sum, e) => sum + e.cacheRead, 0);
764
+ const totalCacheWrite = report.entries.reduce((sum, e) => sum + e.cacheWrite, 0);
765
+
766
+ table.push(
767
+ formatTotalsRow(totalInput, totalOutput, totalCacheWrite, totalCacheRead, report.totalCost)
768
+ );
769
+
770
+ console.log(table.toString());
771
+ console.log(pc.gray(`\n Total Cost: ${pc.green(formatCurrency(report.totalCost))}`));
772
+
773
+ if (options.benchmark) {
774
+ console.log(pc.gray(` Processing time: ${processingTime.toFixed(0)}ms (Rust) + ${report.processingTimeMs}ms (parsing)`));
775
+ if (cursorSync.attempted) {
776
+ if (cursorSync.synced) {
777
+ console.log(pc.gray(` Cursor: ${cursorSync.rows} usage events synced (full lifetime data)`));
778
+ } else {
779
+ console.log(pc.yellow(` Cursor: sync failed - ${cursorSync.error}`));
780
+ }
781
+ }
782
+ }
783
+
784
+ console.log();
785
+ }
786
+
787
+ type JsonReportType = "models" | "monthly";
788
+
789
+ async function outputJsonReport(
790
+ reportType: JsonReportType,
791
+ options: FilterOptions & DateFilterOptions
792
+ ) {
793
+ logNativeStatus();
794
+
795
+ const dateFilters = getDateFilters(options);
796
+ const enabledSources = getEnabledSources(options);
797
+ const onlyCursor = enabledSources?.length === 1 && enabledSources[0] === 'cursor';
798
+ const includeCursor = !enabledSources || enabledSources.includes('cursor');
799
+ const localSources: SourceType[] = (enabledSources || ['opencode', 'claude', 'codex', 'gemini', 'cursor'])
800
+ .filter(s => s !== 'cursor');
801
+
802
+ const { fetcher, cursorSync, localMessages } = await loadDataSourcesParallel(
803
+ onlyCursor ? [] : localSources,
804
+ dateFilters
805
+ );
806
+
807
+ if (!localMessages && !onlyCursor) {
808
+ console.error(JSON.stringify({ error: "Failed to parse local session files" }));
809
+ process.exit(1);
810
+ }
811
+
812
+ const emptyMessages: ParsedMessages = { messages: [], opencodeCount: 0, claudeCount: 0, codexCount: 0, geminiCount: 0, processingTimeMs: 0 };
813
+
814
+ if (reportType === "models") {
815
+ const report = await finalizeReportAsync({
816
+ localMessages: localMessages || emptyMessages,
817
+ pricing: fetcher.toPricingEntries(),
818
+ includeCursor: includeCursor && cursorSync.synced,
819
+ since: dateFilters.since,
820
+ until: dateFilters.until,
821
+ year: dateFilters.year,
822
+ });
823
+ console.log(JSON.stringify(report, null, 2));
824
+ } else {
825
+ const report = await finalizeMonthlyReportAsync({
826
+ localMessages: localMessages || emptyMessages,
827
+ pricing: fetcher.toPricingEntries(),
828
+ includeCursor: includeCursor && cursorSync.synced,
829
+ since: dateFilters.since,
830
+ until: dateFilters.until,
831
+ year: dateFilters.year,
832
+ });
833
+ console.log(JSON.stringify(report, null, 2));
834
+ }
835
+ }
836
+
837
+ interface GraphCommandOptions extends FilterOptions, DateFilterOptions {
838
+ output?: string;
839
+ benchmark?: boolean;
840
+ }
841
+
842
+ async function handleGraphCommand(options: GraphCommandOptions) {
843
+ logNativeStatus();
844
+
845
+ // Start spinner for loading phase (only if outputting to file, not stdout)
846
+ const spinner = options.output ? createSpinner({ color: "cyan" }) : null;
847
+ spinner?.start(pc.gray("Loading data sources..."));
848
+
849
+ const dateFilters = getDateFilters(options);
850
+ const enabledSources = getEnabledSources(options);
851
+ // Filter out cursor for local parsing (it's synced separately via network)
852
+ const localSources: SourceType[] = (enabledSources || ['opencode', 'claude', 'codex', 'gemini', 'cursor'])
853
+ .filter(s => s !== 'cursor');
854
+ const includeCursor = !enabledSources || enabledSources.includes('cursor');
855
+
856
+ // Two-phase parallel loading: network (Cursor + pricing) overlaps with local file parsing
857
+ const { fetcher, cursorSync, localMessages } = await loadDataSourcesParallel(localSources, dateFilters);
858
+
859
+ if (!localMessages) {
860
+ spinner?.error('Failed to parse local session files');
861
+ process.exit(1);
862
+ }
863
+
864
+ spinner?.update(pc.gray("Generating graph data..."));
865
+ const startTime = performance.now();
866
+
867
+ const data = await finalizeGraphAsync({
868
+ localMessages,
869
+ pricing: fetcher.toPricingEntries(),
870
+ includeCursor: includeCursor && cursorSync.synced,
871
+ since: dateFilters.since,
872
+ until: dateFilters.until,
873
+ year: dateFilters.year,
874
+ });
875
+
876
+ const processingTime = performance.now() - startTime;
877
+ spinner?.stop();
878
+
879
+ const jsonOutput = JSON.stringify(data, null, 2);
880
+
881
+ // Output to file or stdout
882
+ if (options.output) {
883
+ fs.writeFileSync(options.output, jsonOutput, "utf-8");
884
+ console.error(pc.green(`✓ Graph data written to ${options.output}`));
885
+ console.error(
886
+ pc.gray(
887
+ ` ${data.contributions.length} days, ${data.summary.sources.length} sources, ${data.summary.models.length} models`
888
+ )
889
+ );
890
+ console.error(pc.gray(` Total: ${formatCurrency(data.summary.totalCost)}`));
891
+ if (options.benchmark) {
892
+ console.error(pc.gray(` Processing time: ${processingTime.toFixed(0)}ms (Rust native)`));
893
+ if (cursorSync.attempted) {
894
+ if (cursorSync.synced) {
895
+ console.error(pc.gray(` Cursor: ${cursorSync.rows} usage events synced (full lifetime data)`));
896
+ } else {
897
+ console.error(pc.yellow(` Cursor: sync failed - ${cursorSync.error}`));
898
+ }
899
+ }
900
+ }
901
+ } else {
902
+ console.log(jsonOutput);
903
+ }
904
+ }
905
+
906
+ function getSourceLabel(source: string): string {
907
+ switch (source) {
908
+ case "opencode":
909
+ return "OpenCode";
910
+ case "claude":
911
+ return "Claude";
912
+ case "codex":
913
+ return "Codex";
914
+ case "gemini":
915
+ return "Gemini";
916
+ case "cursor":
917
+ return "Cursor";
918
+ default:
919
+ return source;
920
+ }
921
+ }
922
+
923
+ // =============================================================================
924
+ // Cursor IDE Authentication
925
+ // =============================================================================
926
+
927
+ async function cursorLogin(): Promise<void> {
928
+ const credentials = loadCursorCredentials();
929
+ if (credentials) {
930
+ console.log(pc.yellow("\n Already logged in to Cursor."));
931
+ console.log(pc.gray(" Run 'tokscale cursor logout' to sign out first.\n"));
932
+ return;
933
+ }
934
+
935
+ console.log(pc.cyan("\n Cursor IDE - Login\n"));
936
+ console.log(pc.white(" To get your session token:"));
937
+ console.log(pc.gray(" 1. Open https://www.cursor.com/settings in your browser"));
938
+ console.log(pc.gray(" 2. Open Developer Tools (F12) > Network tab"));
939
+ console.log(pc.gray(" 3. Find any request to cursor.com/api"));
940
+ console.log(pc.gray(" 4. Copy the 'WorkosCursorSessionToken' cookie value"));
941
+ console.log();
942
+
943
+ // Read token from stdin
944
+ const readline = await import("node:readline");
945
+ const rl = readline.createInterface({
946
+ input: process.stdin,
947
+ output: process.stdout,
948
+ });
949
+
950
+ const token = await new Promise<string>((resolve) => {
951
+ rl.question(pc.white(" Paste your session token: "), (answer) => {
952
+ rl.close();
953
+ resolve(answer.trim());
954
+ });
955
+ });
956
+
957
+ if (!token) {
958
+ console.log(pc.red("\n No token provided. Login cancelled.\n"));
959
+ return;
960
+ }
961
+
962
+ // Validate the token
963
+ console.log(pc.gray("\n Validating token..."));
964
+ const validation = await validateCursorSession(token);
965
+
966
+ if (!validation.valid) {
967
+ console.log(pc.red(`\n Invalid token: ${validation.error}`));
968
+ console.log(pc.gray(" Please try again with a valid session token.\n"));
969
+ return;
970
+ }
971
+
972
+ // Save credentials
973
+ saveCursorCredentials({
974
+ sessionToken: token,
975
+ createdAt: new Date().toISOString(),
976
+ });
977
+
978
+ console.log(pc.green("\n Success! Logged in to Cursor."));
979
+ if (validation.membershipType) {
980
+ console.log(pc.gray(` Membership: ${validation.membershipType}`));
981
+ }
982
+ console.log(pc.gray(" Your usage data will now be included in reports.\n"));
983
+ }
984
+
985
+ async function cursorLogout(): Promise<void> {
986
+ const credentials = loadCursorCredentials();
987
+
988
+ if (!credentials) {
989
+ console.log(pc.yellow("\n Not logged in to Cursor.\n"));
990
+ return;
991
+ }
992
+
993
+ const cleared = clearCursorCredentials();
994
+
995
+ if (cleared) {
996
+ console.log(pc.green("\n Logged out from Cursor.\n"));
997
+ } else {
998
+ console.error(pc.red("\n Failed to clear Cursor credentials.\n"));
999
+ process.exit(1);
1000
+ }
1001
+ }
1002
+
1003
+ async function cursorStatus(): Promise<void> {
1004
+ const credentials = loadCursorCredentials();
1005
+
1006
+ if (!credentials) {
1007
+ console.log(pc.yellow("\n Not logged in to Cursor."));
1008
+ console.log(pc.gray(" Run 'tokscale cursor login' to authenticate.\n"));
1009
+ return;
1010
+ }
1011
+
1012
+ console.log(pc.cyan("\n Cursor IDE - Status\n"));
1013
+ console.log(pc.gray(" Checking session validity..."));
1014
+
1015
+ const validation = await validateCursorSession(credentials.sessionToken);
1016
+
1017
+ if (validation.valid) {
1018
+ console.log(pc.green(" ✓ Session is valid"));
1019
+ if (validation.membershipType) {
1020
+ console.log(pc.white(` Membership: ${validation.membershipType}`));
1021
+ }
1022
+ console.log(pc.gray(` Logged in: ${new Date(credentials.createdAt).toLocaleDateString()}`));
1023
+
1024
+ // Try to fetch usage to show summary
1025
+ try {
1026
+ const usage = await readCursorUsage();
1027
+ const totalCost = usage.byModel.reduce((sum, m) => sum + m.cost, 0);
1028
+ console.log(pc.gray(` Models used: ${usage.byModel.length}`));
1029
+ console.log(pc.gray(` Total usage events: ${usage.rows.length}`));
1030
+ console.log(pc.gray(` Total cost: $${totalCost.toFixed(2)}`));
1031
+ } catch (e) {
1032
+ // Ignore fetch errors for status check
1033
+ }
1034
+ } else {
1035
+ console.log(pc.red(` ✗ Session invalid: ${validation.error}`));
1036
+ console.log(pc.gray(" Run 'tokscale cursor login' to re-authenticate."));
1037
+ }
1038
+
1039
+ console.log(pc.gray(`\n Credentials: ${getCursorCredentialsPath()}\n`));
1040
+ }
1041
+
1042
+ main().catch(console.error);