tokenusage-cli 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/CHANGELOG.md +46 -19
  2. package/LICENSE +22 -22
  3. package/README.md +123 -94
  4. package/THIRD_PARTY_NOTICES.md +140 -140
  5. package/bin/tokenusage.js +69 -69
  6. package/package.json +59 -59
  7. package/src/cli.js +146 -134
  8. package/src/commands/device-login.js +205 -205
  9. package/src/commands/diagnostics.js +38 -38
  10. package/src/commands/doctor.js +110 -110
  11. package/src/commands/init.js +2484 -2436
  12. package/src/commands/pause.js +77 -0
  13. package/src/commands/sessions.js +29 -29
  14. package/src/commands/status.js +1758 -1747
  15. package/src/commands/sync.js +8048 -7934
  16. package/src/commands/uninstall.js +322 -312
  17. package/src/lib/account-usage-dedup.js +267 -267
  18. package/src/lib/antigravity-paths.js +48 -48
  19. package/src/lib/ark-agent-plan-limits.js +438 -438
  20. package/src/lib/ark-coding-plan-limits.js +537 -537
  21. package/src/lib/async-queue-reader.js +138 -138
  22. package/src/lib/atomic-json.js +27 -27
  23. package/src/lib/bearer-token.js +11 -11
  24. package/src/lib/categorizer-utils.js +232 -232
  25. package/src/lib/claude-categorizer.js +1343 -1343
  26. package/src/lib/claude-config.js +279 -279
  27. package/src/lib/claude-user-identity.js +56 -56
  28. package/src/lib/cli-ui.js +179 -179
  29. package/src/lib/cloud-account.js +541 -541
  30. package/src/lib/cloud-device-token.js +141 -141
  31. package/src/lib/cloud-sync-prefs.js +14 -14
  32. package/src/lib/cloud-usage-reset.js +115 -115
  33. package/src/lib/codex-config.js +595 -595
  34. package/src/lib/codex-context-breakdown.js +806 -806
  35. package/src/lib/codex-model-attribution.js +128 -128
  36. package/src/lib/codex-rollout-parser.js +1471 -1471
  37. package/src/lib/codex-service-tier.js +49 -49
  38. package/src/lib/codex-token-refresh.js +140 -140
  39. package/src/lib/codex-token-usage.js +195 -195
  40. package/src/lib/codex-usage-record.js +195 -195
  41. package/src/lib/collection-pause.js +77 -0
  42. package/src/lib/command-runner.js +313 -313
  43. package/src/lib/commandcode-limits.js +317 -317
  44. package/src/lib/context-health.js +124 -124
  45. package/src/lib/cursor-config.js +605 -605
  46. package/src/lib/cursor-store.js +1918 -1918
  47. package/src/lib/debug-flags.js +7 -7
  48. package/src/lib/devin-limits.js +249 -249
  49. package/src/lib/devin-usage.js +212 -212
  50. package/src/lib/diagnostics.js +383 -383
  51. package/src/lib/doctor.js +385 -385
  52. package/src/lib/dumate.js +95 -95
  53. package/src/lib/fs.js +455 -455
  54. package/src/lib/function-url.js +14 -14
  55. package/src/lib/gemini-config.js +291 -291
  56. package/src/lib/git-outcomes.js +243 -243
  57. package/src/lib/grok-context-breakdown.js +890 -890
  58. package/src/lib/grok-hook.js +360 -360
  59. package/src/lib/grok-limits.js +865 -865
  60. package/src/lib/grok-usage.js +98 -98
  61. package/src/lib/heatmap-compact.js +114 -114
  62. package/src/lib/ingest-sanitize.js +41 -41
  63. package/src/lib/init-flow.js +42 -42
  64. package/src/lib/install-resolver.js +170 -170
  65. package/src/lib/jsonl-lines.js +134 -134
  66. package/src/lib/kimi-model-repair.js +173 -173
  67. package/src/lib/kimi-profile.js +61 -61
  68. package/src/lib/kimi-session.js +216 -216
  69. package/src/lib/local-api.js +3588 -3588
  70. package/src/lib/machine-id.js +238 -238
  71. package/src/lib/multi-install-parser.js +113 -113
  72. package/src/lib/notify-command.js +38 -38
  73. package/src/lib/omp-hook.js +589 -589
  74. package/src/lib/openclaw-cli.js +104 -104
  75. package/src/lib/openclaw-hook.js +375 -375
  76. package/src/lib/openclaw-session-plugin.js +560 -560
  77. package/src/lib/opencode-config.js +121 -121
  78. package/src/lib/opencode-go-limits.js +807 -807
  79. package/src/lib/outcomes-engine.js +253 -253
  80. package/src/lib/passive-mode.js +219 -219
  81. package/src/lib/pet-packages.js +722 -722
  82. package/src/lib/pricing/curated-overrides.json +822 -822
  83. package/src/lib/pricing/index.js +379 -379
  84. package/src/lib/pricing/litellm-fetcher.js +172 -172
  85. package/src/lib/pricing/matcher.js +456 -456
  86. package/src/lib/pricing/seed-snapshot.json +1 -1
  87. package/src/lib/progress.js +76 -76
  88. package/src/lib/project-usage-purge.js +117 -117
  89. package/src/lib/prompt.js +24 -24
  90. package/src/lib/provider-status.js +104 -104
  91. package/src/lib/proxy-env.js +489 -489
  92. package/src/lib/proxy-settings.js +163 -163
  93. package/src/lib/qoder-cn-cli-limits.js +119 -119
  94. package/src/lib/qoder-limits.js +880 -880
  95. package/src/lib/quiet-warnings.js +26 -26
  96. package/src/lib/rollout.js +26005 -25966
  97. package/src/lib/runtime-config.js +9 -4
  98. package/src/lib/scan-roots.js +277 -277
  99. package/src/lib/scheduled-task.js +145 -0
  100. package/src/lib/sentry.js +231 -231
  101. package/src/lib/session-analytics.js +2972 -2972
  102. package/src/lib/session-performance.js +237 -237
  103. package/src/lib/session-upload.js +379 -379
  104. package/src/lib/skill-usage.js +267 -267
  105. package/src/lib/skills-manager.js +1591 -1591
  106. package/src/lib/source-metadata.js +48 -48
  107. package/src/lib/sqlite-reader.js +215 -215
  108. package/src/lib/star-cta.js +73 -73
  109. package/src/lib/subscription-manager.js +293 -293
  110. package/src/lib/subscriptions.js +508 -508
  111. package/src/lib/sync-report.js +138 -0
  112. package/src/lib/telemetry.js +193 -193
  113. package/src/lib/tracker-paths.js +16 -16
  114. package/src/lib/trae-cn-config.js +548 -548
  115. package/src/lib/trae-db.js +127 -127
  116. package/src/lib/trae-snapshot.js +230 -230
  117. package/src/lib/trae-sqlite.js +143 -143
  118. package/src/lib/trae-usage.js +121 -121
  119. package/src/lib/upload-queue.js +134 -134
  120. package/src/lib/upload-throttle.js +171 -171
  121. package/src/lib/usage-limits.js +4552 -4552
  122. package/src/lib/wrapped-aggregator.js +236 -236
  123. package/src/lib/wsl-probe.js +281 -281
  124. package/src/lib/zcode-limits.js +1172 -1172
  125. package/src/lib/zcode-reset-credits.js +66 -66
  126. package/test/audit-fixes.test.js +200 -0
  127. package/test/cli-smoke.test.js +53 -53
  128. package/test/collection-controls.test.js +210 -0
  129. package/test/ingest-sanitize.test.js +162 -162
  130. package/test/quiet-warnings.test.js +53 -53
  131. package/test/session-upload.test.js +427 -427
@@ -1,293 +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
- };
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
+ };