@tokscale/cli 1.4.3 → 2.0.1

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