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