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,48 @@
1
+ const ACCOUNT_LEVEL_SOURCES = new Set(["cursor", "trae-cn"]);
2
+
3
+ function normalizeSource(value) {
4
+ return String(value || "").trim().toLowerCase();
5
+ }
6
+
7
+ function getSourceScope(source) {
8
+ return ACCOUNT_LEVEL_SOURCES.has(normalizeSource(source)) ? "account" : "local";
9
+ }
10
+
11
+ function isAccountLevelSource(source) {
12
+ return getSourceScope(source) === "account";
13
+ }
14
+
15
+ function normalizeUsageScope(value) {
16
+ const raw = String(value || "").trim().toLowerCase();
17
+ if (!raw || raw === "all" || raw === "raw") return "all";
18
+ if (raw === "personal" || raw === "local") return "personal";
19
+ return "all";
20
+ }
21
+
22
+ function filterRowsByUsageScope(rows, scope = "all") {
23
+ const normalizedScope = normalizeUsageScope(scope);
24
+ if (normalizedScope === "all") return Array.isArray(rows) ? rows : [];
25
+ return (Array.isArray(rows) ? rows : []).filter((row) => !isAccountLevelSource(row?.source));
26
+ }
27
+
28
+ function listExcludedSources(rows, scope = "all") {
29
+ const normalizedScope = normalizeUsageScope(scope);
30
+ if (normalizedScope === "all") return [];
31
+ const seen = new Set();
32
+ const out = [];
33
+ for (const row of Array.isArray(rows) ? rows : []) {
34
+ const source = normalizeSource(row?.source);
35
+ if (!source || seen.has(source) || !isAccountLevelSource(source)) continue;
36
+ seen.add(source);
37
+ out.push({ source, source_scope: getSourceScope(source), reason: "account_level_source" });
38
+ }
39
+ return out.sort((a, b) => a.source.localeCompare(b.source));
40
+ }
41
+
42
+ module.exports = {
43
+ getSourceScope,
44
+ isAccountLevelSource,
45
+ normalizeUsageScope,
46
+ filterRowsByUsageScope,
47
+ listExcludedSources,
48
+ };
@@ -0,0 +1,215 @@
1
+ const cp = require("node:child_process");
2
+ const fssync = require("node:fs");
3
+ const { promisify } = require("node:util");
4
+
5
+ const warnedSqliteReadFailures = new Set();
6
+
7
+ function isDebugEnabled(env = process.env) {
8
+ const value = String((env && env.TOKENUSAGE_DEBUG) || "").toLowerCase();
9
+ return value === "1" || value === "true";
10
+ }
11
+
12
+ function formatError(err) {
13
+ if (!err) return "unknown error";
14
+ return err && err.message ? err.message : String(err);
15
+ }
16
+
17
+ function warnSqliteUnavailable({ dbPath, label, cliError, nodeSqliteError, env, stderr }) {
18
+ const key = `${label || "SQLite"}:${dbPath || ""}`;
19
+ if (warnedSqliteReadFailures.has(key)) return;
20
+ warnedSqliteReadFailures.add(key);
21
+
22
+ const out = stderr && typeof stderr.write === "function" ? stderr : process.stderr;
23
+ const displayLabel = label || "local";
24
+ out.write(
25
+ `[tokenusage] Cannot read ${displayLabel} SQLite database. Install sqlite3 CLI and add it to PATH, or use Node.js 22+ with node:sqlite support. Path: ${dbPath}\n`,
26
+ );
27
+ if (isDebugEnabled(env)) {
28
+ out.write(`[tokenusage] sqlite3 CLI failed: ${formatError(cliError)}\n`);
29
+ out.write(`[tokenusage] node:sqlite failed: ${formatError(nodeSqliteError)}\n`);
30
+ }
31
+ }
32
+
33
+ function readSqliteRowsWithCli(dbPath, sql, { execFileSync, timeout, maxBuffer, readOnly }) {
34
+ const args = readOnly ? ["-readonly", "-json", dbPath, sql] : ["-json", dbPath, sql];
35
+ const raw = execFileSync("sqlite3", args, {
36
+ windowsHide: true,
37
+ encoding: "utf8",
38
+ maxBuffer,
39
+ timeout,
40
+ stdio: ["pipe", "pipe", "pipe"],
41
+ });
42
+ if (!raw || !raw.trim()) return [];
43
+ const rows = JSON.parse(raw);
44
+ return Array.isArray(rows) ? rows : [];
45
+ }
46
+
47
+ function isSqliteCliUnavailable(err) {
48
+ const message = formatError(err).toLowerCase();
49
+ return (
50
+ err?.code === "ENOENT" ||
51
+ message.includes("spawn sqlite3 enoent") ||
52
+ message.includes("sqlite3 enoent") ||
53
+ message.includes("not recognized as an internal or external command")
54
+ );
55
+ }
56
+
57
+ function isNodeSqliteUnavailable(err) {
58
+ const message = formatError(err).toLowerCase();
59
+ return (
60
+ message.includes("no such built-in module") ||
61
+ message.includes("cannot find module 'node:sqlite'") ||
62
+ message.includes('cannot find module "node:sqlite"') ||
63
+ message.includes("node:sqlite databasesync is unavailable")
64
+ );
65
+ }
66
+
67
+ function readSqliteRowsWithNode(dbPath, sql, { requireFn }) {
68
+ const { DatabaseSync } = requireFn("node:sqlite");
69
+ if (typeof DatabaseSync !== "function") {
70
+ throw new Error("node:sqlite DatabaseSync is unavailable");
71
+ }
72
+ const db = new DatabaseSync(dbPath, { readOnly: true });
73
+ try {
74
+ const rows = db.prepare(sql).all();
75
+ return Array.isArray(rows) ? rows : [];
76
+ } finally {
77
+ db.close();
78
+ }
79
+ }
80
+
81
+ function readSqliteJsonRows(dbPath, sql, options = {}) {
82
+ if (!dbPath || !sql) return [];
83
+ try {
84
+ if (!fssync.existsSync(dbPath)) return [];
85
+ } catch (_e) {
86
+ return [];
87
+ }
88
+ const execFileSync = options.execFileSync || cp.execFileSync;
89
+ const requireFn = options.requireFn || require;
90
+ const env = options.env || process.env;
91
+ const timeout = Number.isFinite(options.timeout) ? options.timeout : 30_000;
92
+ const maxBuffer = Number.isFinite(options.maxBuffer) ? options.maxBuffer : 50 * 1024 * 1024;
93
+ const label = options.label || "local";
94
+
95
+ let cliError = null;
96
+ try {
97
+ return readSqliteRowsWithCli(dbPath, sql, { execFileSync, timeout, maxBuffer, readOnly: Boolean(options.readOnly) });
98
+ } catch (err) {
99
+ cliError = err;
100
+ }
101
+
102
+ let nodeSqliteError = null;
103
+ try {
104
+ return readSqliteRowsWithNode(dbPath, sql, { requireFn });
105
+ } catch (err) {
106
+ nodeSqliteError = err;
107
+ }
108
+
109
+ if (isSqliteCliUnavailable(cliError) && isNodeSqliteUnavailable(nodeSqliteError)) {
110
+ warnSqliteUnavailable({
111
+ dbPath,
112
+ label,
113
+ cliError,
114
+ nodeSqliteError,
115
+ env,
116
+ stderr: options.stderr,
117
+ });
118
+ }
119
+ if (options.throwOnReadFailure) {
120
+ const err = new Error(
121
+ `Cannot read ${label} SQLite database at ${dbPath}: ${formatError(cliError)}; ${formatError(nodeSqliteError)}`,
122
+ );
123
+ err.cliError = cliError;
124
+ err.nodeSqliteError = nodeSqliteError;
125
+ throw err;
126
+ }
127
+ return [];
128
+ }
129
+
130
+ async function readSqliteRowsWithCliAsync(dbPath, sql, { execFile, timeout, maxBuffer, readOnly }) {
131
+ const args = readOnly ? ["-readonly", "-json", dbPath, sql] : ["-json", dbPath, sql];
132
+ const { stdout } = await execFile("sqlite3", args, {
133
+ windowsHide: true,
134
+ encoding: "utf8",
135
+ maxBuffer,
136
+ timeout,
137
+ });
138
+ if (!stdout || !stdout.trim()) return [];
139
+ const rows = JSON.parse(stdout);
140
+ return Array.isArray(rows) ? rows : [];
141
+ }
142
+
143
+ // Async twin of readSqliteJsonRows for hot paths that must not block the event
144
+ // loop (e.g. the usage-limits poll — see the "limits 路径 spawnSync 冻结全端点"
145
+ // lesson). The CLI path runs via async execFile; the node:sqlite fallback is
146
+ // synchronous (no async API exists), but it only runs when the sqlite3 CLI is
147
+ // absent — uncommon on macOS/Linux, where the async path keeps the loop free.
148
+ async function readSqliteJsonRowsAsync(dbPath, sql, options = {}) {
149
+ if (!dbPath || !sql) return [];
150
+ try {
151
+ if (!fssync.existsSync(dbPath)) return [];
152
+ } catch (_e) {
153
+ return [];
154
+ }
155
+ const execFile = options.execFile || promisify(cp.execFile);
156
+ const requireFn = options.requireFn || require;
157
+ const env = options.env || process.env;
158
+ const timeout = Number.isFinite(options.timeout) ? options.timeout : 30_000;
159
+ const maxBuffer = Number.isFinite(options.maxBuffer) ? options.maxBuffer : 50 * 1024 * 1024;
160
+ const label = options.label || "local";
161
+
162
+ let cliError = null;
163
+ try {
164
+ return await readSqliteRowsWithCliAsync(dbPath, sql, { execFile, timeout, maxBuffer, readOnly: Boolean(options.readOnly) });
165
+ } catch (err) {
166
+ cliError = err;
167
+ }
168
+
169
+ let nodeSqliteError = null;
170
+ try {
171
+ return readSqliteRowsWithNode(dbPath, sql, { requireFn });
172
+ } catch (err) {
173
+ nodeSqliteError = err;
174
+ }
175
+
176
+ if (isSqliteCliUnavailable(cliError) && isNodeSqliteUnavailable(nodeSqliteError)) {
177
+ warnSqliteUnavailable({
178
+ dbPath,
179
+ label,
180
+ cliError,
181
+ nodeSqliteError,
182
+ env,
183
+ stderr: options.stderr,
184
+ });
185
+ }
186
+ if (options.throwOnReadFailure) {
187
+ const err = new Error(
188
+ `Cannot read ${label} SQLite database at ${dbPath}: ${formatError(cliError)}; ${formatError(nodeSqliteError)}`,
189
+ );
190
+ err.cliError = cliError;
191
+ err.nodeSqliteError = nodeSqliteError;
192
+ throw err;
193
+ }
194
+ return [];
195
+ }
196
+
197
+ function readSqliteFirstValue(dbPath, sql, column, options = {}) {
198
+ const rows = readSqliteJsonRows(dbPath, sql, options);
199
+ const row = rows[0];
200
+ if (!row || typeof row !== "object") return null;
201
+ const key = typeof column === "string" && column.length > 0 ? column : Object.keys(row)[0];
202
+ const value = row[key];
203
+ return typeof value === "string" ? value.trim() : value == null ? null : String(value).trim();
204
+ }
205
+
206
+ function resetSqliteReaderWarningsForTests() {
207
+ warnedSqliteReadFailures.clear();
208
+ }
209
+
210
+ module.exports = {
211
+ readSqliteJsonRows,
212
+ readSqliteJsonRowsAsync,
213
+ readSqliteFirstValue,
214
+ resetSqliteReaderWarningsForTests,
215
+ };
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+
3
+ const path = require("node:path");
4
+
5
+ const pkg = require("../../package.json");
6
+ const { readJson, writeJson } = require("./fs");
7
+
8
+ const STAR_CTA_URL = "https://github.com/baiwumm/token-usage";
9
+ const STAR_CTA_STATE_FILE = "star-cta.json";
10
+
11
+ function isTruthyFlag(value) {
12
+ if (typeof value !== "string") return false;
13
+ const normalized = value.trim().toLowerCase();
14
+ return normalized === "1" || normalized === "true" || normalized === "yes";
15
+ }
16
+
17
+ function isInteractiveCli({ stdout = process.stdout, env = process.env } = {}) {
18
+ if (!stdout?.isTTY) return false;
19
+ if (env?.NODE_TEST_CONTEXT !== undefined) return false;
20
+ if (isTruthyFlag(env?.CI)) return false;
21
+ if (isTruthyFlag(env?.TOKENUSAGE_NO_STAR_PROMPT)) return false;
22
+
23
+ const shell = String(env?.TOKENUSAGE_APP_SHELL || "").trim().toLowerCase();
24
+ if (shell && shell !== "cli") return false;
25
+ return true;
26
+ }
27
+
28
+ async function maybeShowStarCta({
29
+ trackerDir,
30
+ stdout = process.stdout,
31
+ env = process.env,
32
+ nowMs = Date.now(),
33
+ version = pkg.version,
34
+ readJsonFn = readJson,
35
+ writeJsonFn = writeJson,
36
+ } = {}) {
37
+ if (!trackerDir) return { shown: false, reason: "no-tracker-dir" };
38
+ if (!isInteractiveCli({ stdout, env })) {
39
+ return { shown: false, reason: "non-interactive" };
40
+ }
41
+
42
+ const statePath = path.join(trackerDir, STAR_CTA_STATE_FILE);
43
+ const state = await readJsonFn(statePath);
44
+ if (state?.shown_at) return { shown: false, reason: "already-shown" };
45
+
46
+ try {
47
+ await writeJsonFn(statePath, {
48
+ shown_at: new Date(nowMs).toISOString(),
49
+ version: String(version || "").slice(0, 32),
50
+ });
51
+ } catch (_error) {
52
+ // Do not print a prompt that we cannot remember; otherwise a read-only
53
+ // install would show it on every launch.
54
+ return { shown: false, reason: "state-write-failed" };
55
+ }
56
+
57
+ stdout.write(
58
+ [
59
+ " ⭐ If Token Usage helps you understand where your tokens go,",
60
+ " a GitHub Star helps more developers find it:",
61
+ ` ${STAR_CTA_URL}`,
62
+ "",
63
+ ].join("\n"),
64
+ );
65
+ return { shown: true, reason: "shown" };
66
+ }
67
+
68
+ module.exports = {
69
+ STAR_CTA_URL,
70
+ STAR_CTA_STATE_FILE,
71
+ isInteractiveCli,
72
+ maybeShowStarCta,
73
+ };
@@ -0,0 +1,293 @@
1
+ const path = require("node:path");
2
+ const fs = require("node:fs/promises");
3
+ const crypto = require("node:crypto");
4
+
5
+ const { readJsonStrict, writeFileAtomic, chmod600IfPossible } = require("./fs");
6
+
7
+ // Manual subscription manager: user-entered billing plans (service, plan,
8
+ // auto-renew flag, next renewal/expiry timestamp). Distinct from
9
+ // subscriptions.js (auto-detected local plan tiers) and usage-limits.js
10
+ // (rate-limit window resets) — see issue #460.
11
+ const STORE_FILE = "subscription-manager.json";
12
+ const STORE_VERSION = 1;
13
+ const MAX_TEXT_LENGTH = 120;
14
+ const CYCLE_UNITS = new Set(["weekly", "monthly", "yearly"]);
15
+
16
+ function resolveSubscriptionsPath(trackerDir) {
17
+ return path.join(trackerDir, STORE_FILE);
18
+ }
19
+
20
+ function normalizeText(value, { required, field, maxLength = MAX_TEXT_LENGTH } = {}) {
21
+ if (value === null || value === undefined) {
22
+ if (required) throw new Error(`${field} is required`);
23
+ return null;
24
+ }
25
+ if (typeof value !== "string") throw new Error(`${field} must be a string`);
26
+ const trimmed = value.trim();
27
+ if (!trimmed) {
28
+ if (required) throw new Error(`${field} is required`);
29
+ return null;
30
+ }
31
+ if (trimmed.length > maxLength) {
32
+ throw new Error(`${field} must be at most ${maxLength} characters`);
33
+ }
34
+ return trimmed;
35
+ }
36
+
37
+ // Accepts epoch milliseconds or any Date-parseable string. Stored values are
38
+ // UTC ISO strings truncated to whole minutes so comparisons stay clean and a
39
+ // second-level drift between input formats never changes the billed minute.
40
+ function normalizeBillingTime(value, { field = "nextBillingAt", required = true } = {}) {
41
+ let ms;
42
+ if (value === null || value === undefined) {
43
+ if (required) throw new Error(`${field} is required`);
44
+ return null;
45
+ }
46
+ if (typeof value === "number") {
47
+ ms = value;
48
+ } else if (typeof value === "string") {
49
+ const trimmed = value.trim();
50
+ if (!trimmed) {
51
+ if (required) throw new Error(`${field} is required`);
52
+ return null;
53
+ }
54
+ ms = new Date(trimmed).getTime();
55
+ } else {
56
+ throw new Error(`${field} is required`);
57
+ }
58
+ if (!Number.isFinite(ms)) throw new Error(`${field} must be a valid date`);
59
+ return new Date(Math.floor(ms / 60000) * 60000).toISOString();
60
+ }
61
+
62
+ // Billing cycle length. Drives the progress bar span and how far an
63
+ // auto-renew subscription rolls forward after a recorded renewal passes.
64
+ // Defaults to monthly so pre-cycle records keep their original semantics.
65
+ function normalizeCycle(value) {
66
+ if (value === null || value === undefined) return "monthly";
67
+ if (typeof value !== "string" || !CYCLE_UNITS.has(value)) {
68
+ throw new Error("cycle must be one of: weekly, monthly, yearly");
69
+ }
70
+ return value;
71
+ }
72
+
73
+ function normalizeSubscriptionFields(fields) {
74
+ if (!fields || typeof fields !== "object" || Array.isArray(fields)) {
75
+ throw new Error("subscription must be an object");
76
+ }
77
+ if (typeof fields.autoRenew !== "boolean") {
78
+ throw new Error("autoRenew must be a boolean");
79
+ }
80
+ return {
81
+ service: normalizeText(fields.service, { required: true, field: "service" }),
82
+ plan: normalizeText(fields.plan ?? null, { required: false, field: "plan" }),
83
+ // Optional link to a usage-limits provider row (e.g. "codex"). The value
84
+ // is a limits provider id but is not validated against the canonical list
85
+ // here — the backend stays lenient, the dropdown constrains it in the UI.
86
+ provider: normalizeText(fields.provider ?? null, {
87
+ required: false,
88
+ field: "provider",
89
+ maxLength: 64,
90
+ }),
91
+ autoRenew: fields.autoRenew,
92
+ cycle: normalizeCycle(fields.cycle),
93
+ nextBillingAt: normalizeBillingTime(fields.nextBillingAt),
94
+ // Billing anchor: the day the subscription started. The dashboard derives
95
+ // every cycle boundary from this date, so month-end anchors (Jan 31) stay
96
+ // stable instead of drifting after the first clamped month. Optional:
97
+ // records created before the field existed fall back to a derived anchor.
98
+ startedAt:
99
+ fields.startedAt === undefined
100
+ ? null
101
+ : normalizeBillingTime(fields.startedAt, { field: "startedAt", required: false }),
102
+ };
103
+ }
104
+
105
+ function isValidStoredRecord(record) {
106
+ if (!record || typeof record !== "object" || Array.isArray(record)) return false;
107
+ if (typeof record.id !== "string" || !record.id) return false;
108
+ if (typeof record.service !== "string" || !record.service) return false;
109
+ if (typeof record.autoRenew !== "boolean") return false;
110
+ if (typeof record.nextBillingAt !== "string") return false;
111
+ return Number.isFinite(new Date(record.nextBillingAt).getTime());
112
+ }
113
+
114
+ // Read the store. Any state other than a clean file or a plainly missing one
115
+ // must never collapse into an empty store on its own: the next write would
116
+ // silently destroy every stored subscription (user-entered data that cannot
117
+ // be rebuilt from logs). Reads surface the damage as an error; only the write
118
+ // path may recover, and only after backing the original file up.
119
+ async function readStore(filePath, { forWrite = false } = {}) {
120
+ const { status, value, error } = await readJsonStrict(filePath);
121
+ if (status === "missing") {
122
+ return { store: { version: STORE_VERSION, items: [] }, needsBackup: false };
123
+ }
124
+ if (status === "error") {
125
+ // Unreadable (permissions, I/O error): refuse — a blind overwrite would
126
+ // destroy data we were never able to see.
127
+ throw new Error(`Cannot read subscription store: ${error?.message || String(error)}`);
128
+ }
129
+ if (status === "invalid" || !value || typeof value !== "object" || Array.isArray(value)) {
130
+ if (!forWrite) {
131
+ throw new Error("Subscription store is corrupted (invalid JSON)");
132
+ }
133
+ return { store: { version: STORE_VERSION, items: [] }, needsBackup: true };
134
+ }
135
+ if (!Array.isArray(value.items)) {
136
+ // Valid JSON object without a usable items array: nothing recoverable
137
+ // inside, so an empty store is honest. If the key exists with a wrong
138
+ // type, keep the file backed up before a write replaces it.
139
+ return {
140
+ store: { version: STORE_VERSION, items: [] },
141
+ needsBackup: value.items !== undefined,
142
+ };
143
+ }
144
+ const items = [];
145
+ let dropped = false;
146
+ for (const item of value.items) {
147
+ if (isValidStoredRecord(item)) {
148
+ items.push(item);
149
+ } else {
150
+ dropped = true;
151
+ }
152
+ }
153
+ const version = Number.isFinite(value.version) ? value.version : STORE_VERSION;
154
+ return { store: { version, items }, needsBackup: dropped };
155
+ }
156
+
157
+ // A write is about to replace a store that contained unreadable data — keep
158
+ // a copy around first so nothing is lost without a trace. Copy (not rename):
159
+ // if the replacement write then fails, the canonical path must still hold the
160
+ // damaged original, otherwise the next write would treat it as missing and
161
+ // start from an empty store.
162
+ async function backupDamagedStore(filePath) {
163
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
164
+ try {
165
+ await fs.copyFile(filePath, `${filePath}.corrupt-${stamp}`);
166
+ } catch (e) {
167
+ if (e?.code !== "ENOENT") {
168
+ throw new Error(`Cannot back up the damaged subscription store: ${e?.message || String(e)}`);
169
+ }
170
+ }
171
+ }
172
+
173
+ async function loadStoreForWrite(filePath) {
174
+ const { store, needsBackup } = await readStore(filePath, { forWrite: true });
175
+ if (needsBackup) await backupDamagedStore(filePath);
176
+ return store;
177
+ }
178
+
179
+ async function writeStore(filePath, store) {
180
+ // Private from creation: the 0o600 applies to the tmp file before the
181
+ // rename, so a crash before the fallback chmod cannot leave a
182
+ // world-readable store behind.
183
+ await writeFileAtomic(filePath, JSON.stringify(store, null, 2) + "\n", { mode: 0o600 });
184
+ await chmod600IfPossible(filePath);
185
+ }
186
+
187
+ function sortByNextBillingAt(items) {
188
+ return [...items].sort((a, b) =>
189
+ new Date(a.nextBillingAt).getTime() - new Date(b.nextBillingAt).getTime(),
190
+ );
191
+ }
192
+
193
+ // One subscription per tool: the dashboard derives the subscription's name
194
+ // and inline progress row from the linked provider, so two records sharing a
195
+ // provider cannot be displayed. Enforced inside the store lock's
196
+ // read-modify-write transaction — the frontend picker cannot cover concurrent
197
+ // requests, stale pages, or direct API calls. `excludeId` lets an update
198
+ // re-save its own provider.
199
+ function assertProviderAvailable(items, provider, excludeId = null) {
200
+ if (!provider) return;
201
+ const conflict = items.find(
202
+ (item) => item.provider === provider && item.id !== excludeId,
203
+ );
204
+ if (conflict) {
205
+ throw new Error(
206
+ `Provider "${provider}" already has a subscription (${conflict.id})`,
207
+ );
208
+ }
209
+ }
210
+
211
+ // In-process FIFO queue per store file. Every mutation is a full
212
+ // read-modify-write transaction; without serialization two concurrent writes
213
+ // read the same snapshot and the later one silently drops the earlier change
214
+ // (issue: 30 concurrent creates survived as a single record). The queue keeps
215
+ // independent store files unblocked while ordering operations on the same one.
216
+ const storeLocks = new Map();
217
+
218
+ function withStoreLock(filePath, operation) {
219
+ const previous = storeLocks.get(filePath) || Promise.resolve();
220
+ // Run even if the previous transaction rejected; its error already reached
221
+ // its own caller and must not wedge the queue.
222
+ const run = previous.then(operation, operation);
223
+ storeLocks.set(filePath, run.then(() => undefined, () => undefined));
224
+ return run;
225
+ }
226
+
227
+ async function listSubscriptions({ trackerDir }) {
228
+ const { store } = await readStore(resolveSubscriptionsPath(trackerDir));
229
+ return sortByNextBillingAt(store.items);
230
+ }
231
+
232
+ async function createSubscription({ trackerDir, fields }) {
233
+ // Validate before taking the lock so a bad payload never queues a write.
234
+ const normalized = normalizeSubscriptionFields(fields);
235
+ const filePath = resolveSubscriptionsPath(trackerDir);
236
+ return withStoreLock(filePath, async () => {
237
+ const now = new Date().toISOString();
238
+ const record = {
239
+ id: crypto.randomUUID(),
240
+ ...normalized,
241
+ createdAt: now,
242
+ updatedAt: now,
243
+ };
244
+ const store = await loadStoreForWrite(filePath);
245
+ assertProviderAvailable(store.items, normalized.provider);
246
+ store.items.push(record);
247
+ await writeStore(filePath, store);
248
+ return record;
249
+ });
250
+ }
251
+
252
+ async function updateSubscription({ trackerDir, id, fields }) {
253
+ if (typeof id !== "string" || !id) throw new Error("id is required");
254
+ const filePath = resolveSubscriptionsPath(trackerDir);
255
+ return withStoreLock(filePath, async () => {
256
+ const store = await loadStoreForWrite(filePath);
257
+ const index = store.items.findIndex((item) => item.id === id);
258
+ if (index === -1) throw new Error("Subscription not found");
259
+ const existing = store.items[index];
260
+ // Merge over the existing record so callers may send only changed fields.
261
+ const merged = normalizeSubscriptionFields({ ...existing, ...(fields || {}) });
262
+ assertProviderAvailable(store.items, merged.provider, id);
263
+ const record = {
264
+ ...existing,
265
+ ...merged,
266
+ updatedAt: new Date().toISOString(),
267
+ };
268
+ store.items[index] = record;
269
+ await writeStore(filePath, store);
270
+ return record;
271
+ });
272
+ }
273
+
274
+ async function deleteSubscription({ trackerDir, id }) {
275
+ if (typeof id !== "string" || !id) throw new Error("id is required");
276
+ const filePath = resolveSubscriptionsPath(trackerDir);
277
+ return withStoreLock(filePath, async () => {
278
+ const store = await loadStoreForWrite(filePath);
279
+ const index = store.items.findIndex((item) => item.id === id);
280
+ if (index === -1) throw new Error("Subscription not found");
281
+ store.items.splice(index, 1);
282
+ await writeStore(filePath, store);
283
+ return { removed: true };
284
+ });
285
+ }
286
+
287
+ module.exports = {
288
+ listSubscriptions,
289
+ createSubscription,
290
+ updateSubscription,
291
+ deleteSubscription,
292
+ resolveSubscriptionsPath,
293
+ };