tokenusage-cli 0.1.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 (125) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/LICENSE +22 -0
  3. package/README.md +94 -0
  4. package/THIRD_PARTY_NOTICES.md +140 -0
  5. package/bin/tokenusage.js +69 -0
  6. package/package.json +59 -0
  7. package/src/cli.js +134 -0
  8. package/src/commands/device-login.js +205 -0
  9. package/src/commands/diagnostics.js +38 -0
  10. package/src/commands/doctor.js +110 -0
  11. package/src/commands/init.js +2436 -0
  12. package/src/commands/sessions.js +29 -0
  13. package/src/commands/status.js +1747 -0
  14. package/src/commands/sync.js +7934 -0
  15. package/src/commands/uninstall.js +312 -0
  16. package/src/lib/account-usage-dedup.js +267 -0
  17. package/src/lib/antigravity-paths.js +48 -0
  18. package/src/lib/ark-agent-plan-limits.js +438 -0
  19. package/src/lib/ark-coding-plan-limits.js +537 -0
  20. package/src/lib/async-queue-reader.js +138 -0
  21. package/src/lib/atomic-json.js +27 -0
  22. package/src/lib/bearer-token.js +11 -0
  23. package/src/lib/categorizer-utils.js +232 -0
  24. package/src/lib/claude-categorizer.js +1343 -0
  25. package/src/lib/claude-config.js +279 -0
  26. package/src/lib/claude-user-identity.js +56 -0
  27. package/src/lib/cli-ui.js +179 -0
  28. package/src/lib/cloud-account.js +541 -0
  29. package/src/lib/cloud-device-token.js +141 -0
  30. package/src/lib/cloud-sync-prefs.js +14 -0
  31. package/src/lib/cloud-usage-reset.js +115 -0
  32. package/src/lib/codex-config.js +595 -0
  33. package/src/lib/codex-context-breakdown.js +806 -0
  34. package/src/lib/codex-model-attribution.js +128 -0
  35. package/src/lib/codex-rollout-parser.js +1471 -0
  36. package/src/lib/codex-service-tier.js +49 -0
  37. package/src/lib/codex-token-refresh.js +140 -0
  38. package/src/lib/codex-token-usage.js +195 -0
  39. package/src/lib/codex-usage-record.js +195 -0
  40. package/src/lib/command-runner.js +313 -0
  41. package/src/lib/commandcode-limits.js +317 -0
  42. package/src/lib/context-health.js +124 -0
  43. package/src/lib/cursor-config.js +605 -0
  44. package/src/lib/cursor-store.js +1918 -0
  45. package/src/lib/debug-flags.js +7 -0
  46. package/src/lib/devin-limits.js +249 -0
  47. package/src/lib/devin-usage.js +212 -0
  48. package/src/lib/diagnostics.js +383 -0
  49. package/src/lib/doctor.js +385 -0
  50. package/src/lib/dumate.js +95 -0
  51. package/src/lib/fs.js +455 -0
  52. package/src/lib/function-url.js +14 -0
  53. package/src/lib/gemini-config.js +291 -0
  54. package/src/lib/git-outcomes.js +243 -0
  55. package/src/lib/grok-context-breakdown.js +890 -0
  56. package/src/lib/grok-hook.js +360 -0
  57. package/src/lib/grok-limits.js +865 -0
  58. package/src/lib/grok-usage.js +98 -0
  59. package/src/lib/heatmap-compact.js +114 -0
  60. package/src/lib/ingest-sanitize.js +41 -0
  61. package/src/lib/init-flow.js +42 -0
  62. package/src/lib/install-resolver.js +170 -0
  63. package/src/lib/jsonl-lines.js +134 -0
  64. package/src/lib/kimi-model-repair.js +173 -0
  65. package/src/lib/kimi-profile.js +61 -0
  66. package/src/lib/kimi-session.js +216 -0
  67. package/src/lib/local-api.js +3588 -0
  68. package/src/lib/machine-id.js +238 -0
  69. package/src/lib/multi-install-parser.js +113 -0
  70. package/src/lib/notify-command.js +38 -0
  71. package/src/lib/omp-hook.js +589 -0
  72. package/src/lib/openclaw-cli.js +104 -0
  73. package/src/lib/openclaw-hook.js +375 -0
  74. package/src/lib/openclaw-session-plugin.js +560 -0
  75. package/src/lib/opencode-config.js +121 -0
  76. package/src/lib/opencode-go-limits.js +807 -0
  77. package/src/lib/outcomes-engine.js +253 -0
  78. package/src/lib/passive-mode.js +219 -0
  79. package/src/lib/pet-packages.js +722 -0
  80. package/src/lib/pricing/curated-overrides.json +822 -0
  81. package/src/lib/pricing/index.js +379 -0
  82. package/src/lib/pricing/litellm-fetcher.js +172 -0
  83. package/src/lib/pricing/matcher.js +456 -0
  84. package/src/lib/pricing/seed-snapshot.json +1 -0
  85. package/src/lib/progress.js +76 -0
  86. package/src/lib/project-usage-purge.js +117 -0
  87. package/src/lib/prompt.js +24 -0
  88. package/src/lib/provider-status.js +104 -0
  89. package/src/lib/proxy-env.js +489 -0
  90. package/src/lib/proxy-settings.js +163 -0
  91. package/src/lib/qoder-cn-cli-limits.js +119 -0
  92. package/src/lib/qoder-limits.js +880 -0
  93. package/src/lib/quiet-warnings.js +26 -0
  94. package/src/lib/rollout.js +25966 -0
  95. package/src/lib/runtime-config.js +259 -0
  96. package/src/lib/scan-roots.js +277 -0
  97. package/src/lib/sentry.js +231 -0
  98. package/src/lib/session-analytics.js +2972 -0
  99. package/src/lib/session-performance.js +237 -0
  100. package/src/lib/session-upload.js +379 -0
  101. package/src/lib/skill-usage.js +267 -0
  102. package/src/lib/skills-manager.js +1591 -0
  103. package/src/lib/source-metadata.js +48 -0
  104. package/src/lib/sqlite-reader.js +215 -0
  105. package/src/lib/star-cta.js +73 -0
  106. package/src/lib/subscription-manager.js +293 -0
  107. package/src/lib/subscriptions.js +508 -0
  108. package/src/lib/telemetry.js +193 -0
  109. package/src/lib/tracker-paths.js +16 -0
  110. package/src/lib/trae-cn-config.js +548 -0
  111. package/src/lib/trae-db.js +127 -0
  112. package/src/lib/trae-snapshot.js +230 -0
  113. package/src/lib/trae-sqlite.js +143 -0
  114. package/src/lib/trae-usage.js +121 -0
  115. package/src/lib/upload-queue.js +134 -0
  116. package/src/lib/upload-throttle.js +171 -0
  117. package/src/lib/usage-limits.js +4552 -0
  118. package/src/lib/wrapped-aggregator.js +236 -0
  119. package/src/lib/wsl-probe.js +281 -0
  120. package/src/lib/zcode-limits.js +1172 -0
  121. package/src/lib/zcode-reset-credits.js +66 -0
  122. package/test/cli-smoke.test.js +53 -0
  123. package/test/ingest-sanitize.test.js +162 -0
  124. package/test/quiet-warnings.test.js +53 -0
  125. package/test/session-upload.test.js +427 -0
