tokenusage-cli 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/CHANGELOG.md +39 -19
  2. package/LICENSE +22 -22
  3. package/README.md +94 -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 +181 -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
@@ -1,205 +1,205 @@
1
- "use strict";
2
-
3
- const os = require("node:os");
4
- const path = require("node:path");
5
- const fs = require("node:fs/promises");
6
-
7
- const { readJson, updateJsonLocked } = require("../lib/fs");
8
- const { resolveTrackerPaths } = require("../lib/tracker-paths");
9
- const { resolveRuntimeConfig, assertInsforgeRuntime, normalizeInstanceBaseUrl, clearDeviceIdentity, resetInstanceState } = require("../lib/runtime-config");
10
- const { functionUrlFor, fetchFunctionResponse } = require("../lib/function-url");
11
-
12
- const POLL_INTERVAL_MS = 5_000;
13
- const ABSOLUTE_TIMEOUT_MS = 16 * 60 * 1000; // matches the 15-min server window with a small buffer
14
-
15
- async function authorize({ baseUrl, clientInfo, machineId, anonKey, timeoutMs = 20_000 }) {
16
- const res = await fetchFunctionResponse(functionUrlFor(baseUrl, "token-usage-device-flow-authorize"), {
17
- method: "POST",
18
- headers: { "Content-Type": "application/json", ...(anonKey ? { apikey: anonKey } : {}) },
19
- ...(timeoutMs > 0 ? { signal: AbortSignal.timeout(timeoutMs) } : {}),
20
- body: JSON.stringify({
21
- client_info: clientInfo,
22
- // Machine-stable identity: the server anchors the issued device to this
23
- // id instead of the hostname-derived display name, so hostname renames
24
- // don't mint duplicate devices and two machines sharing a default
25
- // hostname don't collapse into one (token ping-pong + row overwrite).
26
- ...(machineId ? { machine_id: machineId } : {}),
27
- }),
28
- });
29
- if (!res.ok) {
30
- const text = await res.text();
31
- throw new Error(`authorize failed (HTTP ${res.status}): ${text.slice(0, 200)}`);
32
- }
33
- return res.json();
34
- }
35
-
36
- async function pollOnce({ baseUrl, deviceCode, anonKey, timeoutMs = 20_000 }) {
37
- const res = await fetchFunctionResponse(functionUrlFor(baseUrl, "token-usage-device-flow-poll"), {
38
- method: "POST",
39
- headers: { "Content-Type": "application/json", ...(anonKey ? { apikey: anonKey } : {}) },
40
- ...(timeoutMs > 0 ? { signal: AbortSignal.timeout(timeoutMs) } : {}),
41
- body: JSON.stringify({ device_code: deviceCode }),
42
- });
43
- const data = await res.json().catch(() => ({}));
44
- // 404 = unknown, 410 = expired, 200 = {status, user_id?, device_token?}.
45
- // Anything else (502 from a misconfigured edge, 5xx during deploy, …) must
46
- // bubble up as a network-style error — masking it as "unknown" would tell
47
- // the user their device_code was evicted when it wasn't.
48
- if (!res.ok && res.status !== 404 && res.status !== 410) {
49
- throw new Error(`poll HTTP ${res.status}: ${(data?.error ?? "").toString().slice(0, 200)}`);
50
- }
51
- return {
52
- status: data.status ?? "unknown",
53
- user_id: data.user_id ?? null,
54
- deviceToken: data.device_token ?? data.deviceToken ?? null,
55
- deviceId: data.device_id ?? data.deviceId ?? null,
56
- httpStatus: res.status,
57
- };
58
- }
59
-
60
- function sleep(ms) {
61
- return new Promise((resolve) => setTimeout(resolve, ms));
62
- }
63
-
64
- async function cmdDeviceLogin(argv = [], options = {}) {
65
- const opts = parseArgs(argv);
66
- const home = options.home || os.homedir();
67
- const sleepFn = options.sleep || sleep;
68
- const { trackerDir } = await resolveTrackerPaths({ home });
69
- const configPath = path.join(trackerDir, "config.json");
70
- const config = (await readJson(configPath)) || {};
71
- if (opts.anonKeyFile) opts.anonKey = (await fs.readFile(opts.anonKeyFile, "utf8")).trim();
72
- const runtime = assertInsforgeRuntime(resolveRuntimeConfig({
73
- cli: { baseUrl: opts.baseUrl || process.env.TOKENUSAGE_BASE_URL || process.env.TOKENUSAGE_API_URL,
74
- anonKey: opts.anonKey, dashboardUrl: opts.dashboardUrl }, config, env: process.env,
75
- }));
76
- const baseUrl = runtime.baseUrl;
77
-
78
- const clientInfo = `${os.platform()}-${os.arch()} ${os.hostname()}`;
79
- // Same machineId the local API serves to the dashboard — both login paths
80
- // must resolve to the SAME cloud device row for this machine.
81
- const { getOrCreateMachineId } = require("../lib/local-api");
82
- const machineId = getOrCreateMachineId(path.join(trackerDir, "queue.jsonl"));
83
- process.stdout.write(`Requesting device code from ${baseUrl}...\n`);
84
- const authResp = await authorize({ baseUrl, clientInfo, machineId, anonKey: runtime.anonKey, timeoutMs: runtime.httpTimeoutMs });
85
- if (typeof authResp.verification_uri !== "string" || !authResp.verification_uri || !authResp.device_code) {
86
- throw new Error("Device authorization returned an incomplete response");
87
- }
88
- const dashboard = new URL(runtime.dashboardUrl);
89
- const expectedPath = dashboard.pathname.replace(/\/$/, "") + "/device";
90
- for (const value of [authResp.verification_uri, authResp.verification_uri_complete].filter(Boolean)) {
91
- const returned = new URL(value);
92
- if (returned.origin !== dashboard.origin || returned.pathname !== expectedPath || returned.username || returned.password) {
93
- throw new Error("Device authorization returned a different dashboard. Configure --dashboard-url for this instance.");
94
- }
95
- }
96
- await updateJsonLocked(configPath, async current => {
97
- const previous = resolveRuntimeConfig({ config, env: {} });
98
- const latest = resolveRuntimeConfig({ config: current, env: {} });
99
- if ((latest.baseUrl !== previous.baseUrl || latest.anonKey !== previous.anonKey) &&
100
- (latest.baseUrl !== baseUrl || latest.anonKey !== runtime.anonKey)) {
101
- throw new Error("Backend instance changed during device login");
102
- }
103
- const changedInstance = previous.baseUrl !== baseUrl || previous.anonKey !== runtime.anonKey;
104
- if (changedInstance) resetInstanceState(trackerDir);
105
- return { ...(changedInstance ? clearDeviceIdentity(current) : current), baseUrl,
106
- anonKey: runtime.anonKey, dashboardUrl: runtime.dashboardUrl };
107
- });
108
-
109
- if (opts.json) {
110
- process.stdout.write(JSON.stringify(authResp, null, 2) + "\n");
111
- } else {
112
- process.stdout.write(
113
- [
114
- "",
115
- " Sign in from a browser:",
116
- ` ${authResp.verification_uri_complete || authResp.verification_uri}`,
117
- "",
118
- ` Or visit ${authResp.verification_uri} and enter the code:`,
119
- "",
120
- ` ${authResp.user_code}`,
121
- "",
122
- ` This code expires in ${Math.round(authResp.expires_in / 60)} minutes.`,
123
- " Polling every 5 seconds until you approve…",
124
- "",
125
- ].join("\n"),
126
- );
127
- }
128
-
129
- const startedAt = Date.now();
130
- let consecutiveErrors = 0;
131
- const MAX_BACKOFF_MS = 30_000;
132
- while (Date.now() - startedAt < ABSOLUTE_TIMEOUT_MS) {
133
- // Exponential backoff on consecutive network failures (capped at 30s) so
134
- // a flaky network doesn't hammer the server at the full 5s cadence for
135
- // the entire 15-minute window. ±20% jitter on retries prevents
136
- // thundering-herd reconnects when many CLIs lose connectivity at once.
137
- let wait =
138
- consecutiveErrors === 0
139
- ? POLL_INTERVAL_MS
140
- : Math.min(POLL_INTERVAL_MS * Math.pow(2, consecutiveErrors - 1), MAX_BACKOFF_MS);
141
- if (consecutiveErrors > 0) {
142
- const jitter = wait * 0.2 * (Math.random() * 2 - 1);
143
- wait = Math.max(POLL_INTERVAL_MS, wait + jitter);
144
- }
145
- await sleepFn(wait);
146
- let result;
147
- try {
148
- result = await pollOnce({ baseUrl, deviceCode: authResp.device_code, anonKey: runtime.anonKey, timeoutMs: runtime.httpTimeoutMs });
149
- consecutiveErrors = 0;
150
- } catch (e) {
151
- consecutiveErrors++;
152
- process.stderr.write(`poll error (retry ${consecutiveErrors}): ${e?.message || e}\n`);
153
- continue;
154
- }
155
- if (result.status === "approved" && result.user_id) {
156
- if (!result.deviceToken) {
157
- throw new Error("device login approved but server did not return a device token");
158
- }
159
- await updateJsonLocked(configPath, async (current) => {
160
- if (normalizeInstanceBaseUrl(current.baseUrl) !== baseUrl || current.anonKey !== runtime.anonKey) {
161
- throw new Error("Backend instance changed during device login");
162
- }
163
- return { ...current,
164
- ...(machineId ? { machineId } : {}),
165
- baseUrl,
166
- user_id: result.user_id,
167
- deviceToken: result.deviceToken,
168
- deviceTokenBaseUrl: baseUrl,
169
- deviceId: result.deviceId || current.deviceId || config.deviceId,
170
- device_login_at: new Date().toISOString(),
171
- };
172
- });
173
- process.stdout.write(`\nApproved. device token written to ${configPath}\n`);
174
- return;
175
- }
176
- if (result.status === "expired") {
177
- throw new Error("device_code expired — re-run `tracker device-login`");
178
- }
179
- if (result.status === "unknown") {
180
- throw new Error("device_code is unknown — server may have evicted it");
181
- }
182
- // status === "pending" → just keep polling silently
183
- }
184
- throw new Error("device-login timed out without approval");
185
- }
186
-
187
- function parseArgs(argv) {
188
- const out = { json: false, baseUrl: null, anonKey: null, anonKeyFile: null, dashboardUrl: null };
189
- for (let i = 0; i < argv.length; i++) {
190
- const a = argv[i];
191
- if (a === "--json") out.json = true;
192
- else if (a === "--base-url") {
193
- out.baseUrl = argv[++i] || null;
194
- } else if (a === "--anon-key") {
195
- out.anonKey = argv[++i] || null;
196
- } else if (a === "--anon-key-file") {
197
- out.anonKeyFile = argv[++i] || null;
198
- } else if (a === "--dashboard-url") {
199
- out.dashboardUrl = argv[++i] || null;
200
- } else throw new Error(`Unknown option: ${a}`);
201
- }
202
- return out;
203
- }
204
-
205
- module.exports = { cmdDeviceLogin, authorize, pollOnce };
1
+ "use strict";
2
+
3
+ const os = require("node:os");
4
+ const path = require("node:path");
5
+ const fs = require("node:fs/promises");
6
+
7
+ const { readJson, updateJsonLocked } = require("../lib/fs");
8
+ const { resolveTrackerPaths } = require("../lib/tracker-paths");
9
+ const { resolveRuntimeConfig, assertInsforgeRuntime, normalizeInstanceBaseUrl, clearDeviceIdentity, resetInstanceState } = require("../lib/runtime-config");
10
+ const { functionUrlFor, fetchFunctionResponse } = require("../lib/function-url");
11
+
12
+ const POLL_INTERVAL_MS = 5_000;
13
+ const ABSOLUTE_TIMEOUT_MS = 16 * 60 * 1000; // matches the 15-min server window with a small buffer
14
+
15
+ async function authorize({ baseUrl, clientInfo, machineId, anonKey, timeoutMs = 20_000 }) {
16
+ const res = await fetchFunctionResponse(functionUrlFor(baseUrl, "token-usage-device-flow-authorize"), {
17
+ method: "POST",
18
+ headers: { "Content-Type": "application/json", ...(anonKey ? { apikey: anonKey } : {}) },
19
+ ...(timeoutMs > 0 ? { signal: AbortSignal.timeout(timeoutMs) } : {}),
20
+ body: JSON.stringify({
21
+ client_info: clientInfo,
22
+ // Machine-stable identity: the server anchors the issued device to this
23
+ // id instead of the hostname-derived display name, so hostname renames
24
+ // don't mint duplicate devices and two machines sharing a default
25
+ // hostname don't collapse into one (token ping-pong + row overwrite).
26
+ ...(machineId ? { machine_id: machineId } : {}),
27
+ }),
28
+ });
29
+ if (!res.ok) {
30
+ const text = await res.text();
31
+ throw new Error(`authorize failed (HTTP ${res.status}): ${text.slice(0, 200)}`);
32
+ }
33
+ return res.json();
34
+ }
35
+
36
+ async function pollOnce({ baseUrl, deviceCode, anonKey, timeoutMs = 20_000 }) {
37
+ const res = await fetchFunctionResponse(functionUrlFor(baseUrl, "token-usage-device-flow-poll"), {
38
+ method: "POST",
39
+ headers: { "Content-Type": "application/json", ...(anonKey ? { apikey: anonKey } : {}) },
40
+ ...(timeoutMs > 0 ? { signal: AbortSignal.timeout(timeoutMs) } : {}),
41
+ body: JSON.stringify({ device_code: deviceCode }),
42
+ });
43
+ const data = await res.json().catch(() => ({}));
44
+ // 404 = unknown, 410 = expired, 200 = {status, user_id?, device_token?}.
45
+ // Anything else (502 from a misconfigured edge, 5xx during deploy, …) must
46
+ // bubble up as a network-style error — masking it as "unknown" would tell
47
+ // the user their device_code was evicted when it wasn't.
48
+ if (!res.ok && res.status !== 404 && res.status !== 410) {
49
+ throw new Error(`poll HTTP ${res.status}: ${(data?.error ?? "").toString().slice(0, 200)}`);
50
+ }
51
+ return {
52
+ status: data.status ?? "unknown",
53
+ user_id: data.user_id ?? null,
54
+ deviceToken: data.device_token ?? data.deviceToken ?? null,
55
+ deviceId: data.device_id ?? data.deviceId ?? null,
56
+ httpStatus: res.status,
57
+ };
58
+ }
59
+
60
+ function sleep(ms) {
61
+ return new Promise((resolve) => setTimeout(resolve, ms));
62
+ }
63
+
64
+ async function cmdDeviceLogin(argv = [], options = {}) {
65
+ const opts = parseArgs(argv);
66
+ const home = options.home || os.homedir();
67
+ const sleepFn = options.sleep || sleep;
68
+ const { trackerDir } = await resolveTrackerPaths({ home });
69
+ const configPath = path.join(trackerDir, "config.json");
70
+ const config = (await readJson(configPath)) || {};
71
+ if (opts.anonKeyFile) opts.anonKey = (await fs.readFile(opts.anonKeyFile, "utf8")).trim();
72
+ const runtime = assertInsforgeRuntime(resolveRuntimeConfig({
73
+ cli: { baseUrl: opts.baseUrl || process.env.TOKENUSAGE_BASE_URL || process.env.TOKENUSAGE_API_URL,
74
+ anonKey: opts.anonKey, dashboardUrl: opts.dashboardUrl }, config, env: process.env,
75
+ }));
76
+ const baseUrl = runtime.baseUrl;
77
+
78
+ const clientInfo = `${os.platform()}-${os.arch()} ${os.hostname()}`;
79
+ // Same machineId the local API serves to the dashboard — both login paths
80
+ // must resolve to the SAME cloud device row for this machine.
81
+ const { getOrCreateMachineId } = require("../lib/local-api");
82
+ const machineId = getOrCreateMachineId(path.join(trackerDir, "queue.jsonl"));
83
+ process.stdout.write(`Requesting device code from ${baseUrl}...\n`);
84
+ const authResp = await authorize({ baseUrl, clientInfo, machineId, anonKey: runtime.anonKey, timeoutMs: runtime.httpTimeoutMs });
85
+ if (typeof authResp.verification_uri !== "string" || !authResp.verification_uri || !authResp.device_code) {
86
+ throw new Error("Device authorization returned an incomplete response");
87
+ }
88
+ const dashboard = new URL(runtime.dashboardUrl);
89
+ const expectedPath = dashboard.pathname.replace(/\/$/, "") + "/device";
90
+ for (const value of [authResp.verification_uri, authResp.verification_uri_complete].filter(Boolean)) {
91
+ const returned = new URL(value);
92
+ if (returned.origin !== dashboard.origin || returned.pathname !== expectedPath || returned.username || returned.password) {
93
+ throw new Error("Device authorization returned a different dashboard. Configure --dashboard-url for this instance.");
94
+ }
95
+ }
96
+ await updateJsonLocked(configPath, async current => {
97
+ const previous = resolveRuntimeConfig({ config, env: {} });
98
+ const latest = resolveRuntimeConfig({ config: current, env: {} });
99
+ if ((latest.baseUrl !== previous.baseUrl || latest.anonKey !== previous.anonKey) &&
100
+ (latest.baseUrl !== baseUrl || latest.anonKey !== runtime.anonKey)) {
101
+ throw new Error("Backend instance changed during device login");
102
+ }
103
+ const changedInstance = previous.baseUrl !== baseUrl || previous.anonKey !== runtime.anonKey;
104
+ if (changedInstance) resetInstanceState(trackerDir);
105
+ return { ...(changedInstance ? clearDeviceIdentity(current) : current), baseUrl,
106
+ anonKey: runtime.anonKey, dashboardUrl: runtime.dashboardUrl };
107
+ });
108
+
109
+ if (opts.json) {
110
+ process.stdout.write(JSON.stringify(authResp, null, 2) + "\n");
111
+ } else {
112
+ process.stdout.write(
113
+ [
114
+ "",
115
+ " Sign in from a browser:",
116
+ ` ${authResp.verification_uri_complete || authResp.verification_uri}`,
117
+ "",
118
+ ` Or visit ${authResp.verification_uri} and enter the code:`,
119
+ "",
120
+ ` ${authResp.user_code}`,
121
+ "",
122
+ ` This code expires in ${Math.round(authResp.expires_in / 60)} minutes.`,
123
+ " Polling every 5 seconds until you approve…",
124
+ "",
125
+ ].join("\n"),
126
+ );
127
+ }
128
+
129
+ const startedAt = Date.now();
130
+ let consecutiveErrors = 0;
131
+ const MAX_BACKOFF_MS = 30_000;
132
+ while (Date.now() - startedAt < ABSOLUTE_TIMEOUT_MS) {
133
+ // Exponential backoff on consecutive network failures (capped at 30s) so
134
+ // a flaky network doesn't hammer the server at the full 5s cadence for
135
+ // the entire 15-minute window. ±20% jitter on retries prevents
136
+ // thundering-herd reconnects when many CLIs lose connectivity at once.
137
+ let wait =
138
+ consecutiveErrors === 0
139
+ ? POLL_INTERVAL_MS
140
+ : Math.min(POLL_INTERVAL_MS * Math.pow(2, consecutiveErrors - 1), MAX_BACKOFF_MS);
141
+ if (consecutiveErrors > 0) {
142
+ const jitter = wait * 0.2 * (Math.random() * 2 - 1);
143
+ wait = Math.max(POLL_INTERVAL_MS, wait + jitter);
144
+ }
145
+ await sleepFn(wait);
146
+ let result;
147
+ try {
148
+ result = await pollOnce({ baseUrl, deviceCode: authResp.device_code, anonKey: runtime.anonKey, timeoutMs: runtime.httpTimeoutMs });
149
+ consecutiveErrors = 0;
150
+ } catch (e) {
151
+ consecutiveErrors++;
152
+ process.stderr.write(`poll error (retry ${consecutiveErrors}): ${e?.message || e}\n`);
153
+ continue;
154
+ }
155
+ if (result.status === "approved" && result.user_id) {
156
+ if (!result.deviceToken) {
157
+ throw new Error("device login approved but server did not return a device token");
158
+ }
159
+ await updateJsonLocked(configPath, async (current) => {
160
+ if (normalizeInstanceBaseUrl(current.baseUrl) !== baseUrl || current.anonKey !== runtime.anonKey) {
161
+ throw new Error("Backend instance changed during device login");
162
+ }
163
+ return { ...current,
164
+ ...(machineId ? { machineId } : {}),
165
+ baseUrl,
166
+ user_id: result.user_id,
167
+ deviceToken: result.deviceToken,
168
+ deviceTokenBaseUrl: baseUrl,
169
+ deviceId: result.deviceId || current.deviceId || config.deviceId,
170
+ device_login_at: new Date().toISOString(),
171
+ };
172
+ });
173
+ process.stdout.write(`\nApproved. device token written to ${configPath}\n`);
174
+ return;
175
+ }
176
+ if (result.status === "expired") {
177
+ throw new Error("device_code expired — re-run `tracker device-login`");
178
+ }
179
+ if (result.status === "unknown") {
180
+ throw new Error("device_code is unknown — server may have evicted it");
181
+ }
182
+ // status === "pending" → just keep polling silently
183
+ }
184
+ throw new Error("device-login timed out without approval");
185
+ }
186
+
187
+ function parseArgs(argv) {
188
+ const out = { json: false, baseUrl: null, anonKey: null, anonKeyFile: null, dashboardUrl: null };
189
+ for (let i = 0; i < argv.length; i++) {
190
+ const a = argv[i];
191
+ if (a === "--json") out.json = true;
192
+ else if (a === "--base-url") {
193
+ out.baseUrl = argv[++i] || null;
194
+ } else if (a === "--anon-key") {
195
+ out.anonKey = argv[++i] || null;
196
+ } else if (a === "--anon-key-file") {
197
+ out.anonKeyFile = argv[++i] || null;
198
+ } else if (a === "--dashboard-url") {
199
+ out.dashboardUrl = argv[++i] || null;
200
+ } else throw new Error(`Unknown option: ${a}`);
201
+ }
202
+ return out;
203
+ }
204
+
205
+ module.exports = { cmdDeviceLogin, authorize, pollOnce };
@@ -1,38 +1,38 @@
1
- const path = require("node:path");
2
-
3
- const { writeFileAtomic, chmod600IfPossible } = require("../lib/fs");
4
- const { collectTrackerDiagnostics } = require("../lib/diagnostics");
5
-
6
- async function cmdDiagnostics(argv = []) {
7
- const opts = parseArgs(argv);
8
- const diagnostics = await collectTrackerDiagnostics();
9
- const json = JSON.stringify(diagnostics, null, opts.compact ? 0 : 2) + "\n";
10
-
11
- if (opts.out) {
12
- const outPath = path.resolve(process.cwd(), opts.out);
13
- await writeFileAtomic(outPath, json);
14
- await chmod600IfPossible(outPath);
15
- process.stderr.write(`Wrote diagnostics to: ${outPath}\n`);
16
- }
17
-
18
- process.stdout.write(json);
19
- }
20
-
21
- function parseArgs(argv) {
22
- const out = {
23
- out: null,
24
- compact: false,
25
- };
26
-
27
- for (let i = 0; i < argv.length; i++) {
28
- const a = argv[i];
29
- if (a === "--out") out.out = argv[++i] || null;
30
- else if (a === "--compact") out.compact = true;
31
- else if (a === "--pretty") out.compact = false;
32
- else throw new Error(`Unknown option: ${a}`);
33
- }
34
-
35
- return out;
36
- }
37
-
38
- module.exports = { cmdDiagnostics };
1
+ const path = require("node:path");
2
+
3
+ const { writeFileAtomic, chmod600IfPossible } = require("../lib/fs");
4
+ const { collectTrackerDiagnostics } = require("../lib/diagnostics");
5
+
6
+ async function cmdDiagnostics(argv = []) {
7
+ const opts = parseArgs(argv);
8
+ const diagnostics = await collectTrackerDiagnostics();
9
+ const json = JSON.stringify(diagnostics, null, opts.compact ? 0 : 2) + "\n";
10
+
11
+ if (opts.out) {
12
+ const outPath = path.resolve(process.cwd(), opts.out);
13
+ await writeFileAtomic(outPath, json);
14
+ await chmod600IfPossible(outPath);
15
+ process.stderr.write(`Wrote diagnostics to: ${outPath}\n`);
16
+ }
17
+
18
+ process.stdout.write(json);
19
+ }
20
+
21
+ function parseArgs(argv) {
22
+ const out = {
23
+ out: null,
24
+ compact: false,
25
+ };
26
+
27
+ for (let i = 0; i < argv.length; i++) {
28
+ const a = argv[i];
29
+ if (a === "--out") out.out = argv[++i] || null;
30
+ else if (a === "--compact") out.compact = true;
31
+ else if (a === "--pretty") out.compact = false;
32
+ else throw new Error(`Unknown option: ${a}`);
33
+ }
34
+
35
+ return out;
36
+ }
37
+
38
+ module.exports = { cmdDiagnostics };