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
@@ -0,0 +1,138 @@
1
+ "use strict";
2
+
3
+ // Per-run telemetry for docs/cli-contract.md §2.11
4
+ // (POST /api/functions/token-usage-sync-report): one record per completed
5
+ // sync — empty runs included. Reporting is strictly best-effort: a failure,
6
+ // a 404 (older backend) or a 5xx only reaches the local log and NEVER
7
+ // affects the ingest that already happened or the process exit code.
8
+ // run_id is the client-side idempotency key (`<started_at epoch ms>-<4hex>`),
9
+ // so a retry after a lost response dedupes server-side instead of double-
10
+ // counting the run.
11
+
12
+ const os = require("node:os");
13
+ const { functionUrlFor, fetchFunctionResponse } = require("./function-url");
14
+
15
+ const SYNC_REPORT_SLUG = "token-usage-sync-report";
16
+
17
+ function buildRunId(startedAtMs = Date.now(), randomBytes = 2) {
18
+ const crypto = require("node:crypto");
19
+ return `${startedAtMs}-${crypto.randomBytes(randomBytes).toString("hex")}`;
20
+ }
21
+
22
+ // Contract trigger enum: scheduled | manual | watch | notify. The auto-ish
23
+ // background flavors (retry, publish, openclaw signal) fold into the four
24
+ // allowed values: hook/signal spawns are notify, everything scheduled or
25
+ // retrying is scheduled, the --watch loop is watch, a plain CLI run is manual.
26
+ function resolveSyncTrigger(opts = {}, context = {}) {
27
+ if (context?.trigger === "watch") return "watch";
28
+ if (opts?.fromNotify || opts?.fromOpenclaw) return "notify";
29
+ if (opts?.auto || opts?.background || opts?.fromRetry) return "scheduled";
30
+ return "manual";
31
+ }
32
+
33
+ /**
34
+ * Collects the §2.11 whitelist fields across one run. `log` receives the
35
+ * local-only failure lines (the contract's error details never leave the
36
+ * machine beyond the stable response codes).
37
+ */
38
+ function createSyncRunTelemetry({
39
+ trigger,
40
+ startedAtMs = Date.now(),
41
+ runId = buildRunId(startedAtMs),
42
+ cliVersion,
43
+ osLabel = `${process.platform} ${os.release()}`,
44
+ log = () => {},
45
+ } = {}) {
46
+ let parsedFiles = 0;
47
+ let bucketsUploaded = 0;
48
+ let tokensIngested = 0;
49
+ let sessionsUploaded = 0;
50
+ let sessionsSkipped = 0;
51
+ let queueBytes = null;
52
+ let result = "ok";
53
+ let errorCode = null;
54
+ let reported = false;
55
+
56
+ return {
57
+ runId,
58
+ trigger,
59
+ noteParsedFiles(count) {
60
+ parsedFiles = Math.max(0, Number(count) || 0);
61
+ },
62
+ // Server-acked drain result: buckets placed into successful ingest
63
+ // requests plus their total_tokens sum (client-side telemetry semantics
64
+ // per §2.11 — a larger replay may override these buckets later).
65
+ noteUpload({ inserted = 0, tokens = 0 } = {}) {
66
+ bucketsUploaded += Math.max(0, Number(inserted) || 0);
67
+ tokensIngested += Math.max(0, Number(tokens) || 0);
68
+ },
69
+ noteSessions({ upserted = 0, skipped = 0 } = {}) {
70
+ sessionsUploaded += Math.max(0, Number(upserted) || 0);
71
+ sessionsSkipped += Math.max(0, Number(skipped) || 0);
72
+ },
73
+ setOutcome({ result: nextResult, errorCode: nextErrorCode = null }) {
74
+ result = nextResult;
75
+ errorCode = nextErrorCode;
76
+ },
77
+ noteQueueBytes(bytes) {
78
+ queueBytes = Math.max(0, Number(bytes) || 0);
79
+ },
80
+ snapshot() {
81
+ return {
82
+ run_id: runId,
83
+ started_at: new Date(startedAtMs).toISOString(),
84
+ ended_at: new Date().toISOString(),
85
+ trigger,
86
+ result,
87
+ ...(errorCode ? { error_code: errorCode } : {}),
88
+ parsed_files: parsedFiles,
89
+ buckets_uploaded: bucketsUploaded,
90
+ tokens_ingested: tokensIngested,
91
+ sessions_uploaded: sessionsUploaded,
92
+ sessions_skipped: sessionsSkipped,
93
+ queue_bytes: queueBytes,
94
+ cli_version: cliVersion,
95
+ os: osLabel,
96
+ };
97
+ },
98
+ /**
99
+ * POST the run record. Unpaired runs (no device token / base URL) skip
100
+ * silently — there is no backend to report to. Every failure path logs
101
+ * locally and resolves false; nothing here may throw into the sync flow.
102
+ */
103
+ async report({ baseUrl, anonKey, deviceToken } = {}) {
104
+ if (reported) return false;
105
+ if (!deviceToken || !baseUrl) return false;
106
+ reported = true;
107
+
108
+ const payload = this.snapshot();
109
+ try {
110
+ const headers = {
111
+ "Content-Type": "application/json",
112
+ Accept: "application/json",
113
+ Authorization: `Bearer ${deviceToken}`,
114
+ };
115
+ if (anonKey) headers.apikey = anonKey;
116
+ const res = await fetchFunctionResponse(
117
+ functionUrlFor(baseUrl, SYNC_REPORT_SLUG),
118
+ { method: "POST", headers, body: JSON.stringify(payload) },
119
+ );
120
+ if (!res.ok) {
121
+ log(`Run report skipped (HTTP ${res.status})`);
122
+ return false;
123
+ }
124
+ return true;
125
+ } catch (error) {
126
+ log(`Run report failed (kept locally): ${error?.message || error}`);
127
+ return false;
128
+ }
129
+ },
130
+ };
131
+ }
132
+
133
+ module.exports = {
134
+ SYNC_REPORT_SLUG,
135
+ buildRunId,
136
+ resolveSyncTrigger,
137
+ createSyncRunTelemetry,
138
+ };
@@ -1,193 +1,193 @@
1
- "use strict";
2
-
3
- /**
4
- * Anonymous daily heartbeat for counting active installs.
5
- *
6
- * Privacy contract (documented in README "Privacy" section — keep in sync):
7
- * the payload carries exactly four fields — a one-way sha256 hash of the
8
- * machine id, the app version, `process.platform`, and the app shell
9
- * (cli / macos / windows / linux). No token counts, no model names, no usernames,
10
- * no paths. Opt out with TOKENUSAGE_NO_TELEMETRY=1, the DO_NOT_TRACK
11
- * standard, or `"telemetry": false` in config.json.
12
- */
13
-
14
- const path = require("node:path");
15
- const crypto = require("node:crypto");
16
-
17
- const pkg = require("../../package.json");
18
- const { readJson, writeJson } = require("./fs");
19
- const { getOrCreateMachineId } = require("./machine-id");
20
- const { resolveRuntimeConfig } = require("./runtime-config");
21
- const { functionUrlFor, fetchFunctionResponse } = require("./function-url");
22
- const {
23
- decideAutoUpload,
24
- recordUploadSuccess,
25
- recordUploadFailure,
26
- } = require("./upload-throttle");
27
-
28
- const HEARTBEAT_FUNCTION_SLUG = "tokenusage-telemetry";
29
- const HEARTBEAT_STATE_FILE = "telemetry.heartbeat.json";
30
- const HEARTBEAT_INTERVAL_MS = 24 * 60 * 60 * 1000;
31
- // The hash namespace is versioned so the anonymous id can be rotated fleet-wide
32
- // by bumping the string. sha256(namespace + machineId) cannot be joined back to
33
- // the cloud device rows (those store the machineId itself).
34
- const MACHINE_HASH_NAMESPACE = "tokenusage-telemetry-v1:";
35
- // Generous because some networks need 3-4s just for the TLS handshake to the
36
- // cloud host; sync awaits this at most once per day so the worst-case stall
37
- // is bounded and rare.
38
- const DEFAULT_TIMEOUT_MS = 10_000;
39
- const VALID_SHELLS = new Set(["cli", "macos", "windows", "linux"]);
40
-
41
- const THROTTLE_CONFIG = {
42
- intervalMs: HEARTBEAT_INTERVAL_MS,
43
- jitterMsMax: 60_000,
44
- backoffInitialMs: 60 * 60_000, // failures retry hourly at most
45
- backoffMaxMs: HEARTBEAT_INTERVAL_MS,
46
- };
47
-
48
- function isTelemetryDisabled({ env = process.env, config = {} } = {}) {
49
- if (isTruthyFlag(env?.TOKENUSAGE_NO_TELEMETRY)) return true;
50
- if (isTruthyFlag(env?.DO_NOT_TRACK)) return true;
51
- if (config && config.telemetry === false) return true;
52
- return false;
53
- }
54
-
55
- function isTruthyFlag(value) {
56
- if (typeof value !== "string") return false;
57
- const v = value.trim().toLowerCase();
58
- return v === "1" || v === "true";
59
- }
60
-
61
- function hashMachineId(machineId) {
62
- return crypto
63
- .createHash("sha256")
64
- .update(`${MACHINE_HASH_NAMESPACE}${machineId}`)
65
- .digest("hex");
66
- }
67
-
68
- function resolveShell(env = process.env) {
69
- const raw = typeof env?.TOKENUSAGE_APP_SHELL === "string"
70
- ? env.TOKENUSAGE_APP_SHELL.trim().toLowerCase()
71
- : "";
72
- return VALID_SHELLS.has(raw) ? raw : "cli";
73
- }
74
-
75
- function buildHeartbeatPayload({ machineId, version = pkg.version, platform = process.platform, env = process.env }) {
76
- return {
77
- machine_hash: hashMachineId(machineId),
78
- app_version: String(version || "").slice(0, 32),
79
- platform: String(platform || "unknown").slice(0, 16),
80
- shell: resolveShell(env),
81
- };
82
- }
83
-
84
- /**
85
- * Send the daily heartbeat if allowed. Never throws; every failure path is a
86
- * silent no-op so serve/sync flow is never affected. Returns a small status
87
- * object for tests and debug logging.
88
- */
89
- async function maybeSendHeartbeat({
90
- trackerDir,
91
- fetchImpl = fetch,
92
- nowMs = Date.now(),
93
- env = process.env,
94
- timeoutMs = DEFAULT_TIMEOUT_MS,
95
- version,
96
- } = {}) {
97
- try {
98
- if (!trackerDir) return { sent: false, reason: "no-tracker-dir" };
99
-
100
- // Never phone home from the node test runner: many tests drive cmdSync /
101
- // cmdServe directly from sandboxed temp homes, and their fresh throttle
102
- // state would let a real POST through to production on every run. Tests
103
- // that exercise this module inject their own env without this marker.
104
- if (env?.NODE_TEST_CONTEXT !== undefined) {
105
- return { sent: false, reason: "test-env" };
106
- }
107
-
108
- const configPath = path.join(trackerDir, "config.json");
109
- const config = (await readJson(configPath)) || {};
110
- if (isTelemetryDisabled({ env, config })) {
111
- return { sent: false, reason: "opt-out" };
112
- }
113
-
114
- const statePath = path.join(trackerDir, HEARTBEAT_STATE_FILE);
115
- const state = await readJson(statePath);
116
- const decision = decideAutoUpload({
117
- nowMs,
118
- pendingBytes: 1, // heartbeats always have "one ping pending"
119
- state,
120
- config: THROTTLE_CONFIG,
121
- });
122
- if (!decision.allowed) {
123
- return { sent: false, reason: "throttled", blockedUntilMs: decision.blockedUntilMs };
124
- }
125
-
126
- const machineId = getOrCreateMachineId(path.join(trackerDir, "queue.jsonl"));
127
- if (!machineId) return { sent: false, reason: "no-machine-id" };
128
-
129
- const runtime = resolveRuntimeConfig({ config, env });
130
- const payload = buildHeartbeatPayload({ machineId, version, env });
131
-
132
- const controller = new AbortController();
133
- const timer = setTimeout(() => controller.abort(), timeoutMs);
134
- let response;
135
- try {
136
- response = await fetchFunctionResponse(functionUrlFor(runtime.baseUrl, HEARTBEAT_FUNCTION_SLUG), {
137
- method: "POST",
138
- headers: {
139
- "Content-Type": "application/json",
140
- apikey: runtime.anonKey,
141
- },
142
- body: JSON.stringify(payload),
143
- signal: controller.signal,
144
- }, fetchImpl);
145
- } finally {
146
- clearTimeout(timer);
147
- }
148
-
149
- if (!response || !response.ok) {
150
- const failedState = recordUploadFailure({
151
- nowMs,
152
- state,
153
- error: { message: `heartbeat http ${response?.status || "error"}`, status: response?.status },
154
- config: THROTTLE_CONFIG,
155
- });
156
- await writeJson(statePath, failedState);
157
- return { sent: false, reason: "http-error", status: response?.status };
158
- }
159
-
160
- const nextState = recordUploadSuccess({ nowMs, state, config: THROTTLE_CONFIG });
161
- await writeJson(statePath, nextState);
162
- return { sent: true, reason: "sent" };
163
- } catch (e) {
164
- // Includes abort/network errors: record backoff if we can, stay silent.
165
- try {
166
- const statePath = path.join(trackerDir, HEARTBEAT_STATE_FILE);
167
- const state = await readJson(statePath);
168
- await writeJson(
169
- statePath,
170
- recordUploadFailure({
171
- nowMs,
172
- state,
173
- error: { message: String(e?.message || e) },
174
- config: THROTTLE_CONFIG,
175
- }),
176
- );
177
- } catch {
178
- // Even state persistence failed — nothing else to do.
179
- }
180
- return { sent: false, reason: "error" };
181
- }
182
- }
183
-
184
- module.exports = {
185
- HEARTBEAT_FUNCTION_SLUG,
186
- HEARTBEAT_STATE_FILE,
187
- HEARTBEAT_INTERVAL_MS,
188
- isTelemetryDisabled,
189
- hashMachineId,
190
- resolveShell,
191
- buildHeartbeatPayload,
192
- maybeSendHeartbeat,
193
- };
1
+ "use strict";
2
+
3
+ /**
4
+ * Anonymous daily heartbeat for counting active installs.
5
+ *
6
+ * Privacy contract (documented in README "Privacy" section — keep in sync):
7
+ * the payload carries exactly four fields — a one-way sha256 hash of the
8
+ * machine id, the app version, `process.platform`, and the app shell
9
+ * (cli / macos / windows / linux). No token counts, no model names, no usernames,
10
+ * no paths. Opt out with TOKENUSAGE_NO_TELEMETRY=1, the DO_NOT_TRACK
11
+ * standard, or `"telemetry": false` in config.json.
12
+ */
13
+
14
+ const path = require("node:path");
15
+ const crypto = require("node:crypto");
16
+
17
+ const pkg = require("../../package.json");
18
+ const { readJson, writeJson } = require("./fs");
19
+ const { getOrCreateMachineId } = require("./machine-id");
20
+ const { resolveRuntimeConfig } = require("./runtime-config");
21
+ const { functionUrlFor, fetchFunctionResponse } = require("./function-url");
22
+ const {
23
+ decideAutoUpload,
24
+ recordUploadSuccess,
25
+ recordUploadFailure,
26
+ } = require("./upload-throttle");
27
+
28
+ const HEARTBEAT_FUNCTION_SLUG = "tokenusage-telemetry";
29
+ const HEARTBEAT_STATE_FILE = "telemetry.heartbeat.json";
30
+ const HEARTBEAT_INTERVAL_MS = 24 * 60 * 60 * 1000;
31
+ // The hash namespace is versioned so the anonymous id can be rotated fleet-wide
32
+ // by bumping the string. sha256(namespace + machineId) cannot be joined back to
33
+ // the cloud device rows (those store the machineId itself).
34
+ const MACHINE_HASH_NAMESPACE = "tokenusage-telemetry-v1:";
35
+ // Generous because some networks need 3-4s just for the TLS handshake to the
36
+ // cloud host; sync awaits this at most once per day so the worst-case stall
37
+ // is bounded and rare.
38
+ const DEFAULT_TIMEOUT_MS = 10_000;
39
+ const VALID_SHELLS = new Set(["cli", "macos", "windows", "linux"]);
40
+
41
+ const THROTTLE_CONFIG = {
42
+ intervalMs: HEARTBEAT_INTERVAL_MS,
43
+ jitterMsMax: 60_000,
44
+ backoffInitialMs: 60 * 60_000, // failures retry hourly at most
45
+ backoffMaxMs: HEARTBEAT_INTERVAL_MS,
46
+ };
47
+
48
+ function isTelemetryDisabled({ env = process.env, config = {} } = {}) {
49
+ if (isTruthyFlag(env?.TOKENUSAGE_NO_TELEMETRY)) return true;
50
+ if (isTruthyFlag(env?.DO_NOT_TRACK)) return true;
51
+ if (config && config.telemetry === false) return true;
52
+ return false;
53
+ }
54
+
55
+ function isTruthyFlag(value) {
56
+ if (typeof value !== "string") return false;
57
+ const v = value.trim().toLowerCase();
58
+ return v === "1" || v === "true";
59
+ }
60
+
61
+ function hashMachineId(machineId) {
62
+ return crypto
63
+ .createHash("sha256")
64
+ .update(`${MACHINE_HASH_NAMESPACE}${machineId}`)
65
+ .digest("hex");
66
+ }
67
+
68
+ function resolveShell(env = process.env) {
69
+ const raw = typeof env?.TOKENUSAGE_APP_SHELL === "string"
70
+ ? env.TOKENUSAGE_APP_SHELL.trim().toLowerCase()
71
+ : "";
72
+ return VALID_SHELLS.has(raw) ? raw : "cli";
73
+ }
74
+
75
+ function buildHeartbeatPayload({ machineId, version = pkg.version, platform = process.platform, env = process.env }) {
76
+ return {
77
+ machine_hash: hashMachineId(machineId),
78
+ app_version: String(version || "").slice(0, 32),
79
+ platform: String(platform || "unknown").slice(0, 16),
80
+ shell: resolveShell(env),
81
+ };
82
+ }
83
+
84
+ /**
85
+ * Send the daily heartbeat if allowed. Never throws; every failure path is a
86
+ * silent no-op so serve/sync flow is never affected. Returns a small status
87
+ * object for tests and debug logging.
88
+ */
89
+ async function maybeSendHeartbeat({
90
+ trackerDir,
91
+ fetchImpl = fetch,
92
+ nowMs = Date.now(),
93
+ env = process.env,
94
+ timeoutMs = DEFAULT_TIMEOUT_MS,
95
+ version,
96
+ } = {}) {
97
+ try {
98
+ if (!trackerDir) return { sent: false, reason: "no-tracker-dir" };
99
+
100
+ // Never phone home from the node test runner: many tests drive cmdSync /
101
+ // cmdServe directly from sandboxed temp homes, and their fresh throttle
102
+ // state would let a real POST through to production on every run. Tests
103
+ // that exercise this module inject their own env without this marker.
104
+ if (env?.NODE_TEST_CONTEXT !== undefined) {
105
+ return { sent: false, reason: "test-env" };
106
+ }
107
+
108
+ const configPath = path.join(trackerDir, "config.json");
109
+ const config = (await readJson(configPath)) || {};
110
+ if (isTelemetryDisabled({ env, config })) {
111
+ return { sent: false, reason: "opt-out" };
112
+ }
113
+
114
+ const statePath = path.join(trackerDir, HEARTBEAT_STATE_FILE);
115
+ const state = await readJson(statePath);
116
+ const decision = decideAutoUpload({
117
+ nowMs,
118
+ pendingBytes: 1, // heartbeats always have "one ping pending"
119
+ state,
120
+ config: THROTTLE_CONFIG,
121
+ });
122
+ if (!decision.allowed) {
123
+ return { sent: false, reason: "throttled", blockedUntilMs: decision.blockedUntilMs };
124
+ }
125
+
126
+ const machineId = getOrCreateMachineId(path.join(trackerDir, "queue.jsonl"));
127
+ if (!machineId) return { sent: false, reason: "no-machine-id" };
128
+
129
+ const runtime = resolveRuntimeConfig({ config, env });
130
+ const payload = buildHeartbeatPayload({ machineId, version, env });
131
+
132
+ const controller = new AbortController();
133
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
134
+ let response;
135
+ try {
136
+ response = await fetchFunctionResponse(functionUrlFor(runtime.baseUrl, HEARTBEAT_FUNCTION_SLUG), {
137
+ method: "POST",
138
+ headers: {
139
+ "Content-Type": "application/json",
140
+ apikey: runtime.anonKey,
141
+ },
142
+ body: JSON.stringify(payload),
143
+ signal: controller.signal,
144
+ }, fetchImpl);
145
+ } finally {
146
+ clearTimeout(timer);
147
+ }
148
+
149
+ if (!response || !response.ok) {
150
+ const failedState = recordUploadFailure({
151
+ nowMs,
152
+ state,
153
+ error: { message: `heartbeat http ${response?.status || "error"}`, status: response?.status },
154
+ config: THROTTLE_CONFIG,
155
+ });
156
+ await writeJson(statePath, failedState);
157
+ return { sent: false, reason: "http-error", status: response?.status };
158
+ }
159
+
160
+ const nextState = recordUploadSuccess({ nowMs, state, config: THROTTLE_CONFIG });
161
+ await writeJson(statePath, nextState);
162
+ return { sent: true, reason: "sent" };
163
+ } catch (e) {
164
+ // Includes abort/network errors: record backoff if we can, stay silent.
165
+ try {
166
+ const statePath = path.join(trackerDir, HEARTBEAT_STATE_FILE);
167
+ const state = await readJson(statePath);
168
+ await writeJson(
169
+ statePath,
170
+ recordUploadFailure({
171
+ nowMs,
172
+ state,
173
+ error: { message: String(e?.message || e) },
174
+ config: THROTTLE_CONFIG,
175
+ }),
176
+ );
177
+ } catch {
178
+ // Even state persistence failed — nothing else to do.
179
+ }
180
+ return { sent: false, reason: "error" };
181
+ }
182
+ }
183
+
184
+ module.exports = {
185
+ HEARTBEAT_FUNCTION_SLUG,
186
+ HEARTBEAT_STATE_FILE,
187
+ HEARTBEAT_INTERVAL_MS,
188
+ isTelemetryDisabled,
189
+ hashMachineId,
190
+ resolveShell,
191
+ buildHeartbeatPayload,
192
+ maybeSendHeartbeat,
193
+ };
@@ -1,16 +1,16 @@
1
- const os = require("node:os");
2
- const path = require("node:path");
3
-
4
- async function resolveTrackerPaths({ home = os.homedir() } = {}) {
5
- const rootDir = path.join(home, ".tokenusage");
6
- return {
7
- rootDir,
8
- trackerDir: path.join(rootDir, "tracker"),
9
- binDir: path.join(rootDir, "bin"),
10
- cacheDir: path.join(rootDir, "cache"),
11
- };
12
- }
13
-
14
- module.exports = {
15
- resolveTrackerPaths,
16
- };
1
+ const os = require("node:os");
2
+ const path = require("node:path");
3
+
4
+ async function resolveTrackerPaths({ home = os.homedir() } = {}) {
5
+ const rootDir = path.join(home, ".tokenusage");
6
+ return {
7
+ rootDir,
8
+ trackerDir: path.join(rootDir, "tracker"),
9
+ binDir: path.join(rootDir, "bin"),
10
+ cacheDir: path.join(rootDir, "cache"),
11
+ };
12
+ }
13
+
14
+ module.exports = {
15
+ resolveTrackerPaths,
16
+ };