tokenusage-cli 0.1.0 → 0.2.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 (131) hide show
  1. package/CHANGELOG.md +46 -19
  2. package/LICENSE +22 -22
  3. package/README.md +123 -94
  4. package/THIRD_PARTY_NOTICES.md +140 -140
  5. package/bin/tokenusage.js +69 -69
  6. package/package.json +59 -59
  7. package/src/cli.js +146 -134
  8. package/src/commands/device-login.js +205 -205
  9. package/src/commands/diagnostics.js +38 -38
  10. package/src/commands/doctor.js +110 -110
  11. package/src/commands/init.js +2484 -2436
  12. package/src/commands/pause.js +77 -0
  13. package/src/commands/sessions.js +29 -29
  14. package/src/commands/status.js +1758 -1747
  15. package/src/commands/sync.js +8048 -7934
  16. package/src/commands/uninstall.js +322 -312
  17. package/src/lib/account-usage-dedup.js +267 -267
  18. package/src/lib/antigravity-paths.js +48 -48
  19. package/src/lib/ark-agent-plan-limits.js +438 -438
  20. package/src/lib/ark-coding-plan-limits.js +537 -537
  21. package/src/lib/async-queue-reader.js +138 -138
  22. package/src/lib/atomic-json.js +27 -27
  23. package/src/lib/bearer-token.js +11 -11
  24. package/src/lib/categorizer-utils.js +232 -232
  25. package/src/lib/claude-categorizer.js +1343 -1343
  26. package/src/lib/claude-config.js +279 -279
  27. package/src/lib/claude-user-identity.js +56 -56
  28. package/src/lib/cli-ui.js +179 -179
  29. package/src/lib/cloud-account.js +541 -541
  30. package/src/lib/cloud-device-token.js +141 -141
  31. package/src/lib/cloud-sync-prefs.js +14 -14
  32. package/src/lib/cloud-usage-reset.js +115 -115
  33. package/src/lib/codex-config.js +595 -595
  34. package/src/lib/codex-context-breakdown.js +806 -806
  35. package/src/lib/codex-model-attribution.js +128 -128
  36. package/src/lib/codex-rollout-parser.js +1471 -1471
  37. package/src/lib/codex-service-tier.js +49 -49
  38. package/src/lib/codex-token-refresh.js +140 -140
  39. package/src/lib/codex-token-usage.js +195 -195
  40. package/src/lib/codex-usage-record.js +195 -195
  41. package/src/lib/collection-pause.js +77 -0
  42. package/src/lib/command-runner.js +313 -313
  43. package/src/lib/commandcode-limits.js +317 -317
  44. package/src/lib/context-health.js +124 -124
  45. package/src/lib/cursor-config.js +605 -605
  46. package/src/lib/cursor-store.js +1918 -1918
  47. package/src/lib/debug-flags.js +7 -7
  48. package/src/lib/devin-limits.js +249 -249
  49. package/src/lib/devin-usage.js +212 -212
  50. package/src/lib/diagnostics.js +383 -383
  51. package/src/lib/doctor.js +385 -385
  52. package/src/lib/dumate.js +95 -95
  53. package/src/lib/fs.js +455 -455
  54. package/src/lib/function-url.js +14 -14
  55. package/src/lib/gemini-config.js +291 -291
  56. package/src/lib/git-outcomes.js +243 -243
  57. package/src/lib/grok-context-breakdown.js +890 -890
  58. package/src/lib/grok-hook.js +360 -360
  59. package/src/lib/grok-limits.js +865 -865
  60. package/src/lib/grok-usage.js +98 -98
  61. package/src/lib/heatmap-compact.js +114 -114
  62. package/src/lib/ingest-sanitize.js +41 -41
  63. package/src/lib/init-flow.js +42 -42
  64. package/src/lib/install-resolver.js +170 -170
  65. package/src/lib/jsonl-lines.js +134 -134
  66. package/src/lib/kimi-model-repair.js +173 -173
  67. package/src/lib/kimi-profile.js +61 -61
  68. package/src/lib/kimi-session.js +216 -216
  69. package/src/lib/local-api.js +3588 -3588
  70. package/src/lib/machine-id.js +238 -238
  71. package/src/lib/multi-install-parser.js +113 -113
  72. package/src/lib/notify-command.js +38 -38
  73. package/src/lib/omp-hook.js +589 -589
  74. package/src/lib/openclaw-cli.js +104 -104
  75. package/src/lib/openclaw-hook.js +375 -375
  76. package/src/lib/openclaw-session-plugin.js +560 -560
  77. package/src/lib/opencode-config.js +121 -121
  78. package/src/lib/opencode-go-limits.js +807 -807
  79. package/src/lib/outcomes-engine.js +253 -253
  80. package/src/lib/passive-mode.js +219 -219
  81. package/src/lib/pet-packages.js +722 -722
  82. package/src/lib/pricing/curated-overrides.json +822 -822
  83. package/src/lib/pricing/index.js +379 -379
  84. package/src/lib/pricing/litellm-fetcher.js +172 -172
  85. package/src/lib/pricing/matcher.js +456 -456
  86. package/src/lib/pricing/seed-snapshot.json +1 -1
  87. package/src/lib/progress.js +76 -76
  88. package/src/lib/project-usage-purge.js +117 -117
  89. package/src/lib/prompt.js +24 -24
  90. package/src/lib/provider-status.js +104 -104
  91. package/src/lib/proxy-env.js +489 -489
  92. package/src/lib/proxy-settings.js +163 -163
  93. package/src/lib/qoder-cn-cli-limits.js +119 -119
  94. package/src/lib/qoder-limits.js +880 -880
  95. package/src/lib/quiet-warnings.js +26 -26
  96. package/src/lib/rollout.js +26005 -25966
  97. package/src/lib/runtime-config.js +9 -4
  98. package/src/lib/scan-roots.js +277 -277
  99. package/src/lib/scheduled-task.js +145 -0
  100. package/src/lib/sentry.js +231 -231
  101. package/src/lib/session-analytics.js +2972 -2972
  102. package/src/lib/session-performance.js +237 -237
  103. package/src/lib/session-upload.js +379 -379
  104. package/src/lib/skill-usage.js +267 -267
  105. package/src/lib/skills-manager.js +1591 -1591
  106. package/src/lib/source-metadata.js +48 -48
  107. package/src/lib/sqlite-reader.js +215 -215
  108. package/src/lib/star-cta.js +73 -73
  109. package/src/lib/subscription-manager.js +293 -293
  110. package/src/lib/subscriptions.js +508 -508
  111. package/src/lib/sync-report.js +138 -0
  112. package/src/lib/telemetry.js +193 -193
  113. package/src/lib/tracker-paths.js +16 -16
  114. package/src/lib/trae-cn-config.js +548 -548
  115. package/src/lib/trae-db.js +127 -127
  116. package/src/lib/trae-snapshot.js +230 -230
  117. package/src/lib/trae-sqlite.js +143 -143
  118. package/src/lib/trae-usage.js +121 -121
  119. package/src/lib/upload-queue.js +134 -134
  120. package/src/lib/upload-throttle.js +171 -171
  121. package/src/lib/usage-limits.js +4552 -4552
  122. package/src/lib/wrapped-aggregator.js +236 -236
  123. package/src/lib/wsl-probe.js +281 -281
  124. package/src/lib/zcode-limits.js +1172 -1172
  125. package/src/lib/zcode-reset-credits.js +66 -66
  126. package/test/audit-fixes.test.js +200 -0
  127. package/test/cli-smoke.test.js +53 -53
  128. package/test/collection-controls.test.js +210 -0
  129. package/test/ingest-sanitize.test.js +162 -162
  130. package/test/quiet-warnings.test.js +53 -53
  131. package/test/session-upload.test.js +427 -427