@@ -0,0 +1,259 @@
1
+ // token-usage production deployment (operator-approved 2026-10-25,
2
+ // docs/rewrite-plan.md §1#19). Override per invocation with --base-url or
3
+ // TOKENUSAGE_BASE_URL.
4
+ const DEFAULT_BASE_URL = "https://token-usage.baiwumm.com";
5
+ // Retired hosts from the upstream (InsForge) era; a persisted config pointing
6
+ // at one of these must fall back to the current default instead of uploading
7
+ // into a dead backend.
8
+ const LEGACY_INSFORGE_HOSTS = new Set([
9
+ "b46ug8xu.us-east.insforge.app",
10
+ "srctyff5.us-east.insforge.app",
11
+ ]);
12
+ // The pre-GA Vercel deployment; installs pinned to it during acceptance move
13
+ // to the production domain like every other host change.
14
+ const LEGACY_TOKEN_USAGE_HOSTS = new Set(["token-usage-delta.vercel.app"]);
15
+ const DEFAULT_DASHBOARD_URL = DEFAULT_BASE_URL;
16
+ const DEFAULT_HTTP_TIMEOUT_MS = 20_000;
17
+ // Public InsForge anon key (JWT, role=anon). Mirrors dashboard/src/lib/insforge-config.ts
18
+ // (PROD_INSFORGE_ANON_KEY) — public by design (ships in the browser bundle and
19
+ // appears in .github/workflows/*.yml). The local server needs it to call the
20
+ // cross-device `token-usage-account-*` edge functions on the popover's behalf.
21
+ // (Previously this mistakenly used the full-access `ik_*` API key, which has
22
+ // admin access and must never be shipped to clients.)
23
+ // token-usage's Supabase publishable key — public by design (ships in the
24
+ // web app's browser bundle; RLS zero-policy on token_* tables means it grants
25
+ // nothing without the service-role key on the server).
26
+ const DEFAULT_ANON_KEY = "sb_publishable_Sym9xClyNRvjxqtj74gF4Q_owoDy3px";
27
+
28
+ function resolveRuntimeConfig({ cli = {}, config = {}, env = process.env, defaults = {} } = {}) {
29
+ // Older Windows test runs could leak their fixture HOME and persist
30
+ // https://example.invalid into the user's real config.json. The test
31
+ // isolation bug is fixed, but existing installs must recover instead of
32
+ // backing off cloud uploads forever against the reserved placeholder host.
33
+ const persistedBaseUrl = normalizePersistedBaseUrl(config.baseUrl);
34
+ const baseUrl = pickString(
35
+ cli.baseUrl,
36
+ persistedBaseUrl,
37
+ env?.TOKENUSAGE_INSFORGE_BASE_URL,
38
+ defaults.baseUrl,
39
+ DEFAULT_BASE_URL,
40
+ );
41
+ const selectedBase = normalizeInstanceBaseUrl(baseUrl.value);
42
+ const configBase = normalizeInstanceBaseUrl(persistedBaseUrl || DEFAULT_BASE_URL);
43
+ const envBase = normalizeInstanceBaseUrl(env?.TOKENUSAGE_INSFORGE_BASE_URL || baseUrl.value);
44
+ const defaultBase = normalizeInstanceBaseUrl(defaults.baseUrl || DEFAULT_BASE_URL);
45
+ const custom = selectedBase !== DEFAULT_BASE_URL;
46
+ const anonKey = pickString(
47
+ cli.anonKey,
48
+ configBase === selectedBase ? config.anonKey : undefined,
49
+ envBase === selectedBase ? env?.TOKENUSAGE_INSFORGE_ANON_KEY : undefined,
50
+ defaultBase === selectedBase ? defaults.anonKey : undefined,
51
+ custom ? null : DEFAULT_ANON_KEY,
52
+ );
53
+ const dashboardUrl = pickString(
54
+ cli.dashboardUrl,
55
+ configBase === selectedBase ? config.dashboardUrl : undefined,
56
+ envBase === selectedBase ? env?.TOKENUSAGE_DASHBOARD_URL : undefined,
57
+ defaultBase === selectedBase ? defaults.dashboardUrl : undefined,
58
+ custom ? baseUrl.value : DEFAULT_DASHBOARD_URL,
59
+ );
60
+ const deviceToken = pickString(
61
+ cli.deviceToken,
62
+ configBase === selectedBase && (!custom || normalizeInstanceBaseUrl(config.deviceTokenBaseUrl) === selectedBase)
63
+ ? config.deviceToken : undefined,
64
+ envBase === selectedBase && (!custom || normalizeInstanceBaseUrl(env?.TOKENUSAGE_INSFORGE_BASE_URL) === selectedBase)
65
+ ? env?.TOKENUSAGE_DEVICE_TOKEN : undefined,
66
+ defaultBase === selectedBase ? defaults.deviceToken : undefined,
67
+ null,
68
+ );
69
+ const httpTimeoutMs = pickHttpTimeoutMs(
70
+ cli.httpTimeoutMs,
71
+ config.httpTimeoutMs,
72
+ env?.TOKENUSAGE_HTTP_TIMEOUT_MS,
73
+ defaults.httpTimeoutMs,
74
+ DEFAULT_HTTP_TIMEOUT_MS,
75
+ );
76
+ const debug = pickBoolean(cli.debug, config.debug, env?.TOKENUSAGE_DEBUG, defaults.debug, false);
77
+ const autoRetryNoSpawn = pickBoolean(
78
+ cli.autoRetryNoSpawn,
79
+ config.autoRetryNoSpawn,
80
+ env?.TOKENUSAGE_AUTO_RETRY_NO_SPAWN,
81
+ defaults.autoRetryNoSpawn,
82
+ false,
83
+ );
84
+
85
+ const unsafeKey = anonKey.value && (!isPublicAnonKey(anonKey.value) || (custom && anonKey.value === DEFAULT_ANON_KEY));
86
+ const configurationError = !selectedBase ? "invalid_insforge_base_url"
87
+ : !normalizeInstanceBaseUrl(dashboardUrl.value) ? "invalid_dashboard_url"
88
+ : unsafeKey ? "invalid_insforge_anon_key"
89
+ : custom && !anonKey.value ? "custom_insforge_anon_key_required" : null;
90
+ return {
91
+ baseUrl: selectedBase || baseUrl.value,
92
+ anonKey: unsafeKey ? null : anonKey.value,
93
+ dashboardUrl: dashboardUrl.value,
94
+ deviceToken: configurationError ? null : deviceToken.value,
95
+ httpTimeoutMs: httpTimeoutMs.value,
96
+ debug: debug.value,
97
+ autoRetryNoSpawn: autoRetryNoSpawn.value,
98
+ configurationError,
99
+ sources: {
100
+ baseUrl: baseUrl.source,
101
+ anonKey: anonKey.source,
102
+ dashboardUrl: dashboardUrl.source,
103
+ deviceToken: deviceToken.source,
104
+ httpTimeoutMs: httpTimeoutMs.source,
105
+ debug: debug.source,
106
+ autoRetryNoSpawn: autoRetryNoSpawn.source,
107
+ },
108
+ };
109
+ }
110
+
111
+ function normalizeInstanceBaseUrl(value) {
112
+ try {
113
+ const url = new URL(String(value || ""));
114
+ const loopback = ["localhost", "127.0.0.1", "::1", "[::1]"].includes(url.hostname);
115
+ if (url.username || url.password || url.search || url.hash ||
116
+ (url.protocol !== "https:" && !(url.protocol === "http:" && loopback))) return null;
117
+ return url.toString().replace(/\/$/, "");
118
+ } catch { return null; }
119
+ }
120
+
121
+ function isPublicAnonKey(value) {
122
+ try {
123
+ if (typeof value !== "string") return false;
124
+ const key = value.trim();
125
+ if (key.startsWith("ik_")) return false;
126
+ if (/^anon_(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(key)) return true;
127
+ // Supabase's new publishable key format (sb_publishable_...).
128
+ if (/^sb_publishable_[A-Za-z0-9_-]{20,}$/.test(key)) return true;
129
+ const parts = key.split(".");
130
+ if (parts.length !== 3 || !parts.every(part => /^[A-Za-z0-9_-]+$/.test(part))) return false;
131
+ return JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8")).role === "anon";
132
+ } catch { return false; }
133
+ }
134
+
135
+ function assertInsforgeRuntime(runtime) {
136
+ if (!runtime?.configurationError) return runtime;
137
+ const messages = {
138
+ invalid_insforge_base_url: "InsForge URL must use HTTPS, or HTTP on localhost, without credentials, query or fragment.",
139
+ invalid_insforge_anon_key: "Use this instance's public anon key. Admin and service keys cannot be used by the client.",
140
+ invalid_dashboard_url: "Dashboard URL must use HTTPS, or HTTP on localhost, without credentials, query or fragment.",
141
+ custom_insforge_anon_key_required: "A custom InsForge URL requires its own public anon key. Configure --anon-key-file or TOKENUSAGE_INSFORGE_ANON_KEY.",
142
+ };
143
+ throw Object.assign(new Error(messages[runtime.configurationError] || "Invalid InsForge configuration"), {
144
+ code: runtime.configurationError, status: 503,
145
+ });
146
+ }
147
+
148
+ function clearDeviceIdentity(config) {
149
+ const next = { ...config };
150
+ for (const key of ["deviceToken", "deviceTokenBaseUrl", "deviceId", "user_id", "device_login_at"]) delete next[key];
151
+ return next;
152
+ }
153
+
154
+ function resetInstanceState(trackerDir) {
155
+ const fs = require("node:fs");
156
+ const path = require("node:path");
157
+ fs.mkdirSync(trackerDir, { recursive: true });
158
+ fs.writeFileSync(path.join(trackerDir, "queue.state.json"), JSON.stringify({ offset: 0, updatedAt: new Date().toISOString() }), { mode: 0o600 });
159
+ for (const file of ["relay-cookies.json", "cloud-device-token.json", "cloud-upload-owner.json", "upload.throttle.json", "link_code_state.json"]) {
160
+ try { fs.unlinkSync(path.join(trackerDir, file)); }
161
+ catch (error) { if (error.code !== "ENOENT") throw error; }
162
+ }
163
+ }
164
+
165
+ function pickString(...candidates) {
166
+ return pickValue(candidates, normalizeString);
167
+ }
168
+
169
+ function pickBoolean(...candidates) {
170
+ return pickValue(candidates, normalizeBoolean);
171
+ }
172
+
173
+ function pickHttpTimeoutMs(...candidates) {
174
+ return pickValue(candidates, normalizeHttpTimeoutMs);
175
+ }
176
+
177
+ function pickValue(candidates, normalize) {
178
+ const labels = ["cli", "config", "env", "default", "default"];
179
+ for (let i = 0; i < candidates.length; i += 1) {
180
+ const value = normalize(candidates[i]);
181
+ if (value !== undefined) {
182
+ return { value, source: labels[i] || "default" };
183
+ }
184
+ }
185
+ return { value: null, source: "default" };
186
+ }
187
+
188
+ function normalizeString(value) {
189
+ if (typeof value !== "string") return undefined;
190
+ const trimmed = value.trim();
191
+ if (!trimmed) return undefined;
192
+ return trimmed;
193
+ }
194
+
195
+ function normalizePersistedBaseUrl(value) {
196
+ const normalized = normalizeString(value);
197
+ if (normalized === undefined) return undefined;
198
+ try {
199
+ const hostname = new URL(normalized).hostname.toLowerCase();
200
+ if (hostname === "example.invalid") return undefined;
201
+ if (LEGACY_INSFORGE_HOSTS.has(hostname)) return undefined;
202
+ if (LEGACY_TOKEN_USAGE_HOSTS.has(hostname)) return undefined;
203
+ } catch {
204
+ // Preserve the existing resolver behavior for arbitrary custom values.
205
+ }
206
+ return normalized;
207
+ }
208
+
209
+ // True when the value points at a retired InsForge project (dead backend).
210
+ // Callers use this to trigger the one-time config repair in sync.
211
+ function isLegacyInsforgeBaseUrl(value) {
212
+ const normalized = normalizeString(value);
213
+ if (normalized === undefined) return false;
214
+ try {
215
+ return LEGACY_INSFORGE_HOSTS.has(new URL(normalized).hostname.toLowerCase());
216
+ } catch {
217
+ return false;
218
+ }
219
+ }
220
+
221
+ function normalizeBoolean(value) {
222
+ if (typeof value === "boolean") return value;
223
+ if (typeof value === "number") return value !== 0;
224
+ if (typeof value === "string") {
225
+ const trimmed = value.trim().toLowerCase();
226
+ if (!trimmed) return undefined;
227
+ if (trimmed === "1" || trimmed === "true") return true;
228
+ if (trimmed === "0" || trimmed === "false") return false;
229
+ }
230
+ return undefined;
231
+ }
232
+
233
+ function normalizeHttpTimeoutMs(value) {
234
+ if (value == null || value === "") return undefined;
235
+ const n = Number(value);
236
+ if (!Number.isFinite(n)) return undefined;
237
+ if (n <= 0) return 0;
238
+ return clampInt(n, 1000, 120_000);
239
+ }
240
+
241
+ function clampInt(value, min, max) {
242
+ const n = Number(value);
243
+ if (!Number.isFinite(n)) return min;
244
+ return Math.min(max, Math.max(min, Math.floor(n)));
245
+ }
246
+
247
+ module.exports = {
248
+ DEFAULT_BASE_URL,
249
+ DEFAULT_ANON_KEY,
250
+ DEFAULT_DASHBOARD_URL,
251
+ DEFAULT_HTTP_TIMEOUT_MS,
252
+ resolveRuntimeConfig,
253
+ isLegacyInsforgeBaseUrl,
254
+ normalizeInstanceBaseUrl,
255
+ isPublicAnonKey,
256
+ assertInsforgeRuntime,
257
+ clearDeviceIdentity,
258
+ resetInstanceState,
259
+ };
@@ -0,0 +1,277 @@
1
+ "use strict";
2
+
3
+ // Persistent extra scan roots for Codex and Claude Code (#657).
4
+ //
5
+ // Agent harnesses run Codex / Claude Code with a private home
6
+ // (CODEX_HOME=..., CLAUDE_CONFIG_DIR=...). Those sessions were invisible to
7
+ // Token Usage unless the sync happened to be spawned by a process that
8
+ // inherited the same environment: a hook-fired sync saw them, the native app's
9
+ // background refresh did not. Worse, the two producers then disagreed about
10
+ // where a rollout's cursor lives (the cursor store classifies a rollout as a
11
+ // Codex path — per-day shard — only when it sits under one of ITS codexRoots,
12
+ // everything else goes to core), never saw each other's cursor, and re-parsed
13
+ // the same file from byte 0 on every alternation (#639: one 30-minute bucket
14
+ // re-emitted 138 times, 59B tokens for a 1.2B day).
15
+ //
16
+ // So roots come from ONE persistent list that every producer reads, and the
17
+ // cursor store's codexRoots are derived from that same list.
18
+ //
19
+ // Per provider, in order (first occurrence wins; later duplicates by realpath
20
+ // are dropped):
21
+ // 1. the roots the caller already scans (native home, WSL install)
22
+ // 2. the spawning process's implicit root — CODEX_HOME / CLAUDE_CONFIG_DIR
23
+ // 3. config.scanRoots.<provider>[] from ~/.tokenusage/tracker/config.json
24
+ //
25
+ // Config shape:
26
+ // { "scanRoots": { "codex": ["~/.local/share/agent/codex"],
27
+ // "claude": ["~/.local/share/agent/claude", "~/.claude-native"] } }
28
+
29
+ const fs = require("node:fs");
30
+ const os = require("node:os");
31
+ const path = require("node:path");
32
+
33
+ const { readJson } = require("./fs");
34
+ const { resolveTrackerPaths } = require("./tracker-paths");
35
+
36
+ const PROVIDERS = Object.freeze({
37
+ codex: Object.freeze({ envVar: "CODEX_HOME" }),
38
+ claude: Object.freeze({ envVar: "CLAUDE_CONFIG_DIR" }),
39
+ });
40
+ const PROVIDER_NAMES = Object.freeze(Object.keys(PROVIDERS));
41
+
42
+ // Turn a configured root into a stable absolute path. `~` expands against
43
+ // `home`, and a RELATIVE entry is resolved against `home` too — never against
44
+ // process.cwd(), which differs between a hook-fired sync, the CLI and the
45
+ // desktop app and would make producers scan different directories.
46
+ function expandHome(value, home) {
47
+ if (typeof value !== "string") return null;
48
+ const trimmed = value.trim();
49
+ if (!trimmed) return null;
50
+ if (trimmed === "~") return path.resolve(home);
51
+ if (trimmed.startsWith("~/") || trimmed.startsWith("~\\")) {
52
+ return path.resolve(home, trimmed.slice(2));
53
+ }
54
+ return path.isAbsolute(trimmed) ? path.resolve(trimmed) : path.resolve(home, trimmed);
55
+ }
56
+
57
+ // The spawning process's implicit root — CODEX_HOME / CLAUDE_CONFIG_DIR —
58
+ // normalized ONCE, the same way configured entries are: `~` and relative
59
+ // values are anchored to `home`, never to process.cwd(). Every producer
60
+ // (sync discovery, the cursor store's codexRoots, status, diagnostics, the
61
+ // session browser) must use this value, or a relative CODEX_HOME such as
62
+ // `profiles/codex` is scanned under one directory and cursor-classified
63
+ // under another, and the same rollout replays. Returns null when unset.
64
+ function resolveEnvRoot(provider, { env = process.env, home = os.homedir() } = {}) {
65
+ const spec = PROVIDERS[provider];
66
+ if (!spec) return null;
67
+ const raw = env && typeof env[spec.envVar] === "string" ? env[spec.envVar] : "";
68
+ return expandHome(raw, home);
69
+ }
70
+
71
+ // Accepts { codex: string | string[], claude: string | string[] }. Anything
72
+ // else — wrong type, empty strings, unknown providers — is ignored rather than
73
+ // failing the sync: a malformed config must not stop collection.
74
+ function normalizeScanRootsConfig(raw) {
75
+ const out = {};
76
+ for (const provider of PROVIDER_NAMES) out[provider] = [];
77
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return out;
78
+ for (const provider of PROVIDER_NAMES) {
79
+ const value = raw[provider];
80
+ const list = Array.isArray(value) ? value : (typeof value === "string" ? [value] : []);
81
+ for (const entry of list) {
82
+ if (typeof entry !== "string" || !entry.trim()) continue;
83
+ out[provider].push(entry.trim());
84
+ }
85
+ }
86
+ return out;
87
+ }
88
+
89
+ // { exists, error }: `exists` is true only for a directory that can be
90
+ // LISTED, not merely stat'ed — a stat-able directory whose listing fails
91
+ // (mode 000, ACL) would otherwise be admitted to the scan, yield no files,
92
+ // read as "present" in status/doctor, and slip past the deferred-repair
93
+ // guard in sync. ENOENT and ENOTDIR (or a regular file in a directory's
94
+ // place) mean the root is absent (error null); any other failure (EACCES,
95
+ // ELOOP, EIO, ...) is reported as `error` so callers can say "unreadable"
96
+ // instead of "missing".
97
+ function scanRootDirState(target, deps = {}) {
98
+ const statSync = deps.statSync || fs.statSync;
99
+ const opendirSync = deps.opendirSync || fs.opendirSync;
100
+ try {
101
+ if (!statSync(target).isDirectory()) return { exists: false, error: null };
102
+ // Probe listability without reading entries; large roots stay cheap.
103
+ opendirSync(target).closeSync();
104
+ return { exists: true, error: null };
105
+ } catch (e) {
106
+ const code = e && typeof e.code === "string" ? e.code : "EUNKNOWN";
107
+ if (code === "ENOENT" || code === "ENOTDIR") return { exists: false, error: null };
108
+ return { exists: false, error: code };
109
+ }
110
+ }
111
+
112
+ function isDirectorySync(target, deps) {
113
+ return scanRootDirState(target, deps).exists;
114
+ }
115
+
116
+ function realpathOrSelf(target, deps) {
117
+ const realpathSync = deps.realpathSync || fs.realpathSync;
118
+ try {
119
+ return realpathSync(target);
120
+ } catch {
121
+ return target;
122
+ }
123
+ }
124
+
125
+ function identityKey(target, deps) {
126
+ const resolved = path.resolve(target);
127
+ const real = realpathOrSelf(resolved, deps);
128
+ return real.replace(/\\/g, "/").replace(/\/+$/, "");
129
+ }
130
+
131
+ // Drop later entries that resolve (realpath) to a directory already listed.
132
+ // Used at the projects/ level too: two Claude profiles may symlink one
133
+ // projects/ dir, and reading it under both spellings would double-parse every
134
+ // file, leaving correctness to the bounded claudeHashes layer.
135
+ function dedupeDirsByRealpath(dirs, deps = {}) {
136
+ const seen = new Set();
137
+ const out = [];
138
+ for (const dir of Array.isArray(dirs) ? dirs : []) {
139
+ if (typeof dir !== "string" || !dir) continue;
140
+ const key = identityKey(dir, deps);
141
+ if (seen.has(key)) continue;
142
+ seen.add(key);
143
+ out.push(dir);
144
+ }
145
+ return out;
146
+ }
147
+
148
+ // Resolve the full, ordered, deduplicated root list per provider.
149
+ //
150
+ // base: { codex: string[], claude: string[] } — roots the caller scans
151
+ // anyway (native home, WSL install); they keep their position and
152
+ // are labelled origin "native".
153
+ // env: CODEX_HOME / CLAUDE_CONFIG_DIR become origin "env" unless already
154
+ // covered by base.
155
+ // config.scanRoots.<provider>[] become origin "config".
156
+ //
157
+ // Every entry: { path, realPath, exists, error, origin }. `exists` is a
158
+ // readable-directory check and `error` carries a stat error code other than
159
+ // absence (see scanRootDirState); non-existent or unreadable configured roots
160
+ // are kept in the list (so cursor-path classification stays stable while a
161
+ // volume is unmounted) and callers that walk directories skip them via
162
+ // `exists`.
163
+ function resolveScanRoots({
164
+ home = os.homedir(),
165
+ env = process.env,
166
+ config = null,
167
+ base = {},
168
+ deps = {},
169
+ } = {}) {
170
+ const configured = normalizeScanRootsConfig(config && typeof config === "object" ? config.scanRoots : null);
171
+ const out = {};
172
+ for (const provider of PROVIDER_NAMES) {
173
+ const candidates = [];
174
+ for (const root of Array.isArray(base[provider]) ? base[provider] : []) {
175
+ if (typeof root === "string" && root.trim()) candidates.push({ raw: root, origin: "native" });
176
+ }
177
+ const envRoot = resolveEnvRoot(provider, { env, home });
178
+ if (envRoot) candidates.push({ raw: envRoot, origin: "env" });
179
+ for (const root of configured[provider]) candidates.push({ raw: root, origin: "config" });
180
+
181
+ const seen = new Set();
182
+ const entries = [];
183
+ for (const candidate of candidates) {
184
+ const expanded = expandHome(candidate.raw, home);
185
+ if (!expanded) continue;
186
+ const resolved = expanded;
187
+ const key = identityKey(resolved, deps);
188
+ if (seen.has(key)) continue;
189
+ seen.add(key);
190
+ const state = scanRootDirState(resolved, deps);
191
+ entries.push({
192
+ path: resolved,
193
+ realPath: realpathOrSelf(resolved, deps),
194
+ exists: state.exists,
195
+ error: state.error,
196
+ origin: candidate.origin,
197
+ });
198
+ }
199
+ out[provider] = entries;
200
+ }
201
+ return out;
202
+ }
203
+
204
+ // Append `extraDirs` to `baseDirs`, dropping any extra that resolves (realpath)
205
+ // to a directory already present. Base entries are never collapsed against
206
+ // each other: the native + WSL pair is listed on purpose (see sync.js) and
207
+ // their dedup is handled downstream by file-identity hashes.
208
+ function appendUniqueDirs(baseDirs, extraDirs, deps = {}) {
209
+ const out = [];
210
+ const seen = new Set();
211
+ for (const dir of Array.isArray(baseDirs) ? baseDirs : []) {
212
+ if (typeof dir !== "string" || !dir) continue;
213
+ seen.add(identityKey(dir, deps));
214
+ out.push(dir);
215
+ }
216
+ for (const dir of Array.isArray(extraDirs) ? extraDirs : []) {
217
+ if (typeof dir !== "string" || !dir) continue;
218
+ const key = identityKey(dir, deps);
219
+ if (seen.has(key)) continue;
220
+ seen.add(key);
221
+ out.push(dir);
222
+ }
223
+ return out;
224
+ }
225
+
226
+ // Roots beyond what the caller already scans: the "env" and "config" entries
227
+ // that exist on disk. Paths only, in list order.
228
+ function extraScanRootPaths(entries) {
229
+ return (Array.isArray(entries) ? entries : [])
230
+ .filter((entry) => entry && entry.origin !== "native" && entry.exists)
231
+ .map((entry) => entry.path);
232
+ }
233
+
234
+ function hasAnyScanChild(root, children, deps = {}) {
235
+ for (const child of Array.isArray(children) ? children : [children]) {
236
+ if (isDirectorySync(path.join(root, child), deps)) return true;
237
+ }
238
+ return false;
239
+ }
240
+
241
+ // Human label for status / doctor output.
242
+ function describeScanRootOrigin(entry, provider) {
243
+ if (!entry || entry.origin === "native") return "native";
244
+ if (entry.origin === "env") return PROVIDERS[provider]?.envVar || "env";
245
+ return "scanRoots";
246
+ }
247
+
248
+ // "" for a readable root, " (missing)" for an absent one, " (unreadable: CODE)"
249
+ // for a stat failure other than absence.
250
+ function describeScanRootState(entry) {
251
+ if (!entry || entry.exists) return "";
252
+ return entry.error ? ` (unreadable: ${entry.error})` : " (missing)";
253
+ }
254
+
255
+ // config.scanRoots as persisted in ~/.tokenusage/tracker/config.json for
256
+ // callers that do not already hold the config (the session browser).
257
+ async function loadScanRootsConfig({ home = os.homedir() } = {}) {
258
+ const { trackerDir } = await resolveTrackerPaths({ home });
259
+ const config = await readJson(path.join(trackerDir, "config.json")).catch(() => null);
260
+ return normalizeScanRootsConfig(config && typeof config === "object" ? config.scanRoots : null);
261
+ }
262
+
263
+ module.exports = {
264
+ PROVIDER_NAMES,
265
+ appendUniqueDirs,
266
+ dedupeDirsByRealpath,
267
+ describeScanRootOrigin,
268
+ describeScanRootState,
269
+ expandHome,
270
+ extraScanRootPaths,
271
+ hasAnyScanChild,
272
+ loadScanRootsConfig,
273
+ normalizeScanRootsConfig,
274
+ resolveEnvRoot,
275
+ resolveScanRoots,
276
+ scanRootDirState,
277
+ };