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,141 +1,141 @@
1
- const fs = require("node:fs");
2
- const path = require("node:path");
3
- const crypto = require("node:crypto");
4
- const {
5
- resolveRuntimeConfig,
6
- normalizeInstanceBaseUrl,
7
- } = require("./runtime-config");
8
-
9
- function validBinding(binding) {
10
- return ["userId", "baseUrl", "machineId"].every(
11
- (key) => typeof binding?.[key] === "string" && binding[key].length > 0,
12
- );
13
- }
14
-
15
- function readCloudDeviceTokenEntry(filePath) {
16
- let fd;
17
- try {
18
- fd = fs.openSync(filePath, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
19
- if (!fs.fstatSync(fd).isFile()) return null;
20
- fs.fchmodSync(fd, 0o600);
21
- const data = JSON.parse(fs.readFileSync(fd, "utf8"));
22
- if (data?.version === 1 && validBinding(data) && typeof data.token === "string" && data.token) {
23
- return {
24
- version: 1,
25
- userId: data.userId,
26
- baseUrl: data.baseUrl,
27
- machineId: data.machineId,
28
- token: data.token,
29
- };
30
- }
31
- } catch { /* missing or invalid cache requires ordinary issuance */ }
32
- finally { if (fd !== undefined) fs.closeSync(fd); }
33
- return null;
34
- }
35
-
36
- // A successful auth refresh supplies the binding. This file never imports a
37
- // CLI config token, whose owner may belong to another signed-in account.
38
- function createCloudDeviceTokenStore(filePath) {
39
- let loaded = false;
40
- let entry = null;
41
-
42
- function load() {
43
- if (loaded) return entry;
44
- loaded = true;
45
- entry = readCloudDeviceTokenEntry(filePath);
46
- return entry;
47
- }
48
-
49
- function clear(binding) {
50
- if (binding && (!validBinding(binding) || ["userId", "baseUrl", "machineId"].some((key) => load()?.[key] !== binding[key]))) return;
51
- loaded = true;
52
- entry = null;
53
- try { fs.unlinkSync(filePath); } catch { /* cache may not exist */ }
54
- }
55
-
56
- return {
57
- get(binding) {
58
- if (!validBinding(binding)) return null;
59
- const value = load();
60
- if (!value) return null;
61
- if (value.userId !== binding.userId) {
62
- clear();
63
- return null;
64
- }
65
- return value.baseUrl === binding.baseUrl && value.machineId === binding.machineId ? value.token : null;
66
- },
67
- set(binding, token) {
68
- if (!validBinding(binding) || typeof token !== "string" || !token) return false;
69
- const value = { version: 1, userId: binding.userId, baseUrl: binding.baseUrl, machineId: binding.machineId, token };
70
- if (JSON.stringify(load()) === JSON.stringify(value)) return true;
71
- loaded = true;
72
- entry = value;
73
- const tmp = `${filePath}.tmp.${crypto.randomUUID()}`;
74
- try {
75
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
76
- fs.writeFileSync(tmp, JSON.stringify(value) + "\n", { encoding: "utf8", mode: 0o600, flag: "wx" });
77
- fs.renameSync(tmp, filePath);
78
- return true;
79
- } catch {
80
- try { fs.unlinkSync(tmp); } catch { /* no temporary file to remove */ }
81
- return false;
82
- }
83
- },
84
- invalidate(token) {
85
- if (typeof token === "string" && token && load()?.token === token) clear();
86
- },
87
- clear,
88
- };
89
- }
90
-
91
- /**
92
- * Presence for status/doctor/diagnostics — same stores upload uses.
93
- * Prefer config/env/cli (resolveRuntimeConfig); else cloud-device-token.json
94
- * when baseUrl (+ machineId when known) match. Never clears the store.
95
- */
96
- function resolveDeviceTokenPresence({
97
- trackerDir,
98
- config = {},
99
- runtime = null,
100
- env = process.env,
101
- } = {}) {
102
- const resolved = runtime || resolveRuntimeConfig({ config, env });
103
- if (typeof resolved?.deviceToken === "string" && resolved.deviceToken.trim()) {
104
- return {
105
- set: true,
106
- source: resolved.sources?.deviceToken || "config",
107
- };
108
- }
109
-
110
- if (!trackerDir || typeof trackerDir !== "string") {
111
- return { set: false, source: null };
112
- }
113
-
114
- const entry = readCloudDeviceTokenEntry(path.join(trackerDir, "cloud-device-token.json"));
115
- if (!entry) return { set: false, source: null };
116
-
117
- const expectedBase =
118
- normalizeInstanceBaseUrl(resolved?.baseUrl) ||
119
- (typeof resolved?.baseUrl === "string" ? resolved.baseUrl.trim() : "") ||
120
- normalizeInstanceBaseUrl(config.baseUrl) ||
121
- (typeof config.baseUrl === "string" ? config.baseUrl.trim() : "");
122
- if (expectedBase && entry.baseUrl !== expectedBase) {
123
- return { set: false, source: null };
124
- }
125
-
126
- const expectedMachine =
127
- typeof config.machineId === "string" && config.machineId.trim()
128
- ? config.machineId.trim()
129
- : null;
130
- if (expectedMachine && entry.machineId !== expectedMachine) {
131
- return { set: false, source: null };
132
- }
133
-
134
- return { set: true, source: "cloud-device-token" };
135
- }
136
-
137
- module.exports = {
138
- createCloudDeviceTokenStore,
139
- resolveDeviceTokenPresence,
140
- readCloudDeviceTokenEntry,
141
- };
1
+ const fs = require("node:fs");
2
+ const path = require("node:path");
3
+ const crypto = require("node:crypto");
4
+ const {
5
+ resolveRuntimeConfig,
6
+ normalizeInstanceBaseUrl,
7
+ } = require("./runtime-config");
8
+
9
+ function validBinding(binding) {
10
+ return ["userId", "baseUrl", "machineId"].every(
11
+ (key) => typeof binding?.[key] === "string" && binding[key].length > 0,
12
+ );
13
+ }
14
+
15
+ function readCloudDeviceTokenEntry(filePath) {
16
+ let fd;
17
+ try {
18
+ fd = fs.openSync(filePath, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
19
+ if (!fs.fstatSync(fd).isFile()) return null;
20
+ fs.fchmodSync(fd, 0o600);
21
+ const data = JSON.parse(fs.readFileSync(fd, "utf8"));
22
+ if (data?.version === 1 && validBinding(data) && typeof data.token === "string" && data.token) {
23
+ return {
24
+ version: 1,
25
+ userId: data.userId,
26
+ baseUrl: data.baseUrl,
27
+ machineId: data.machineId,
28
+ token: data.token,
29
+ };
30
+ }
31
+ } catch { /* missing or invalid cache requires ordinary issuance */ }
32
+ finally { if (fd !== undefined) fs.closeSync(fd); }
33
+ return null;
34
+ }
35
+
36
+ // A successful auth refresh supplies the binding. This file never imports a
37
+ // CLI config token, whose owner may belong to another signed-in account.
38
+ function createCloudDeviceTokenStore(filePath) {
39
+ let loaded = false;
40
+ let entry = null;
41
+
42
+ function load() {
43
+ if (loaded) return entry;
44
+ loaded = true;
45
+ entry = readCloudDeviceTokenEntry(filePath);
46
+ return entry;
47
+ }
48
+
49
+ function clear(binding) {
50
+ if (binding && (!validBinding(binding) || ["userId", "baseUrl", "machineId"].some((key) => load()?.[key] !== binding[key]))) return;
51
+ loaded = true;
52
+ entry = null;
53
+ try { fs.unlinkSync(filePath); } catch { /* cache may not exist */ }
54
+ }
55
+
56
+ return {
57
+ get(binding) {
58
+ if (!validBinding(binding)) return null;
59
+ const value = load();
60
+ if (!value) return null;
61
+ if (value.userId !== binding.userId) {
62
+ clear();
63
+ return null;
64
+ }
65
+ return value.baseUrl === binding.baseUrl && value.machineId === binding.machineId ? value.token : null;
66
+ },
67
+ set(binding, token) {
68
+ if (!validBinding(binding) || typeof token !== "string" || !token) return false;
69
+ const value = { version: 1, userId: binding.userId, baseUrl: binding.baseUrl, machineId: binding.machineId, token };
70
+ if (JSON.stringify(load()) === JSON.stringify(value)) return true;
71
+ loaded = true;
72
+ entry = value;
73
+ const tmp = `${filePath}.tmp.${crypto.randomUUID()}`;
74
+ try {
75
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
76
+ fs.writeFileSync(tmp, JSON.stringify(value) + "\n", { encoding: "utf8", mode: 0o600, flag: "wx" });
77
+ fs.renameSync(tmp, filePath);
78
+ return true;
79
+ } catch {
80
+ try { fs.unlinkSync(tmp); } catch { /* no temporary file to remove */ }
81
+ return false;
82
+ }
83
+ },
84
+ invalidate(token) {
85
+ if (typeof token === "string" && token && load()?.token === token) clear();
86
+ },
87
+ clear,
88
+ };
89
+ }
90
+
91
+ /**
92
+ * Presence for status/doctor/diagnostics — same stores upload uses.
93
+ * Prefer config/env/cli (resolveRuntimeConfig); else cloud-device-token.json
94
+ * when baseUrl (+ machineId when known) match. Never clears the store.
95
+ */
96
+ function resolveDeviceTokenPresence({
97
+ trackerDir,
98
+ config = {},
99
+ runtime = null,
100
+ env = process.env,
101
+ } = {}) {
102
+ const resolved = runtime || resolveRuntimeConfig({ config, env });
103
+ if (typeof resolved?.deviceToken === "string" && resolved.deviceToken.trim()) {
104
+ return {
105
+ set: true,
106
+ source: resolved.sources?.deviceToken || "config",
107
+ };
108
+ }
109
+
110
+ if (!trackerDir || typeof trackerDir !== "string") {
111
+ return { set: false, source: null };
112
+ }
113
+
114
+ const entry = readCloudDeviceTokenEntry(path.join(trackerDir, "cloud-device-token.json"));
115
+ if (!entry) return { set: false, source: null };
116
+
117
+ const expectedBase =
118
+ normalizeInstanceBaseUrl(resolved?.baseUrl) ||
119
+ (typeof resolved?.baseUrl === "string" ? resolved.baseUrl.trim() : "") ||
120
+ normalizeInstanceBaseUrl(config.baseUrl) ||
121
+ (typeof config.baseUrl === "string" ? config.baseUrl.trim() : "");
122
+ if (expectedBase && entry.baseUrl !== expectedBase) {
123
+ return { set: false, source: null };
124
+ }
125
+
126
+ const expectedMachine =
127
+ typeof config.machineId === "string" && config.machineId.trim()
128
+ ? config.machineId.trim()
129
+ : null;
130
+ if (expectedMachine && entry.machineId !== expectedMachine) {
131
+ return { set: false, source: null };
132
+ }
133
+
134
+ return { set: true, source: "cloud-device-token" };
135
+ }
136
+
137
+ module.exports = {
138
+ createCloudDeviceTokenStore,
139
+ resolveDeviceTokenPresence,
140
+ readCloudDeviceTokenEntry,
141
+ };
@@ -1,14 +1,14 @@
1
- const fs = require("node:fs");
2
- const path = require("node:path");
3
-
4
- // The dashboard mirrors saved choices here. Missing or invalid preferences
5
- // must never enable automatic uploads merely because credentials exist.
6
- function readCloudSyncEnabled(trackerDir) {
7
- try {
8
- return JSON.parse(fs.readFileSync(path.join(trackerDir, "cloud-sync-pref.json"), "utf8"))?.enabled === true;
9
- } catch {
10
- return false;
11
- }
12
- }
13
-
14
- module.exports = { readCloudSyncEnabled };
1
+ const fs = require("node:fs");
2
+ const path = require("node:path");
3
+
4
+ // The dashboard mirrors saved choices here. Missing or invalid preferences
5
+ // must never enable automatic uploads merely because credentials exist.
6
+ function readCloudSyncEnabled(trackerDir) {
7
+ try {
8
+ return JSON.parse(fs.readFileSync(path.join(trackerDir, "cloud-sync-pref.json"), "utf8"))?.enabled === true;
9
+ } catch {
10
+ return false;
11
+ }
12
+ }
13
+
14
+ module.exports = { readCloudSyncEnabled };
@@ -1,115 +1,115 @@
1
- const fs = require("node:fs");
2
- const fsp = require("node:fs/promises");
3
- const path = require("node:path");
4
- const crypto = require("node:crypto");
5
- const { openLock, writeFileAtomic } = require("./fs");
6
- const { functionUrlFor, fetchFunctionResponse } = require("./function-url");
7
-
8
- const MARKER = "cloud-usage-reset.json";
9
- const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
10
- const failure = (code, status = 409) => Object.assign(new Error(code), { code, status });
11
- const sameBase = (a, b) => String(a).replace(/\/$/, "") === String(b).replace(/\/$/, "");
12
-
13
- function readCloudUsageReset(trackerDir) {
14
- let raw;
15
- try { raw = fs.readFileSync(path.join(trackerDir, MARKER), "utf8"); }
16
- catch (error) { if (error.code === "ENOENT") return null; throw error; }
17
- let value;
18
- try { value = JSON.parse(raw); } catch { throw failure("cloud_usage_reset_invalid_state"); }
19
- if (value?.version !== 1 || !UUID.test(value.operationId) || !UUID.test(value.deviceId) ||
20
- !UUID.test(value.ownerId) || !/^https?:\/\//.test(value.baseUrl || "") ||
21
- !["prepared", "uploading"].includes(value.phase)) throw failure("cloud_usage_reset_invalid_state");
22
- return value;
23
- }
24
-
25
- function cloudUsageResetBlocksUpload(trackerDir, { ownerId, baseUrl, deviceId } = {}) {
26
- try {
27
- const marker = readCloudUsageReset(trackerDir);
28
- return Boolean(marker && (marker.phase === "prepared" || marker.ownerId !== ownerId ||
29
- !sameBase(marker.baseUrl, baseUrl) || (deviceId && marker.deviceId !== deviceId)));
30
- }
31
- catch { return true; }
32
- }
33
-
34
- async function writeMarker(trackerDir, marker) {
35
- await writeFileAtomic(path.join(trackerDir, MARKER), JSON.stringify(marker) + "\n", { mode: 0o600 });
36
- }
37
-
38
- async function requestReset({ baseUrl, anonKey, authorization, body, fetchImpl = fetchFunctionResponse }) {
39
- const response = await fetchImpl(functionUrlFor(baseUrl, "token-usage-device-usage-reset"), {
40
- method: "POST",
41
- headers: { "Content-Type": "application/json", Accept: "application/json", Authorization: `Bearer ${authorization}`,
42
- ...(anonKey ? { apikey: anonKey } : {}) },
43
- signal: AbortSignal.timeout(60_000),
44
- body: JSON.stringify(body),
45
- });
46
- const data = await response.json().catch(() => ({}));
47
- if (!response.ok || data.ok !== true) throw failure(data.code || "cloud_usage_reset_failed", response.status || 502);
48
- if (data.operation_id !== body.operation_id) throw failure("cloud_usage_reset_invalid_response", 502);
49
- return data;
50
- }
51
-
52
- // Called only after the local bridge has bound the JWT to its current device.
53
- // The marker precedes the remote mutation: an interrupted request must retry the
54
- // same operation, never clear already-replayed history a second time.
55
- async function resetCloudDeviceUsage({ trackerDir, ownerId, deviceId, baseUrl, anonKey, accessToken,
56
- isCurrent = () => true, fetchImpl }) {
57
- if (!UUID.test(ownerId) || !UUID.test(deviceId) || !accessToken) throw failure("auth_required", 401);
58
- const lock = await openLock(path.join(trackerDir, "sync.lock"), { quietIfLocked: true });
59
- if (!lock) throw failure("cloud_usage_reset_sync_busy");
60
- try {
61
- if (!isCurrent()) throw failure("auth_session_changed");
62
- let marker = readCloudUsageReset(trackerDir);
63
- const newOperation = !marker;
64
- if (marker && (marker.ownerId !== ownerId || marker.deviceId !== deviceId || !sameBase(marker.baseUrl, baseUrl))) {
65
- throw failure("cloud_usage_reset_owner_changed");
66
- }
67
- if (marker?.phase === "uploading") return { ok: true, operation_id: marker.operationId, status: "uploading" };
68
- if (!marker) {
69
- marker = { version: 1, operationId: crypto.randomUUID(), ownerId, deviceId, baseUrl, phase: "prepared" };
70
- await writeMarker(trackerDir, marker);
71
- }
72
- if (!isCurrent()) throw failure("auth_session_changed");
73
- const result = await requestReset({ baseUrl, anonKey, authorization: accessToken, fetchImpl,
74
- body: { action: "reset", device_id: deviceId, operation_id: marker.operationId } }).catch(async error => {
75
- // A definitive first-request rejection did not erase anything. Unknown
76
- // outcomes and retries retain their operation so they cannot erase twice.
77
- if (newOperation && [400, 401, 403, 404, 409, 422].includes(error.status)) {
78
- await fsp.unlink(path.join(trackerDir, MARKER));
79
- }
80
- throw error;
81
- });
82
- if (result.device_id !== deviceId || !["reset", "complete"].includes(result.status)) {
83
- throw failure("cloud_usage_reset_invalid_response", 502);
84
- }
85
- if (!isCurrent()) throw failure("auth_session_changed");
86
- await writeFileAtomic(path.join(trackerDir, "queue.state.json"),
87
- JSON.stringify({ offset: 0, updatedAt: new Date().toISOString() }) + "\n", { mode: 0o600 });
88
- await fsp.unlink(path.join(trackerDir, "upload.throttle.json")).catch(error => { if (error.code !== "ENOENT") throw error; });
89
- marker.phase = "uploading";
90
- await writeMarker(trackerDir, marker);
91
- return { ...result, status: "uploading" };
92
- } finally { await lock.release(); }
93
- }
94
-
95
- // sync owns sync.lock here. Only its fully acknowledged queue can finish the
96
- // operation; a partial batch/checkpoint or another account leaves it pending.
97
- async function finishCloudDeviceUsageReset({ trackerDir, ownerId, deviceId, baseUrl, anonKey, deviceToken, fetchImpl }) {
98
- const marker = readCloudUsageReset(trackerDir);
99
- if (!marker || marker.phase !== "uploading" || marker.ownerId !== ownerId || (deviceId && marker.deviceId !== deviceId) || !sameBase(marker.baseUrl, baseUrl)) return false;
100
- if (!deviceToken) return false;
101
- const queuePath = path.join(trackerDir, "queue.jsonl");
102
- const size = await fsp.stat(queuePath).then(stat => stat.size).catch(error => { if (error.code === "ENOENT") return 0; throw error; });
103
- let offset;
104
- try { offset = JSON.parse(await fsp.readFile(path.join(trackerDir, "queue.state.json"), "utf8")).offset; }
105
- catch { throw failure("cloud_usage_reset_invalid_offset"); }
106
- if (!Number.isSafeInteger(offset) || offset < 0 || offset > size) throw failure("cloud_usage_reset_invalid_offset");
107
- if (offset !== size) return false;
108
- const result = await requestReset({ baseUrl, anonKey, authorization: deviceToken, fetchImpl,
109
- body: { action: "refresh", operation_id: marker.operationId } });
110
- if (result.status !== "complete" || result.device_id !== marker.deviceId) throw failure("cloud_usage_reset_invalid_response", 502);
111
- await fsp.unlink(path.join(trackerDir, MARKER));
112
- return true;
113
- }
114
-
115
- module.exports = { readCloudUsageReset, cloudUsageResetBlocksUpload, resetCloudDeviceUsage, finishCloudDeviceUsageReset };
1
+ const fs = require("node:fs");
2
+ const fsp = require("node:fs/promises");
3
+ const path = require("node:path");
4
+ const crypto = require("node:crypto");
5
+ const { openLock, writeFileAtomic } = require("./fs");
6
+ const { functionUrlFor, fetchFunctionResponse } = require("./function-url");
7
+
8
+ const MARKER = "cloud-usage-reset.json";
9
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
10
+ const failure = (code, status = 409) => Object.assign(new Error(code), { code, status });
11
+ const sameBase = (a, b) => String(a).replace(/\/$/, "") === String(b).replace(/\/$/, "");
12
+
13
+ function readCloudUsageReset(trackerDir) {
14
+ let raw;
15
+ try { raw = fs.readFileSync(path.join(trackerDir, MARKER), "utf8"); }
16
+ catch (error) { if (error.code === "ENOENT") return null; throw error; }
17
+ let value;
18
+ try { value = JSON.parse(raw); } catch { throw failure("cloud_usage_reset_invalid_state"); }
19
+ if (value?.version !== 1 || !UUID.test(value.operationId) || !UUID.test(value.deviceId) ||
20
+ !UUID.test(value.ownerId) || !/^https?:\/\//.test(value.baseUrl || "") ||
21
+ !["prepared", "uploading"].includes(value.phase)) throw failure("cloud_usage_reset_invalid_state");
22
+ return value;
23
+ }
24
+
25
+ function cloudUsageResetBlocksUpload(trackerDir, { ownerId, baseUrl, deviceId } = {}) {
26
+ try {
27
+ const marker = readCloudUsageReset(trackerDir);
28
+ return Boolean(marker && (marker.phase === "prepared" || marker.ownerId !== ownerId ||
29
+ !sameBase(marker.baseUrl, baseUrl) || (deviceId && marker.deviceId !== deviceId)));
30
+ }
31
+ catch { return true; }
32
+ }
33
+
34
+ async function writeMarker(trackerDir, marker) {
35
+ await writeFileAtomic(path.join(trackerDir, MARKER), JSON.stringify(marker) + "\n", { mode: 0o600 });
36
+ }
37
+
38
+ async function requestReset({ baseUrl, anonKey, authorization, body, fetchImpl = fetchFunctionResponse }) {
39
+ const response = await fetchImpl(functionUrlFor(baseUrl, "token-usage-device-usage-reset"), {
40
+ method: "POST",
41
+ headers: { "Content-Type": "application/json", Accept: "application/json", Authorization: `Bearer ${authorization}`,
42
+ ...(anonKey ? { apikey: anonKey } : {}) },
43
+ signal: AbortSignal.timeout(60_000),
44
+ body: JSON.stringify(body),
45
+ });
46
+ const data = await response.json().catch(() => ({}));
47
+ if (!response.ok || data.ok !== true) throw failure(data.code || "cloud_usage_reset_failed", response.status || 502);
48
+ if (data.operation_id !== body.operation_id) throw failure("cloud_usage_reset_invalid_response", 502);
49
+ return data;
50
+ }
51
+
52
+ // Called only after the local bridge has bound the JWT to its current device.
53
+ // The marker precedes the remote mutation: an interrupted request must retry the
54
+ // same operation, never clear already-replayed history a second time.
55
+ async function resetCloudDeviceUsage({ trackerDir, ownerId, deviceId, baseUrl, anonKey, accessToken,
56
+ isCurrent = () => true, fetchImpl }) {
57
+ if (!UUID.test(ownerId) || !UUID.test(deviceId) || !accessToken) throw failure("auth_required", 401);
58
+ const lock = await openLock(path.join(trackerDir, "sync.lock"), { quietIfLocked: true });
59
+ if (!lock) throw failure("cloud_usage_reset_sync_busy");
60
+ try {
61
+ if (!isCurrent()) throw failure("auth_session_changed");
62
+ let marker = readCloudUsageReset(trackerDir);
63
+ const newOperation = !marker;
64
+ if (marker && (marker.ownerId !== ownerId || marker.deviceId !== deviceId || !sameBase(marker.baseUrl, baseUrl))) {
65
+ throw failure("cloud_usage_reset_owner_changed");
66
+ }
67
+ if (marker?.phase === "uploading") return { ok: true, operation_id: marker.operationId, status: "uploading" };
68
+ if (!marker) {
69
+ marker = { version: 1, operationId: crypto.randomUUID(), ownerId, deviceId, baseUrl, phase: "prepared" };
70
+ await writeMarker(trackerDir, marker);
71
+ }
72
+ if (!isCurrent()) throw failure("auth_session_changed");
73
+ const result = await requestReset({ baseUrl, anonKey, authorization: accessToken, fetchImpl,
74
+ body: { action: "reset", device_id: deviceId, operation_id: marker.operationId } }).catch(async error => {
75
+ // A definitive first-request rejection did not erase anything. Unknown
76
+ // outcomes and retries retain their operation so they cannot erase twice.
77
+ if (newOperation && [400, 401, 403, 404, 409, 422].includes(error.status)) {
78
+ await fsp.unlink(path.join(trackerDir, MARKER));
79
+ }
80
+ throw error;
81
+ });
82
+ if (result.device_id !== deviceId || !["reset", "complete"].includes(result.status)) {
83
+ throw failure("cloud_usage_reset_invalid_response", 502);
84
+ }
85
+ if (!isCurrent()) throw failure("auth_session_changed");
86
+ await writeFileAtomic(path.join(trackerDir, "queue.state.json"),
87
+ JSON.stringify({ offset: 0, updatedAt: new Date().toISOString() }) + "\n", { mode: 0o600 });
88
+ await fsp.unlink(path.join(trackerDir, "upload.throttle.json")).catch(error => { if (error.code !== "ENOENT") throw error; });
89
+ marker.phase = "uploading";
90
+ await writeMarker(trackerDir, marker);
91
+ return { ...result, status: "uploading" };
92
+ } finally { await lock.release(); }
93
+ }
94
+
95
+ // sync owns sync.lock here. Only its fully acknowledged queue can finish the
96
+ // operation; a partial batch/checkpoint or another account leaves it pending.
97
+ async function finishCloudDeviceUsageReset({ trackerDir, ownerId, deviceId, baseUrl, anonKey, deviceToken, fetchImpl }) {
98
+ const marker = readCloudUsageReset(trackerDir);
99
+ if (!marker || marker.phase !== "uploading" || marker.ownerId !== ownerId || (deviceId && marker.deviceId !== deviceId) || !sameBase(marker.baseUrl, baseUrl)) return false;
100
+ if (!deviceToken) return false;
101
+ const queuePath = path.join(trackerDir, "queue.jsonl");
102
+ const size = await fsp.stat(queuePath).then(stat => stat.size).catch(error => { if (error.code === "ENOENT") return 0; throw error; });
103
+ let offset;
104
+ try { offset = JSON.parse(await fsp.readFile(path.join(trackerDir, "queue.state.json"), "utf8")).offset; }
105
+ catch { throw failure("cloud_usage_reset_invalid_offset"); }
106
+ if (!Number.isSafeInteger(offset) || offset < 0 || offset > size) throw failure("cloud_usage_reset_invalid_offset");
107
+ if (offset !== size) return false;
108
+ const result = await requestReset({ baseUrl, anonKey, authorization: deviceToken, fetchImpl,
109
+ body: { action: "refresh", operation_id: marker.operationId } });
110
+ if (result.status !== "complete" || result.device_id !== marker.deviceId) throw failure("cloud_usage_reset_invalid_response", 502);
111
+ await fsp.unlink(path.join(trackerDir, MARKER));
112
+ return true;
113
+ }
114
+
115
+ module.exports = { readCloudUsageReset, cloudUsageResetBlocksUpload, resetCloudDeviceUsage, finishCloudDeviceUsageReset };