package/bin/tokenusage.js CHANGED
@@ -1,69 +1,69 @@
1
- #!/usr/bin/env node
2
- /* eslint-disable no-console */
3
-
4
- // Before anything can require node:sqlite: keep its per-require
5
- // ExperimentalWarning out of redirected sync logs.
6
- require('../src/lib/quiet-warnings').suppressSqliteExperimentalWarning();
7
-
8
- const { run } = require('../src/cli');
9
- const { stripDebugFlag } = require('../src/lib/debug-flags');
10
- const {
11
- relaunchWithProxyEnvIfNeeded,
12
- applyUndiciProxyIfNeeded,
13
- readPersistedProxyConfig,
14
- } = require('../src/lib/proxy-env');
15
-
16
- const { argv, debug } = stripDebugFlag(process.argv.slice(2));
17
-
18
- const persistedProxy = readPersistedProxyConfig();
19
- const relaunch = relaunchWithProxyEnvIfNeeded({
20
- argv,
21
- originalArgv: process.argv.slice(1),
22
- proxyConfig: persistedProxy,
23
- });
24
- if (relaunch) {
25
- if (typeof relaunch.status === 'number') process.exit(relaunch.status);
26
- if (relaunch.error) {
27
- console.error(relaunch.error?.stack || String(relaunch.error));
28
- process.exit(1);
29
- }
30
- process.exit(0);
31
- }
32
-
33
- // NODE_USE_ENV_PROXY only works on Node 22.21+/24.5+. For older runtimes
34
- // (including community users on stale Node, and the embedded Node shipped
35
- // with older macOS app builds), set an undici ProxyAgent so fetch() actually
36
- // honors HTTPS_PROXY. Safe to run on modern Node too — explicit dispatcher
37
- // takes precedence over the env-var-driven default.
38
- const applyResult = applyUndiciProxyIfNeeded({ proxyConfig: persistedProxy });
39
- if (applyResult && applyResult.unprotected === true) {
40
- console.error('[proxy] Manual proxy could not be applied and outbound traffic could not be blocked; aborting.');
41
- console.error('[proxy] 手动代理无法生效且无法阻断出站流量,已中止。');
42
- process.exit(1);
43
- }
44
-
45
- run(argv).catch((err) => {
46
- try {
47
- const { captureException } = require('../src/lib/sentry');
48
- captureException(err, { tags: { surface: 'cli-unhandled' } });
49
- } catch {
50
- /* ignore */
51
- }
52
- console.error(err?.stack || String(err));
53
- if (debug) {
54
- if (typeof err?.status === 'number') {
55
- console.error(`Status: ${err.status}`);
56
- }
57
- if (typeof err?.code === 'string' && err.code.trim()) {
58
- console.error(`Code: ${err.code.trim()}`);
59
- }
60
- const original = err?.originalMessage;
61
- if (original && original !== err?.message) {
62
- console.error(`Original error: ${original}`);
63
- }
64
- if (typeof err?.nextActions === 'string' && err.nextActions.trim()) {
65
- console.error(`Next actions: ${err.nextActions.trim()}`);
66
- }
67
- }
68
- process.exitCode = 1;
69
- });
1
+ #!/usr/bin/env node
2
+ /* eslint-disable no-console */
3
+
4
+ // Before anything can require node:sqlite: keep its per-require
5
+ // ExperimentalWarning out of redirected sync logs.
6
+ require('../src/lib/quiet-warnings').suppressSqliteExperimentalWarning();
7
+
8
+ const { run } = require('../src/cli');
9
+ const { stripDebugFlag } = require('../src/lib/debug-flags');
10
+ const {
11
+ relaunchWithProxyEnvIfNeeded,
12
+ applyUndiciProxyIfNeeded,
13
+ readPersistedProxyConfig,
14
+ } = require('../src/lib/proxy-env');
15
+
16
+ const { argv, debug } = stripDebugFlag(process.argv.slice(2));
17
+
18
+ const persistedProxy = readPersistedProxyConfig();
19
+ const relaunch = relaunchWithProxyEnvIfNeeded({
20
+ argv,
21
+ originalArgv: process.argv.slice(1),
22
+ proxyConfig: persistedProxy,
23
+ });
24
+ if (relaunch) {
25
+ if (typeof relaunch.status === 'number') process.exit(relaunch.status);
26
+ if (relaunch.error) {
27
+ console.error(relaunch.error?.stack || String(relaunch.error));
28
+ process.exit(1);
29
+ }
30
+ process.exit(0);
31
+ }
32
+
33
+ // NODE_USE_ENV_PROXY only works on Node 22.21+/24.5+. For older runtimes
34
+ // (including community users on stale Node, and the embedded Node shipped
35
+ // with older macOS app builds), set an undici ProxyAgent so fetch() actually
36
+ // honors HTTPS_PROXY. Safe to run on modern Node too — explicit dispatcher
37
+ // takes precedence over the env-var-driven default.
38
+ const applyResult = applyUndiciProxyIfNeeded({ proxyConfig: persistedProxy });
39
+ if (applyResult && applyResult.unprotected === true) {
40
+ console.error('[proxy] Manual proxy could not be applied and outbound traffic could not be blocked; aborting.');
41
+ console.error('[proxy] 手动代理无法生效且无法阻断出站流量,已中止。');
42
+ process.exit(1);
43
+ }
44
+
45
+ run(argv).catch((err) => {
46
+ try {
47
+ const { captureException } = require('../src/lib/sentry');
48
+ captureException(err, { tags: { surface: 'cli-unhandled' } });
49
+ } catch {
50
+ /* ignore */
51
+ }
52
+ console.error(err?.stack || String(err));
53
+ if (debug) {
54
+ if (typeof err?.status === 'number') {
55
+ console.error(`Status: ${err.status}`);
56
+ }
57
+ if (typeof err?.code === 'string' && err.code.trim()) {
58
+ console.error(`Code: ${err.code.trim()}`);
59
+ }
60
+ const original = err?.originalMessage;
61
+ if (original && original !== err?.message) {
62
+ console.error(`Original error: ${original}`);
63
+ }
64
+ if (typeof err?.nextActions === 'string' && err.nextActions.trim()) {
65
+ console.error(`Next actions: ${err.nextActions.trim()}`);
66
+ }
67
+ }
68
+ process.exitCode = 1;
69
+ });
package/package.json CHANGED
@@ -1,59 +1,59 @@
1
- {
2
- "name": "tokenusage-cli",
3
- "version": "0.1.0",
4
- "description": "Self-hosted AI coding token usage collector for token-usage (forked from TokenTracker, MIT).",
5
- "keywords": [
6
- "token-usage",
7
- "token",
8
- "usage",
9
- "claude",
10
- "codex",
11
- "self-hosted",
12
- "ai"
13
- ],
14
- "homepage": "https://github.com/baiwumm/token-usage/tree/main/packages/cli#readme",
15
- "bugs": "https://github.com/baiwumm/token-usage/issues",
16
- "repository": {
17
- "type": "git",
18
- "url": "git+https://github.com/baiwumm/token-usage.git",
19
- "directory": "packages/cli"
20
- },
21
- "license": "MIT",
22
- "author": "baiwumm",
23
- "main": "src/cli.js",
24
- "bin": {
25
- "tokenusage": "bin/tokenusage.js"
26
- },
27
- "files": [
28
- "bin/",
29
- "src/",
30
- "test/",
31
- "CHANGELOG.md",
32
- "LICENSE",
33
- "THIRD_PARTY_NOTICES.md",
34
- "README.md"
35
- ],
36
- "type": "commonjs",
37
- "engines": {
38
- "node": ">=22.19.0"
39
- },
40
- "scripts": {
41
- "test": "node --test \"test/*.test.js\"",
42
- "prepublishOnly": "npm test"
43
- },
44
- "dependencies": {
45
- "@journeyapps/wa-sqlite": "2.0.7",
46
- "@mongodb-js/zstd": "^2.0.1",
47
- "@sentry/node": "^11.8.0",
48
- "smol-toml": "^1.9.0",
49
- "undici": "8.12.2",
50
- "yauzl": "^3.4.0"
51
- },
52
- "pnpm": {
53
- "onlyBuiltDependencies": [
54
- "@mongodb-js/zstd",
55
- "@journeyapps/wa-sqlite",
56
- "esbuild"
57
- ]
58
- }
59
- }
1
+ {
2
+ "name": "tokenusage-cli",
3
+ "version": "0.2.1",
4
+ "description": "Self-hosted AI coding token usage collector for token-usage (forked from TokenTracker, MIT).",
5
+ "keywords": [
6
+ "token-usage",
7
+ "token",
8
+ "usage",
9
+ "claude",
10
+ "codex",
11
+ "self-hosted",
12
+ "ai"
13
+ ],
14
+ "homepage": "https://github.com/baiwumm/token-usage/tree/main/packages/cli#readme",
15
+ "bugs": "https://github.com/baiwumm/token-usage/issues",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/baiwumm/token-usage.git",
19
+ "directory": "packages/cli"
20
+ },
21
+ "license": "MIT",
22
+ "author": "baiwumm",
23
+ "main": "src/cli.js",
24
+ "bin": {
25
+ "tokenusage": "bin/tokenusage.js"
26
+ },
27
+ "files": [
28
+ "bin/",
29
+ "src/",
30
+ "test/",
31
+ "CHANGELOG.md",
32
+ "LICENSE",
33
+ "THIRD_PARTY_NOTICES.md",
34
+ "README.md"
35
+ ],
36
+ "type": "commonjs",
37
+ "engines": {
38
+ "node": ">=22.19.0"
39
+ },
40
+ "scripts": {
41
+ "test": "node --test \"test/*.test.js\"",
42
+ "prepublishOnly": "npm test"
43
+ },
44
+ "dependencies": {
45
+ "@journeyapps/wa-sqlite": "2.0.7",
46
+ "@mongodb-js/zstd": "^2.0.1",
47
+ "@sentry/node": "^11.8.0",
48
+ "smol-toml": "^1.9.0",
49
+ "undici": "8.12.2",
50
+ "yauzl": "^3.4.0"
51
+ },
52
+ "pnpm": {
53
+ "onlyBuiltDependencies": [
54
+ "@mongodb-js/zstd",
55
+ "@journeyapps/wa-sqlite",
56
+ "esbuild"
57
+ ]
58
+ }
59
+ }
package/src/cli.js CHANGED
@@ -1,134 +1,146 @@
1
- const { cmdInit } = require("./commands/init");
2
- const { cmdSync } = require("./commands/sync");
3
- const { cmdStatus } = require("./commands/status");
4
- const { cmdDiagnostics } = require("./commands/diagnostics");
5
- const { cmdDoctor } = require("./commands/doctor");
6
- const { cmdUninstall } = require("./commands/uninstall");
7
- const { cmdDeviceLogin } = require("./commands/device-login");
8
- const { cmdSessions } = require("./commands/sessions");
9
-
10
- async function run(argv) {
11
- // Best-effort Sentry init (no-op without DSN / when telemetry opted out).
12
- try {
13
- const { initSentry } = require("./lib/sentry");
14
- const { resolveTrackerPaths } = require("./lib/tracker-paths");
15
- const { trackerDir } = await resolveTrackerPaths().catch(() => ({ trackerDir: null }));
16
- await initSentry({ trackerDir });
17
- } catch {
18
- /* never block CLI startup on telemetry */
19
- }
20
-
21
- const [command, ...rest] = argv;
22
-
23
- // No args → short help (the upstream local dashboard was removed in this
24
- // fork; the hosted token-usage site is the dashboard).
25
- if (!command) {
26
- printHelp();
27
- return;
28
- }
29
-
30
- if (command === "-h" || command === "--help") {
31
- printHelp();
32
- return;
33
- }
34
-
35
- if (command === "-v" || command === "--version") {
36
- const pkg = require("../package.json");
37
- console.log(`v${pkg.version}`);
38
- return;
39
- }
40
-
41
- switch (command) {
42
- case "init":
43
- await cmdInit(rest);
44
- return;
45
- case "sync":
46
- if (rest.includes("--watch")) {
47
- await watchSync(rest);
48
- return;
49
- }
50
- await cmdSync(rest);
51
- return;
52
- case "status":
53
- await cmdStatus(rest);
54
- return;
55
- case "diagnostics":
56
- await cmdDiagnostics(rest);
57
- return;
58
- case "doctor":
59
- await cmdDoctor(rest);
60
- return;
61
- case "uninstall":
62
- await cmdUninstall(rest);
63
- return;
64
- case "device-login":
65
- await cmdDeviceLogin(rest);
66
- return;
67
- case "sessions":
68
- await cmdSessions(rest);
69
- return;
70
- default:
71
- throw new Error(`Unknown command: ${command}`);
72
- }
73
- }
74
-
75
- // --watch: keep the process alive and re-run sync on an interval. Each pass
76
- // reuses the session-analytics sidecar cache and the upload watermarks, so a
77
- // pass with nothing new is cheap (a directory signature stat + a no-op).
78
- async function watchSync(rest) {
79
- const args = rest.filter((arg) => arg !== "--watch");
80
- const intervalIndex = args.indexOf("--interval");
81
- let intervalMs = 15 * 60_000;
82
- if (intervalIndex >= 0) {
83
- const value = Number(args[intervalIndex + 1]);
84
- if (Number.isFinite(value) && value >= 60_000) {
85
- intervalMs = value;
86
- args.splice(intervalIndex, 2);
87
- }
88
- }
89
-
90
- process.stdout.write(`tokenusage sync --watch: every ${Math.round(intervalMs / 60_000)} min (Ctrl+C to stop)\n`);
91
- for (;;) {
92
- try {
93
- await cmdSync(args);
94
- } catch (error) {
95
- // A failed pass (offline, backend 5xx) must not kill the watcher; the
96
- // queue and watermarks retain everything for the next pass.
97
- process.stderr.write(`sync pass failed: ${error?.message || error}\n`);
98
- }
99
- await new Promise((resolve) => setTimeout(resolve, intervalMs));
100
- }
101
- }
102
-
103
- function printHelp() {
104
- // Keep this short; npx users want quick guidance.
105
- process.stdout.write(
106
- [
107
- "tokenusage",
108
- "",
109
- "Usage:",
110
- " tokenusage -v, --version Show version info",
111
- " tokenusage [--debug] init [--yes] [--dry-run] [--no-open] [--link-code <code>]",
112
- " tokenusage [--debug] sync [--auto] [--drain] [--no-sessions] [--watch]",
113
- " tokenusage [--debug] status [--probe-keychain] [--probe-keychain-details]",
114
- " tokenusage [--debug] diagnostics [--out diagnostics.json]",
115
- " tokenusage [--debug] doctor [--json] [--out doctor.json] [--base-url <url>]",
116
- " tokenusage [--debug] uninstall [--purge]",
117
- " tokenusage [--debug] device-login [--json] [--base-url <url>]",
118
- " tokenusage sessions [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--format json|csv] [--out file] [--refresh] [--no-git]",
119
- "",
120
- "Notes:",
121
- " - Pairing: device-login prints a code; approve it at the hosted /device page.",
122
- " - sync parses local AI-tool session logs and uploads hourly token deltas",
123
- " plus session metadata (no prompts, message bodies, paths or titles).",
124
- " - --watch keeps running and syncs on an interval (increments only).",
125
- " - --no-sessions skips the session metadata upload (hourly buckets only).",
126
- " - auto sync waits for a device token.",
127
- " - --debug shows original backend errors.",
128
- " - sessions exports metadata-only efficiency analytics; no prompt or response text is retained.",
129
- "",
130
- ].join("\n"),
131
- );
132
- }
133
-
134
- module.exports = { run };
1
+ const { cmdInit } = require("./commands/init");
2
+ const { cmdSync } = require("./commands/sync");
3
+ const { cmdStatus } = require("./commands/status");
4
+ const { cmdDiagnostics } = require("./commands/diagnostics");
5
+ const { cmdDoctor } = require("./commands/doctor");
6
+ const { cmdUninstall } = require("./commands/uninstall");
7
+ const { cmdDeviceLogin } = require("./commands/device-login");
8
+ const { cmdSessions } = require("./commands/sessions");
9
+ const { cmdPause, cmdResume } = require("./commands/pause");
10
+
11
+ async function run(argv) {
12
+ // Best-effort Sentry init (no-op without DSN / when telemetry opted out).
13
+ try {
14
+ const { initSentry } = require("./lib/sentry");
15
+ const { resolveTrackerPaths } = require("./lib/tracker-paths");
16
+ const { trackerDir } = await resolveTrackerPaths().catch(() => ({ trackerDir: null }));
17
+ await initSentry({ trackerDir });
18
+ } catch {
19
+ /* never block CLI startup on telemetry */
20
+ }
21
+
22
+ const [command, ...rest] = argv;
23
+
24
+ // No args → short help (the upstream local dashboard was removed in this
25
+ // fork; the hosted token-usage site is the dashboard).
26
+ if (!command) {
27
+ printHelp();
28
+ return;
29
+ }
30
+
31
+ if (command === "-h" || command === "--help") {
32
+ printHelp();
33
+ return;
34
+ }
35
+
36
+ if (command === "-v" || command === "--version") {
37
+ const pkg = require("../package.json");
38
+ console.log(`v${pkg.version}`);
39
+ return;
40
+ }
41
+
42
+ switch (command) {
43
+ case "init":
44
+ await cmdInit(rest);
45
+ return;
46
+ case "sync":
47
+ if (rest.includes("--watch")) {
48
+ await watchSync(rest);
49
+ return;
50
+ }
51
+ await cmdSync(rest);
52
+ return;
53
+ case "pause":
54
+ await cmdPause(rest);
55
+ return;
56
+ case "resume":
57
+ await cmdResume(rest);
58
+ return;
59
+ case "status":
60
+ await cmdStatus(rest);
61
+ return;
62
+ case "diagnostics":
63
+ await cmdDiagnostics(rest);
64
+ return;
65
+ case "doctor":
66
+ await cmdDoctor(rest);
67
+ return;
68
+ case "uninstall":
69
+ await cmdUninstall(rest);
70
+ return;
71
+ case "device-login":
72
+ await cmdDeviceLogin(rest);
73
+ return;
74
+ case "sessions":
75
+ await cmdSessions(rest);
76
+ return;
77
+ default:
78
+ throw new Error(`Unknown command: ${command}`);
79
+ }
80
+ }
81
+
82
+ // --watch: keep the process alive and re-run sync on an interval. Each pass
83
+ // reuses the session-analytics sidecar cache and the upload watermarks, so a
84
+ // pass with nothing new is cheap (a directory signature stat + a no-op).
85
+ // The trigger tag rides context into cmdSync so run telemetry can report
86
+ // `watch` runs distinctly from scheduled/manual/notify ones (§2.11).
87
+ async function watchSync(rest) {
88
+ const args = rest.filter((arg) => arg !== "--watch");
89
+ const intervalIndex = args.indexOf("--interval");
90
+ let intervalMs = 15 * 60_000;
91
+ if (intervalIndex >= 0) {
92
+ const value = Number(args[intervalIndex + 1]);
93
+ if (Number.isFinite(value) && value >= 60_000) {
94
+ intervalMs = value;
95
+ args.splice(intervalIndex, 2);
96
+ }
97
+ }
98
+
99
+ process.stdout.write(`tokenusage sync --watch: every ${Math.round(intervalMs / 60_000)} min (Ctrl+C to stop)\n`);
100
+ for (;;) {
101
+ try {
102
+ await cmdSync(args, { trigger: "watch" });
103
+ } catch (error) {
104
+ // A failed pass (offline, backend 5xx) must not kill the watcher; the
105
+ // queue and watermarks retain everything for the next pass.
106
+ process.stderr.write(`sync pass failed: ${error?.message || error}\n`);
107
+ }
108
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
109
+ }
110
+ }
111
+
112
+ function printHelp() {
113
+ // Keep this short; npx users want quick guidance.
114
+ process.stdout.write(
115
+ [
116
+ "tokenusage",
117
+ "",
118
+ "Usage:",
119
+ " tokenusage -v, --version Show version info",
120
+ " tokenusage [--debug] init [--yes] [--dry-run] [--no-open] [--link-code <code>] [--run-report=on|off]",
121
+ " tokenusage [--debug] sync [--auto] [--drain] [--no-sessions] [--watch]",
122
+ " tokenusage [--debug] status [--probe-keychain] [--probe-keychain-details]",
123
+ " tokenusage [--debug] pause | resume",
124
+ " tokenusage [--debug] diagnostics [--out diagnostics.json]",
125
+ " tokenusage [--debug] doctor [--json] [--out doctor.json] [--base-url <url>]",
126
+ " tokenusage [--debug] uninstall [--purge]",
127
+ " tokenusage [--debug] device-login [--json] [--base-url <url>]",
128
+ " tokenusage sessions [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--format json|csv] [--out file] [--refresh] [--no-git]",
129
+ "",
130
+ "Notes:",
131
+ " - Pairing: device-login prints a code; approve it at the hosted /device page.",
132
+ " - sync parses local AI-tool session logs and uploads hourly token deltas",
133
+ " plus session metadata (no prompts, message bodies, paths or titles).",
134
+ " - --watch keeps running and syncs on an interval (increments only).",
135
+ " - --no-sessions skips the session metadata upload (hourly buckets only).",
136
+ " - auto sync waits for a device token.",
137
+ " - pause/resume stop and restart automatic collection (flag + scheduled",
138
+ " task); manual sync always runs.",
139
+ " - --debug shows original backend errors.",
140
+ " - sessions exports metadata-only efficiency analytics; no prompt or response text is retained.",
141
+ "",
142
+ ].join("\n"),
143
+ );
144
+ }
145
+
146
+ module.exports = { run };